<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <title>Deep learning in Data Science</title>
 <link href="https://deep-learning-self-learning.pages.dev/atom.xml" rel="self"/>
 <link href="https://deep-learning-self-learning.pages.dev/"/>
 <updated>2026-12-05T04:03:04+00:00</updated>
 <id>https://deep-learning-self-learning.pages.dev</id>
 <author>
   <name>Nguyen Le Linh</name>
   <email>nglelinh@gmail.com</email>
 </author>

 
 <entry>
   <title>Author details</title>
   <link href="https://deep-learning-self-learning.pages.dev/home/author-details/"/>
   <updated>2021-05-20T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/home/author-details</id>
   <content type="html">
</content>
 </entry>
 
 <entry>
   <title>Thông tin tác giả</title>
   <link href="https://deep-learning-self-learning.pages.dev/home/author-details-vi/"/>
   <updated>2021-05-20T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/home/author-details-vi</id>
   <content type="html">
</content>
 </entry>
 
 <entry>
   <title>References and Resources</title>
   <link href="https://deep-learning-self-learning.pages.dev/reference/26_reference/"/>
   <updated>2021-03-28T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/reference/26_reference</id>
   <content type="html">&lt;h2 id=&quot;essential-deep-learning-books&quot;&gt;Essential Deep Learning Books&lt;/h2&gt;

&lt;h3 id=&quot;primary-textbooks&quot;&gt;Primary Textbooks&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Goodfellow, I., Bengio, Y., and Courville, A. (2016).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;http://www.deeplearningbook.org/&quot;&gt;Deep Learning&lt;/a&gt;&lt;/em&gt;. MIT Press.&lt;br /&gt;
The definitive textbook on deep learning theory and mathematics.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Géron, A. (2022).&lt;/strong&gt; &lt;em&gt;Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (3rd Edition)&lt;/em&gt;. O’Reilly Media.&lt;br /&gt;
Practical guide to implementing deep learning models.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Prince, S. J. D. (2023).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://udlbook.github.io/udlbook/&quot;&gt;Understanding Deep Learning&lt;/a&gt;&lt;/em&gt;. MIT Press.&lt;br /&gt;
Modern introduction with excellent visualizations.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;MIT Deep Learning Book.&lt;/strong&gt; From MIT 6.S191 course.&lt;br /&gt;
Rigorous academic treatment of deep learning fundamentals.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Practice supplement:&lt;/strong&gt; Kashani, S., and Ivry, A. &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;Deep Learning Interviews&lt;/a&gt;&lt;/em&gt; (arXiv:2201.00650). Free solved interview / exam problems. Course track: lesson &lt;strong&gt;01-98&lt;/strong&gt;. GitHub: &lt;a href=&quot;https://github.com/BoltzmannEntropy/interviews.ai&quot;&gt;interviews.ai&lt;/a&gt;. Download the PDF from arXiv; this site does not reprint the question bank.&lt;/p&gt;

&lt;h3 id=&quot;domain-specific-books&quot;&gt;Domain-Specific Books&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Shanmugamani, R. (2018).&lt;/strong&gt; &lt;em&gt;Deep Learning for Computer Vision&lt;/em&gt;. Packt Publishing.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tunstall, L., von Werra, L., and Wolf, T. (2022).&lt;/strong&gt; &lt;em&gt;Natural Language Processing with Transformers&lt;/em&gt;. O’Reilly Media.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Sutton, R. S. and Barto, A. G. (2018).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;http://incompleteideas.net/book/the-book-2nd.html&quot;&gt;Reinforcement Learning: An Introduction (2nd Edition)&lt;/a&gt;&lt;/em&gt;. MIT Press.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;foundational-papers&quot;&gt;Foundational Papers&lt;/h2&gt;

&lt;h3 id=&quot;neural-networks-and-training&quot;&gt;Neural Networks and Training&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Rumelhart, D. E., Hinton, G. E., and Williams, R. J. (1986).&lt;/strong&gt; “Learning representations by back-propagating errors.” &lt;em&gt;Nature&lt;/em&gt;, 323(6088), 533-536.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;LeCun, Y., Bottou, L., Bengio, Y., and Haffner, P. (1998).&lt;/strong&gt; “Gradient-based learning applied to document recognition.” &lt;em&gt;Proceedings of the IEEE&lt;/em&gt;, 86(11), 2278-2324.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Glorot, X. and Bengio, Y. (2010).&lt;/strong&gt; “Understanding the difficulty of training deep feedforward neural networks.” &lt;em&gt;AISTATS&lt;/em&gt;.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;optimization-and-regularization&quot;&gt;Optimization and Regularization&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kingma, D. P. and Ba, J. (2015).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1412.6980&quot;&gt;Adam: A Method for Stochastic Optimization&lt;/a&gt;&lt;/em&gt;. ICLR.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ioffe, S. and Szegedy, C. (2015).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1502.03167&quot;&gt;Batch Normalization: Accelerating Deep Network Training&lt;/a&gt;&lt;/em&gt;. ICML.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Srivastava, N., et al. (2014).&lt;/strong&gt; “Dropout: A Simple Way to Prevent Neural Networks from Overfitting.” &lt;em&gt;JMLR&lt;/em&gt;, 15, 1929-1958.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;convolutional-neural-networks&quot;&gt;Convolutional Neural Networks&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Krizhevsky, A., Sutskever, I., and Hinton, G. E. (2012).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks&quot;&gt;ImageNet Classification with Deep Convolutional Neural Networks&lt;/a&gt;&lt;/em&gt;. NeurIPS.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Simonyan, K. and Zisserman, A. (2015).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.1556&quot;&gt;Very Deep Convolutional Networks for Large-Scale Image Recognition&lt;/a&gt;&lt;/em&gt;. ICLR.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;He, K., et al. (2016).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.03385&quot;&gt;Deep Residual Learning for Image Recognition&lt;/a&gt;&lt;/em&gt;. CVPR.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;recurrent-networks-and-sequence-models&quot;&gt;Recurrent Networks and Sequence Models&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hochreiter, S. and Schmidhuber, J. (1997).&lt;/strong&gt; “Long Short-Term Memory.” &lt;em&gt;Neural Computation&lt;/em&gt;, 9(8), 1735-1780.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Cho, K., et al. (2014).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1406.1078&quot;&gt;Learning Phrase Representations using RNN Encoder-Decoder&lt;/a&gt;&lt;/em&gt;. EMNLP.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;attention-and-transformers&quot;&gt;Attention and Transformers&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vaswani, A., et al. (2017).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need&lt;/a&gt;&lt;/em&gt;. NeurIPS.&lt;br /&gt;
   The foundational Transformer paper.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Devlin, J., et al. (2019).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;BERT: Pre-training of Deep Bidirectional Transformers&lt;/a&gt;&lt;/em&gt;. NAACL.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Radford, A., et al. (2019).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf&quot;&gt;Language Models are Unsupervised Multitask Learners&lt;/a&gt;&lt;/em&gt;. OpenAI.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;generative-models&quot;&gt;Generative Models&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Goodfellow, I., et al. (2014).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1406.2661&quot;&gt;Generative Adversarial Networks&lt;/a&gt;&lt;/em&gt;. NeurIPS.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kingma, D. P. and Welling, M. (2014).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.6114&quot;&gt;Auto-Encoding Variational Bayes&lt;/a&gt;&lt;/em&gt;. ICLR.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Karras, T., et al. (2019).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1812.04948&quot;&gt;A Style-Based Generator Architecture for GANs&lt;/a&gt;&lt;/em&gt;. CVPR.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;reinforcement-learning&quot;&gt;Reinforcement Learning&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Mnih, V., et al. (2015).&lt;/strong&gt; “Human-level control through deep reinforcement learning.” &lt;em&gt;Nature&lt;/em&gt;, 518(7540), 529-533.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Silver, D., et al. (2017).&lt;/strong&gt; “Mastering the game of Go without human knowledge.” &lt;em&gt;Nature&lt;/em&gt;, 550(7676), 354-359.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;online-courses-and-resources&quot;&gt;Online Courses and Resources&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Stanford CS231n:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;http://cs231n.stanford.edu/&quot;&gt;Convolutional Neural Networks for Visual Recognition&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Stanford CS224n:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;http://web.stanford.edu/class/cs224n/&quot;&gt;Natural Language Processing with Deep Learning&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;MIT 6.S191:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;http://introtodeeplearning.com/&quot;&gt;Introduction to Deep Learning&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Fast.ai:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://www.fast.ai/&quot;&gt;Practical Deep Learning for Coders&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;online-resources&quot;&gt;Online Resources&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;ArXiv.org:&lt;/strong&gt; Pre-print server for latest research papers&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Papers with Code:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://paperswithcode.com/&quot;&gt;paperwithcode.com&lt;/a&gt;&lt;/em&gt; - Papers with implementations&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Distill.pub:&lt;/strong&gt; Interactive machine learning research explanations&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;PyTorch Tutorials:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://pytorch.org/tutorials/&quot;&gt;pytorch.org/tutorials&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;TensorFlow Tutorials:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://www.tensorflow.org/tutorials&quot;&gt;tensorflow.org/tutorials&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;mathematical-foundations&quot;&gt;Mathematical Foundations&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Wikipedia.&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Backpropagation&quot;&gt;Backpropagation&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Wikipedia.&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Gradient_descent&quot;&gt;Gradient descent&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Wikipedia.&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Automatic_differentiation&quot;&gt;Automatic differentiation&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Wikipedia.&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Cross_entropy&quot;&gt;Cross entropy&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Wikipedia.&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Softmax_function&quot;&gt;Softmax function&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;For the most up-to-date resources and research, check:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/&quot;&gt;ArXiv.org&lt;/a&gt; for latest papers&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://paperswithcode.com/&quot;&gt;Papers with Code&lt;/a&gt; for implementations&lt;/li&gt;
  &lt;li&gt;Course GitHub repository for code examples and notebooks&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;videos-by-chapter&quot;&gt;Videos by chapter&lt;/h2&gt;

&lt;p&gt;One verified video per chapter. Open the matching lesson for the full set of 1–3 videos and the note on what to watch.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;00.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=gq0m_2Glz0g&quot;&gt;MaDL - Introduction&lt;/a&gt; — Tübingen Machine Learning, English. Math the rest of the course assumes: vectors, calculus, and probability in one short tour.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;01.&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. A layered network as a function approximator, the picture Chapter 1 starts from.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;02.&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. From one neuron to a stack of layers.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;03.&lt;/strong&gt; [Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, English. Training as walking downhill on a cost.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;04.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, English. Convolution as a sliding local mix.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;05.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. A hidden state as memory for sequences.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;06.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, English. The LSTM cell state and its gates.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;07.&lt;/strong&gt; [Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, English. Queries, keys, and values.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;08.&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. The transformer block.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;09.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=D8PJAL-MZv8&quot;&gt;Dropout Regularization (C2W1L06)&lt;/a&gt; — DeepLearningAI, English. Dropout as a regularizer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;10.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, English. The Adam update.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;11.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. The 2024 map of generative models.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;12.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, English. Encode, bottleneck, decode.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;13.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, English. A latent distribution, not a point.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;14.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, English. The generator–discriminator game.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;15.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, English. Fine-tuning a pretrained network.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;16.&lt;/strong&gt; [Contrastive Learning with SimCLR&lt;/td&gt;
          &lt;td&gt;Deep Learning Animated](https://www.youtube.com/watch?v=UqJauYELn6c) — Deepia, English. Contrastive self-supervision.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;17.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=svn9-xV7wjk&quot;&gt;How YOLO Object Detection Works&lt;/a&gt; — DeepBean, English. One-pass object detection.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;18.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=viZrOnJclY0&quot;&gt;Word Embedding and Word2Vec, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. A word as a learned vector.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;19.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=SJo7vPgRlBQ&quot;&gt;Mel Frequency Cepstral Coefficients (MFCC) Explained&lt;/a&gt; — DataMListic, English. MFCCs, the features a speech model consumes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;20.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=2pWv7GOvuf0&quot;&gt;RL Course by David Silver - Lecture 1: Introduction to Reinforcement Learning&lt;/a&gt; — Google DeepMind, English. Agents, rewards, and policies.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;21.&lt;/strong&gt; [Lecture 14&lt;/td&gt;
          &lt;td&gt;Deep Reinforcement Learning](https://www.youtube.com/watch?v=lvoHnicueoE) — Stanford University School of Engineering, English. DQN and policy gradients.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;22.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=eGoszzMkGfU&quot;&gt;Graph Neural Networks Explained: A Clear Guide to GNN Basics &amp;amp; Models&lt;/a&gt; — IBM Technology, English. Message passing on a graph.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;23.&lt;/strong&gt; [Lecture 15&lt;/td&gt;
          &lt;td&gt;Efficient Methods and Hardware for Deep Learning](https://www.youtube.com/watch?v=eZdOkDtYMoo) — Stanford University School of Engineering, English. Pruning, quantization, and distillation.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;24.&lt;/strong&gt; [Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, English. Looking inside a trained network.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;25.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=N1fbskTpwZ0&quot;&gt;MIT 6.S191 (2024): Language Models and New Frontiers&lt;/a&gt; — Alexander Amini, English. What the 2024 frontier lecture still treats as open.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;26.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, English. What a large language model is.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Tài liệu tham khảo và nguồn học liệu</title>
   <link href="https://deep-learning-self-learning.pages.dev/reference/26_reference-vi/"/>
   <updated>2021-03-28T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/reference/26_reference-vi</id>
   <content type="html">&lt;h2 id=&quot;sách-học-sâu-thiết-yếu&quot;&gt;Sách học sâu thiết yếu&lt;/h2&gt;

&lt;h3 id=&quot;giáo-trình-chính&quot;&gt;Giáo trình chính&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Goodfellow, I., Bengio, Y., and Courville, A. (2016).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;http://www.deeplearningbook.org/&quot;&gt;Deep Learning&lt;/a&gt;&lt;/em&gt;. MIT Press.&lt;br /&gt;
Giáo trình chuẩn về lý thuyết và toán học học sâu.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Géron, A. (2022).&lt;/strong&gt; &lt;em&gt;Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (3rd Edition)&lt;/em&gt;. O’Reilly Media.&lt;br /&gt;
Hướng dẫn thực hành cài đặt mô hình học sâu.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Prince, S. J. D. (2023).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://udlbook.github.io/udlbook/&quot;&gt;Understanding Deep Learning&lt;/a&gt;&lt;/em&gt;. MIT Press.&lt;br /&gt;
Giới thiệu hiện đại, giàu minh họa trực quan.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;MIT Deep Learning Book.&lt;/strong&gt; Từ khóa học MIT 6.S191.&lt;br /&gt;
Cách tiếp cận học thuật chặt chẽ về nền tảng học sâu.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Bổ sung luyện tập:&lt;/strong&gt; Kashani, S., và Ivry, A. &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;Deep Learning Interviews&lt;/a&gt;&lt;/em&gt; (arXiv:2201.00650). Bài toán phỏng vấn / thi cử đã giải, miễn phí. Lộ trình khóa: bài &lt;strong&gt;01-98&lt;/strong&gt;. GitHub: &lt;a href=&quot;https://github.com/BoltzmannEntropy/interviews.ai&quot;&gt;interviews.ai&lt;/a&gt;. Tải PDF từ arXiv; trang này không in lại ngân hàng câu hỏi.&lt;/p&gt;

&lt;h3 id=&quot;sách-theo-lĩnh-vực&quot;&gt;Sách theo lĩnh vực&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Shanmugamani, R. (2018).&lt;/strong&gt; &lt;em&gt;Deep Learning for Computer Vision&lt;/em&gt;. Packt Publishing.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tunstall, L., von Werra, L., and Wolf, T. (2022).&lt;/strong&gt; &lt;em&gt;Natural Language Processing with Transformers&lt;/em&gt;. O’Reilly Media.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Sutton, R. S. and Barto, A. G. (2018).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;http://incompleteideas.net/book/the-book-2nd.html&quot;&gt;Reinforcement Learning: An Introduction (2nd Edition)&lt;/a&gt;&lt;/em&gt;. MIT Press.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;các-bài-báo-nền-tảng&quot;&gt;Các bài báo nền tảng&lt;/h2&gt;

&lt;h3 id=&quot;mạng-neuron-và-huấn-luyện&quot;&gt;Mạng neuron và huấn luyện&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Rumelhart, D. E., Hinton, G. E., and Williams, R. J. (1986).&lt;/strong&gt; “Learning representations by back-propagating errors.” &lt;em&gt;Nature&lt;/em&gt;, 323(6088), 533-536.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;LeCun, Y., Bottou, L., Bengio, Y., and Haffner, P. (1998).&lt;/strong&gt; “Gradient-based learning applied to document recognition.” &lt;em&gt;Proceedings of the IEEE&lt;/em&gt;, 86(11), 2278-2324.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Glorot, X. and Bengio, Y. (2010).&lt;/strong&gt; “Understanding the difficulty of training deep feedforward neural networks.” &lt;em&gt;AISTATS&lt;/em&gt;.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;tối-ưu-và-chính-quy-hóa&quot;&gt;Tối ưu và chính quy hóa&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kingma, D. P. and Ba, J. (2015).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1412.6980&quot;&gt;Adam: A Method for Stochastic Optimization&lt;/a&gt;&lt;/em&gt;. ICLR.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ioffe, S. and Szegedy, C. (2015).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1502.03167&quot;&gt;Batch Normalization: Accelerating Deep Network Training&lt;/a&gt;&lt;/em&gt;. ICML.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Srivastava, N., et al. (2014).&lt;/strong&gt; “Dropout: A Simple Way to Prevent Neural Networks from Overfitting.” &lt;em&gt;JMLR&lt;/em&gt;, 15, 1929-1958.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;mạng-neuron-tích-chập&quot;&gt;Mạng neuron tích chập&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Krizhevsky, A., Sutskever, I., and Hinton, G. E. (2012).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks&quot;&gt;ImageNet Classification with Deep Convolutional Neural Networks&lt;/a&gt;&lt;/em&gt;. NeurIPS.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Simonyan, K. and Zisserman, A. (2015).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.1556&quot;&gt;Very Deep Convolutional Networks for Large-Scale Image Recognition&lt;/a&gt;&lt;/em&gt;. ICLR.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;He, K., et al. (2016).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.03385&quot;&gt;Deep Residual Learning for Image Recognition&lt;/a&gt;&lt;/em&gt;. CVPR.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;mạng-hồi-quy-và-mô-hình-chuỗi&quot;&gt;Mạng hồi quy và mô hình chuỗi&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hochreiter, S. and Schmidhuber, J. (1997).&lt;/strong&gt; “Long Short-Term Memory.” &lt;em&gt;Neural Computation&lt;/em&gt;, 9(8), 1735-1780.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Cho, K., et al. (2014).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1406.1078&quot;&gt;Learning Phrase Representations using RNN Encoder-Decoder&lt;/a&gt;&lt;/em&gt;. EMNLP.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;attention-và-transformer&quot;&gt;Attention và Transformer&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vaswani, A., et al. (2017).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need&lt;/a&gt;&lt;/em&gt;. NeurIPS.&lt;br /&gt;
   Bài báo nền tảng về kiến trúc Transformer.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Devlin, J., et al. (2019).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;BERT: Pre-training of Deep Bidirectional Transformers&lt;/a&gt;&lt;/em&gt;. NAACL.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Radford, A., et al. (2019).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf&quot;&gt;Language Models are Unsupervised Multitask Learners&lt;/a&gt;&lt;/em&gt;. OpenAI.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;mô-hình-sinh&quot;&gt;Mô hình sinh&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Goodfellow, I., et al. (2014).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1406.2661&quot;&gt;Generative Adversarial Networks&lt;/a&gt;&lt;/em&gt;. NeurIPS.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kingma, D. P. and Welling, M. (2014).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.6114&quot;&gt;Auto-Encoding Variational Bayes&lt;/a&gt;&lt;/em&gt;. ICLR.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Karras, T., et al. (2019).&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://arxiv.org/abs/1812.04948&quot;&gt;A Style-Based Generator Architecture for GANs&lt;/a&gt;&lt;/em&gt;. CVPR.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;học-tăng-cường&quot;&gt;Học tăng cường&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Mnih, V., et al. (2015).&lt;/strong&gt; “Human-level control through deep reinforcement learning.” &lt;em&gt;Nature&lt;/em&gt;, 518(7540), 529-533.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Silver, D., et al. (2017).&lt;/strong&gt; “Mastering the game of Go without human knowledge.” &lt;em&gt;Nature&lt;/em&gt;, 550(7676), 354-359.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;khóa-học-và-nguồn-trực-tuyến&quot;&gt;Khóa học và nguồn trực tuyến&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Stanford CS231n:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;http://cs231n.stanford.edu/&quot;&gt;Convolutional Neural Networks for Visual Recognition&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Stanford CS224n:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;http://web.stanford.edu/class/cs224n/&quot;&gt;Natural Language Processing with Deep Learning&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;MIT 6.S191:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;http://introtodeeplearning.com/&quot;&gt;Introduction to Deep Learning&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Fast.ai:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://www.fast.ai/&quot;&gt;Practical Deep Learning for Coders&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tài-nguyên-trực-tuyến&quot;&gt;Tài nguyên trực tuyến&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;ArXiv.org:&lt;/strong&gt; Máy chủ preprint cho các bài báo nghiên cứu mới nhất&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Papers with Code:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://paperswithcode.com/&quot;&gt;paperwithcode.com&lt;/a&gt;&lt;/em&gt; — bài báo kèm cài đặt tham chiếu&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Distill.pub:&lt;/strong&gt; Giải thích nghiên cứu học máy mang tính tương tác&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;PyTorch Tutorials:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://pytorch.org/tutorials/&quot;&gt;pytorch.org/tutorials&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;TensorFlow Tutorials:&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://www.tensorflow.org/tutorials&quot;&gt;tensorflow.org/tutorials&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;nền-tảng-toán-học&quot;&gt;Nền tảng toán học&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Wikipedia.&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Backpropagation&quot;&gt;Backpropagation&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Wikipedia.&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Gradient_descent&quot;&gt;Gradient descent&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Wikipedia.&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Automatic_differentiation&quot;&gt;Automatic differentiation&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Wikipedia.&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Cross_entropy&quot;&gt;Cross entropy&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Wikipedia.&lt;/strong&gt; &lt;em&gt;&lt;a href=&quot;https://en.wikipedia.org/wiki/Softmax_function&quot;&gt;Softmax function&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;p&gt;Để cập nhật tài liệu và nghiên cứu mới nhất, nên theo dõi:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/&quot;&gt;ArXiv.org&lt;/a&gt; cho bài báo mới&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://paperswithcode.com/&quot;&gt;Papers with Code&lt;/a&gt; cho cài đặt kèm paper&lt;/li&gt;
  &lt;li&gt;Kho GitHub của khóa học cho ví dụ mã và notebook&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-theo-chương&quot;&gt;Video theo chương&lt;/h2&gt;

&lt;p&gt;Một video đã kiểm tra cho mỗi chương. Mở bài tương ứng để có đủ 1–3 video và dòng ghi chú.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;00.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=gq0m_2Glz0g&quot;&gt;MaDL - Introduction&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Phần toán phần còn lại của khóa giả định: vector, giải tích và xác suất trong một tour ngắn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;01.&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Mạng xếp lớp như bộ xấp xỉ hàm, hình Chương 1 bắt đầu từ đó.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;02.&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Từ một neuron tới một chồng lớp.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;03.&lt;/strong&gt; [Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, tiếng Anh. Huấn luyện là đi xuống dốc trên một chi phí.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;04.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Tích chập như một phép trộn cục bộ trượt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;05.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Trạng thái ẩn như bộ nhớ cho chuỗi.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;06.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Trạng thái tế bào LSTM và các cổng.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;07.&lt;/strong&gt; [Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, tiếng Anh. Query, key và value.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;08.&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, tiếng Anh. Khối transformer.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;09.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=D8PJAL-MZv8&quot;&gt;Dropout Regularization (C2W1L06)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Dropout như một bộ chính quy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;10.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Phép cập nhật Adam.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;11.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Bản đồ mô hình sinh năm 2024.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;12.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, tiếng Anh. Mã hóa, nút thắt, giải mã.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;13.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, tiếng Anh. Một phân phối ẩn, không phải một điểm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;14.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, tiếng Anh. Trò chơi bộ sinh và bộ phân biệt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;15.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, tiếng Anh. Tinh chỉnh một mạng đã tiền huấn luyện.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;16.&lt;/strong&gt; [Contrastive Learning with SimCLR&lt;/td&gt;
          &lt;td&gt;Deep Learning Animated](https://www.youtube.com/watch?v=UqJauYELn6c) — Deepia, tiếng Anh. Tự giám sát tương phản.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;17.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=svn9-xV7wjk&quot;&gt;How YOLO Object Detection Works&lt;/a&gt; — DeepBean, tiếng Anh. Phát hiện đối tượng trong một lượt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;18.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=viZrOnJclY0&quot;&gt;Word Embedding and Word2Vec, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Một từ là một vector được học.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;19.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=SJo7vPgRlBQ&quot;&gt;Mel Frequency Cepstral Coefficients (MFCC) Explained&lt;/a&gt; — DataMListic, tiếng Anh. MFCC, đặc trưng một mô hình tiếng nói tiêu thụ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;20.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=2pWv7GOvuf0&quot;&gt;RL Course by David Silver - Lecture 1: Introduction to Reinforcement Learning&lt;/a&gt; — Google DeepMind, tiếng Anh. Tác tử, phần thưởng và chính sách.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;21.&lt;/strong&gt; [Lecture 14&lt;/td&gt;
          &lt;td&gt;Deep Reinforcement Learning](https://www.youtube.com/watch?v=lvoHnicueoE) — Stanford University School of Engineering, tiếng Anh. DQN và policy gradient.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;22.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=eGoszzMkGfU&quot;&gt;Graph Neural Networks Explained: A Clear Guide to GNN Basics &amp;amp; Models&lt;/a&gt; — IBM Technology, tiếng Anh. Truyền thông điệp trên đồ thị.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;23.&lt;/strong&gt; [Lecture 15&lt;/td&gt;
          &lt;td&gt;Efficient Methods and Hardware for Deep Learning](https://www.youtube.com/watch?v=eZdOkDtYMoo) — Stanford University School of Engineering, tiếng Anh. Tỉa, lượng tử hóa và chưng cất.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;24.&lt;/strong&gt; [Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, tiếng Anh. Nhìn vào trong một mạng đã huấn luyện.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;25.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=N1fbskTpwZ0&quot;&gt;MIT 6.S191 (2024): Language Models and New Frontiers&lt;/a&gt; — Alexander Amini, tiếng Anh. Những gì bài giảng biên 2024 vẫn coi là mở.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;26.&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Mô hình ngôn ngữ lớn là gì.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>Makers</title>
   <link href="https://deep-learning-self-learning.pages.dev/home/makers/"/>
   <updated>2021-02-03T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/home/makers</id>
   <content type="html">
</content>
 </entry>
 
 <entry>
   <title>Nhóm thực hiện</title>
   <link href="https://deep-learning-self-learning.pages.dev/home/makers-vi/"/>
   <updated>2021-02-03T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/home/makers-vi</id>
   <content type="html">
</content>
 </entry>
 
 <entry>
   <title>How to contribute</title>
   <link href="https://deep-learning-self-learning.pages.dev/home/link_to_how_to_contribute/"/>
   <updated>2021-01-27T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/home/link_to_how_to_contribute</id>
   <content type="html">
</content>
 </entry>
 
 <entry>
   <title>Hướng dẫn đóng góp</title>
   <link href="https://deep-learning-self-learning.pages.dev/home/link_to_how_to_contribute-vi/"/>
   <updated>2021-01-27T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/home/link_to_how_to_contribute-vi</id>
   <content type="html">
</content>
 </entry>
 
 <entry>
   <title>Giới thiệu</title>
   <link href="https://deep-learning-self-learning.pages.dev/home/introduction/"/>
   <updated>2021-01-20T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/home/introduction</id>
   <content type="html">&lt;h1 id=&quot;giới-thiệu-khóa-học&quot;&gt;Giới thiệu khóa học&lt;/h1&gt;

&lt;p&gt;Học sâu (&lt;em&gt;deep learning&lt;/em&gt;) đã trở thành công cụ trung tâm của trí tuệ nhân tạo hiện đại: nhận dạng ảnh, dịch máy, sinh nội dung, điều khiển robot và nhiều ứng dụng khác. Khóa học này được thiết kế cho &lt;strong&gt;tự học có hệ thống&lt;/strong&gt;, đi từ nền tảng toán và mạng neuron đến các kiến trúc hiện đại (CNN, RNN/LSTM, Attention, Transformer), rồi mở rộng sang mô hình sinh, học chuyển giao và các hướng ứng dụng.&lt;/p&gt;

&lt;h2 id=&quot;đối-tượng-và-cách-tiếp-cận&quot;&gt;Đối tượng và cách tiếp cận&lt;/h2&gt;

&lt;p&gt;Người học cần kiến thức cơ bản về giải tích, đại số tuyến tính, xác suất và lập trình Python. Mỗi bài được viết theo dạng &lt;strong&gt;bài giảng đầy đủ&lt;/strong&gt;: trực giác, công thức, ví dụ số, mã minh họa, bài báo gốc và các cạm bẫy thường gặp.&lt;/p&gt;

&lt;p&gt;Nội dung được tổ chức theo chương; trong mỗi chương, các bài dài được chia thành các bài nhỏ hơn để dễ theo dõi. Thanh điều hướng bên cho phép thu gọn/mở rộng chương và mục con.&lt;/p&gt;

&lt;h2 id=&quot;hai-phiên-bản-ngôn-ngữ&quot;&gt;Hai phiên bản ngôn ngữ&lt;/h2&gt;

&lt;p&gt;Toàn bộ nội dung chính có &lt;strong&gt;bản tiếng Anh&lt;/strong&gt; và &lt;strong&gt;bản tiếng Việt&lt;/strong&gt;. Hai bản khớp nhau theo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chapter&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;order&lt;/code&gt;, nên có thể chuyển ngữ ngay trên từng bài mà không mất vị trí học. Bản tiếng Việt dùng văn phong giáo trình học thuật; thuật ngữ kỹ thuật được giới thiệu bằng tiếng Việt kèm nguyên ngữ tiếng Anh khi cần.&lt;/p&gt;

&lt;h2 id=&quot;lộ-trình-gợi-ý&quot;&gt;Lộ trình gợi ý&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chương 00&lt;/strong&gt; — ôn toán nền (nếu cần).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chương 01–03&lt;/strong&gt; — học sâu là gì, mạng neuron, huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chương 04–08&lt;/strong&gt; — CNN, chuỗi, LSTM, attention, Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chương 09–10&lt;/strong&gt; — chính quy hóa và tối ưu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chương 11–15&lt;/strong&gt; — mô hình sinh và học chuyển giao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chương 16–25&lt;/strong&gt; — ứng dụng và hướng mở rộng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chương 26&lt;/strong&gt; — hub LLM chuyên biệt (toán tiền huấn luyện, prompting, căn chỉnh, phục vụ, chưng cất, sổ sách decoder hiện đại).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Luyện phỏng vấn tùy chọn: sau bài lý thuyết khớp, dùng &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) và các bài companion &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;*-98&lt;/code&gt; theo chương.&lt;/p&gt;

&lt;p&gt;Luyện phỏng vấn tùy chọn: sau bài lý thuyết khớp, dùng &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) và các bài companion &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;*-98&lt;/code&gt; theo chương.&lt;/p&gt;

&lt;p&gt;Chúc bạn học tập hiệu quả.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Introduction</title>
   <link href="https://deep-learning-self-learning.pages.dev/home/introduction-en/"/>
   <updated>2021-01-20T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/home/introduction-en</id>
   <content type="html">&lt;h1 id=&quot;course-introduction&quot;&gt;Course introduction&lt;/h1&gt;

&lt;p&gt;Deep learning is a central tool of modern artificial intelligence: vision, translation, generative media, control, and many other applications. This course is designed for &lt;strong&gt;systematic self-study&lt;/strong&gt;, moving from mathematical and neural-network foundations to modern architectures (CNNs, RNNs/LSTMs, attention, Transformers), then to generative models, transfer learning, and broader applications.&lt;/p&gt;

&lt;h2 id=&quot;audience-and-approach&quot;&gt;Audience and approach&lt;/h2&gt;

&lt;p&gt;Learners should know basic calculus, linear algebra, probability, and Python. Each lesson is written as a &lt;strong&gt;full lecture note&lt;/strong&gt;: intuition, mathematics, numerical examples, code sketches, foundational papers, and common pitfalls.&lt;/p&gt;

&lt;p&gt;Content is organized by chapter; long topics are split into smaller lessons for readability. The sidebar supports collapsing and expanding chapters and nested sections.&lt;/p&gt;

&lt;h2 id=&quot;two-language-editions&quot;&gt;Two language editions&lt;/h2&gt;

&lt;p&gt;The main curriculum is available in &lt;strong&gt;English and Vietnamese&lt;/strong&gt;. Editions are aligned by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chapter&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;order&lt;/code&gt;, so you can switch language on any lesson without losing your place. The Vietnamese edition uses academic textbook style; technical terms are introduced in Vietnamese with English glosses when helpful.&lt;/p&gt;

&lt;h2 id=&quot;suggested-path&quot;&gt;Suggested path&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chapter 00&lt;/strong&gt; — math refreshers (if needed).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chapters 01–03&lt;/strong&gt; — what deep learning is, neural nets, training.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chapters 04–08&lt;/strong&gt; — CNNs, sequences, LSTM, attention, Transformers.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chapters 09–10&lt;/strong&gt; — regularization and optimization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chapters 11–15&lt;/strong&gt; — generative models and transfer learning.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chapters 16–25&lt;/strong&gt; — applications and future directions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chapter 26&lt;/strong&gt; — dedicated LLM hub (pretraining math, prompting, alignment, serving, distillation, modern-decoder accounting).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Optional interview drill: after the matching theory lesson, use &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) and the chapter &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;*-98&lt;/code&gt; companions.&lt;/p&gt;

&lt;p&gt;Optional interview drill: after the matching theory lesson, use &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) and the chapter &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;*-98&lt;/code&gt; companions.&lt;/p&gt;

&lt;p&gt;Happy learning.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Nội dung khóa học</title>
   <link href="https://deep-learning-self-learning.pages.dev/home/contents/"/>
   <updated>2021-01-20T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/home/contents</id>
   <content type="html">&lt;p&gt;Khóa học giới thiệu toàn diện về học sâu (&lt;em&gt;deep learning&lt;/em&gt;), bao gồm nền tảng mạng neuron, các kiến trúc hiện đại (CNN, RNN, Transformer), kỹ thuật huấn luyện, mô hình sinh, ứng dụng thực tiễn trong thị giác máy tính và xử lý ngôn ngữ tự nhiên, cùng &lt;strong&gt;Chương 26&lt;/strong&gt; — hub chuyên về mô hình ngôn ngữ lớn (toán tiền huấn luyện, prompting, căn chỉnh, phục vụ, chưng cất, và sổ sách decoder hiện đại).&lt;/p&gt;

&lt;h1 id=&quot;mục-tiêu-khóa-học&quot;&gt;Mục tiêu khóa học&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Cung cấp kiến thức nền tảng về lý thuyết và thực hành học sâu, hỗ trợ việc học tập và nghiên cứu trong khoa học dữ liệu và trí tuệ nhân tạo.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Giúp người học hiểu, cài đặt và huấn luyện mạng neuron sâu từ đầu cũng như bằng các framework hiện đại.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Rèn luyện kỹ năng áp dụng học sâu vào bài toán thực tế trên nhiều miền: thị giác máy tính, xử lý ngôn ngữ tự nhiên, học tăng cường, v.v.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Chuẩn bị cho việc đọc hiểu và triển khai các bài báo nghiên cứu tiên tiến, góp phần phát triển lĩnh vực học sâu.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;giáo-trình-chính&quot;&gt;Giáo trình chính&lt;/h2&gt;

&lt;h3 id=&quot;tài-liệu-tham-khảo-trọng-tâm&quot;&gt;Tài liệu tham khảo trọng tâm&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Deep Learning&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ian Goodfellow, Yoshua Bengio, Aaron Courville&lt;br /&gt;
&lt;em&gt;Nhà xuất bản&lt;/em&gt;: MIT Press, 2016&lt;br /&gt;
&lt;em&gt;Trực tuyến&lt;/em&gt;: &lt;a href=&quot;http://www.deeplearningbook.org/&quot;&gt;deeplearningbook.org&lt;/a&gt; (miễn phí)&lt;br /&gt;
Giáo trình chuẩn về lý thuyết và toán học của học sâu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (3rd Edition)&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Aurélien Géron&lt;br /&gt;
&lt;em&gt;Nhà xuất bản&lt;/em&gt;: O’Reilly Media, 2022&lt;br /&gt;
Hướng dẫn thực hành cài đặt và triển khai mô hình học sâu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Understanding Deep Learning&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Simon J.D. Prince&lt;br /&gt;
&lt;em&gt;Nhà xuất bản&lt;/em&gt;: MIT Press, 2023&lt;br /&gt;
&lt;em&gt;Trực tuyến&lt;/em&gt;: &lt;a href=&quot;https://udlbook.github.io/udlbook/&quot;&gt;udlbook.github.io&lt;/a&gt;&lt;br /&gt;
Giới thiệu hiện đại, trực quan, chú trọng minh họa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. MIT Deep Learning Book&lt;/strong&gt;&lt;br /&gt;
Từ khóa học Deep Learning của MIT&lt;br /&gt;
Cách tiếp cận học thuật chặt chẽ với nền tảng lý thuyết vững.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Deep Learning Interviews&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Shlomo Kashani và Amir Ivry&lt;br /&gt;
&lt;em&gt;Trực tuyến&lt;/em&gt;: &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt; (PDF miễn phí) · &lt;a href=&quot;https://github.com/BoltzmannEntropy/interviews.ai&quot;&gt;GitHub&lt;/a&gt;&lt;br /&gt;
Bài toán phỏng vấn / thi cử đã giải. Khóa này thêm lộ trình luyện tùy chọn — bắt đầu từ &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt; — chỉ với câu gốc. Tải sách từ arXiv; đừng chờ bản in lại ở đây.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-bổ-sung&quot;&gt;Tài liệu bổ sung&lt;/h2&gt;

&lt;h3 id=&quot;thị-giác-máy-tính&quot;&gt;Thị giác máy tính&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Deep Learning for Computer Vision&lt;/em&gt; — Rajalingappaa Shanmugamani, Packt, 2018&lt;/li&gt;
  &lt;li&gt;Tài liệu khóa Stanford CS231n&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;xử-lý-ngôn-ngữ-tự-nhiên&quot;&gt;Xử lý ngôn ngữ tự nhiên&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Natural Language Processing with Transformers&lt;/em&gt; — Lewis Tunstall, Leandro von Werra, Thomas Wolf, O’Reilly, 2022&lt;/li&gt;
  &lt;li&gt;Tài liệu khóa Stanford CS224n&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;học-tăng-cường&quot;&gt;Học tăng cường&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Reinforcement Learning: An Introduction (2nd Edition)&lt;/em&gt; — Richard S. Sutton, Andrew G. Barto, MIT Press, 2018&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;bài-báo-và-chủ-đề-nâng-cao&quot;&gt;Bài báo và chủ đề nâng cao&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;“Attention Is All You Need” — Vaswani et al., 2017 (Transformer)&lt;/li&gt;
  &lt;li&gt;“Distilling the Knowledge in a Neural Network” — Hinton, Vinyals và Dean, 2015 (chưng cất tri thức; phần tiếp thời LLM ở Chương 26)&lt;/li&gt;
  &lt;li&gt;“Language Models are Few-Shot Learners” — Brown et al., 2020 (học trong ngữ cảnh)&lt;/li&gt;
  &lt;li&gt;“Generative Adversarial Networks” — Goodfellow et al., 2014 (GAN)&lt;/li&gt;
  &lt;li&gt;“Deep Residual Learning for Image Recognition” — He et al., 2015 (ResNet)&lt;/li&gt;
  &lt;li&gt;ArXiv.org và Papers with Code cho nghiên cứu mới nhất&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;học-liệu-trong-khóa&quot;&gt;Học liệu trong khóa&lt;/h2&gt;

&lt;p&gt;Toàn bộ ghi chép bài giảng, ví dụ mã nguồn và bài tập nằm trong kho lưu trữ này. Mỗi chương gồm:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Giải thích lý thuyết kèm nền tảng toán&lt;/li&gt;
  &lt;li&gt;Cài đặt Python/NumPy phục vụ học tập&lt;/li&gt;
  &lt;li&gt;Ví dụ thực hành với PyTorch và TensorFlow&lt;/li&gt;
  &lt;li&gt;Bài tập và dự án rèn luyện kỹ năng thực hành&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Khóa học hỗ trợ &lt;strong&gt;hai ngôn ngữ&lt;/strong&gt; (tiếng Anh và tiếng Việt). Người học có thể chuyển phiên bản bất kỳ lúc nào qua nút chuyển ngôn ngữ trên giao diện.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Course Contents</title>
   <link href="https://deep-learning-self-learning.pages.dev/home/contents-en/"/>
   <updated>2021-01-20T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/home/contents-en</id>
   <content type="html">&lt;p&gt;A comprehensive introduction to deep learning, covering neural network fundamentals, modern architectures (CNNs, RNNs, Transformers), training techniques, generative models, practical applications in computer vision and natural language processing, and a dedicated &lt;strong&gt;Chapter 26&lt;/strong&gt; hub on large language models (pretraining math, prompting, alignment, serving, distillation, and modern-decoder accounting).&lt;/p&gt;

&lt;h1 id=&quot;course-objectives&quot;&gt;Course Objectives&lt;/h1&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;Provide students with fundamental knowledge of deep learning theory and practice to support their study and research in data science and AI.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Enable students to understand, implement, and train deep neural networks from scratch and using modern frameworks.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Develop skills in applying deep learning to real-world problems across various domains including computer vision, NLP, and reinforcement learning.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;Prepare students to read and implement cutting-edge research papers and contribute to the advancement of deep learning.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;main-textbooks&quot;&gt;Main Textbooks&lt;/h2&gt;

&lt;h3 id=&quot;primary-references&quot;&gt;Primary References&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Deep Learning&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ian Goodfellow, Yoshua Bengio, and Aaron Courville&lt;br /&gt;
&lt;em&gt;Publisher&lt;/em&gt;: MIT Press, 2016&lt;br /&gt;
&lt;em&gt;Online&lt;/em&gt;: &lt;a href=&quot;http://www.deeplearningbook.org/&quot;&gt;deeplearningbook.org&lt;/a&gt; (Free)&lt;br /&gt;
The definitive textbook covering theory and mathematics of deep learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow (3rd Edition)&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Author&lt;/em&gt;: Aurélien Géron&lt;br /&gt;
&lt;em&gt;Publisher&lt;/em&gt;: O’Reilly Media, 2022&lt;br /&gt;
Practical guide to implementing and deploying deep learning models.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Understanding Deep Learning&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Author&lt;/em&gt;: Simon J.D. Prince&lt;br /&gt;
&lt;em&gt;Publisher&lt;/em&gt;: MIT Press, 2023&lt;br /&gt;
&lt;em&gt;Online&lt;/em&gt;: &lt;a href=&quot;https://udlbook.github.io/udlbook/&quot;&gt;udlbook.github.io&lt;/a&gt;&lt;br /&gt;
Modern introduction with excellent visualizations and intuitive explanations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. MIT Deep Learning Book&lt;/strong&gt;&lt;br /&gt;
From MIT’s Deep Learning course&lt;br /&gt;
Rigorous academic treatment with strong theoretical foundations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Deep Learning Interviews&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Shlomo Kashani and Amir Ivry&lt;br /&gt;
&lt;em&gt;Online&lt;/em&gt;: &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt; (free PDF) · &lt;a href=&quot;https://github.com/BoltzmannEntropy/interviews.ai&quot;&gt;GitHub&lt;/a&gt;&lt;br /&gt;
Solved interview- and exam-style problems. This course adds an optional practice track — start at &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt; — with original prompts only. Download the book from arXiv; do not expect a reprint here.&lt;/p&gt;

&lt;h2 id=&quot;additional-references&quot;&gt;Additional References&lt;/h2&gt;

&lt;h3 id=&quot;computer-vision&quot;&gt;Computer Vision&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Deep Learning for Computer Vision&lt;/strong&gt; by Rajalingappaa Shanmugamani, Packt Publishing, 2018&lt;/li&gt;
  &lt;li&gt;Stanford CS231n Course Materials&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;natural-language-processing&quot;&gt;Natural Language Processing&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Natural Language Processing with Transformers&lt;/strong&gt; by Lewis Tunstall, Leandro von Werra, and Thomas Wolf, O’Reilly, 2022&lt;/li&gt;
  &lt;li&gt;Stanford CS224n Course Materials&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;reinforcement-learning&quot;&gt;Reinforcement Learning&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Reinforcement Learning: An Introduction (2nd Edition)&lt;/strong&gt; by Richard S. Sutton and Andrew G. Barto, MIT Press, 2018&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;research-papers-and-advanced-topics&quot;&gt;Research Papers and Advanced Topics&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;“Attention Is All You Need” - Vaswani et al., 2017 (Transformers)&lt;/li&gt;
  &lt;li&gt;“Distilling the Knowledge in a Neural Network” - Hinton, Vinyals, and Dean, 2015 (knowledge distillation; LLM-era continuation in Chapter 26)&lt;/li&gt;
  &lt;li&gt;“Language Models are Few-Shot Learners” - Brown et al., 2020 (in-context learning)&lt;/li&gt;
  &lt;li&gt;“Generative Adversarial Networks” - Goodfellow et al., 2014 (GANs)&lt;/li&gt;
  &lt;li&gt;“Deep Residual Learning for Image Recognition” - He et al., 2015 (ResNet)&lt;/li&gt;
  &lt;li&gt;ArXiv.org and Papers with Code for latest research&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;course-materials&quot;&gt;Course Materials&lt;/h2&gt;

&lt;p&gt;All lecture notes, code examples, and assignments are available in this repository. Each chapter includes:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Theoretical explanations with mathematical foundations&lt;/li&gt;
  &lt;li&gt;Python/NumPy implementations for educational clarity&lt;/li&gt;
  &lt;li&gt;Practical examples using PyTorch and TensorFlow&lt;/li&gt;
  &lt;li&gt;Exercises and projects for hands-on learning&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The course is available in &lt;strong&gt;English and Vietnamese&lt;/strong&gt;. Use the language switch control in the interface to move between the two editions at any time.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>26-07 Nội tại decoder hiện đại và sổ sách chi phí</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_07_Modern_Internals_and_Accounting/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_07_Modern_Internals_and_Accounting</id>
   <content type="html">&lt;p&gt;Nếu bạn đặt sơ đồ Transformer gốc năm 2017 cạnh mã nguồn của Llama 3, Qwen 2.5 hay Gemma 2, bạn sẽ nhận ra gần như mọi khối bên trong đều đã được nâng cấp tinh vi: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LayerNorm&lt;/code&gt; đổi thành &lt;strong&gt;RMSNorm&lt;/strong&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ReLU FFN&lt;/code&gt; đổi thành &lt;strong&gt;SwiGLU&lt;/strong&gt;, mã hóa vị trí cộng đổi thành phép quay &lt;strong&gt;RoPE&lt;/strong&gt;, còn Multi-Head Attention đổi thành &lt;strong&gt;GQA&lt;/strong&gt;! Bài học khép lại toàn bộ khóa học này biến bạn thành một “kế toán trưởng” kiến trúc LLM: hiểu sâu từng mảnh ghép hiện đại và tự tay hạch toán chính xác từng tham số, từng byte VRAM và từng phép tính FLOPs.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nâng-cấp-nội-tại-của-khối-decoder-llm-hiện-đại&quot;&gt;Kiến thức cần nhớ: Bốn nâng cấp nội tại của khối Decoder LLM hiện đại&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;RMSNorm (Root Mean Square Normalization):&lt;/strong&gt; Bỏ phép trừ trung bình của LayerNorm, chỉ chuẩn hóa theo căn trung bình bình phương \(\text{RMS}(\mathbf{x}) = \sqrt{\frac{1}{d}\sum x_i^2 + \epsilon}\), giữ nguyên độ ổn định Pre-Norm mà giảm chi phí đọc/ghi bộ nhớ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FFN SwiGLU (Gated Linear Unit với SiLU):&lt;/strong&gt; Dùng 3 ma trận chiếu \((W_{\text{gate}}, W_{\text{up}}, W_{\text{down}})\) với kích thước ẩn \(d_{ff} \approx \frac{8}{3}d\) để giữ nguyên tổng tham số như FFN chuẩn \(4d\) nhưng tăng mạnh khả năng biểu diễn phi tuyến.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;RoPE (Rotary Position Embedding):&lt;/strong&gt; Xoay từng cặp chiều \((2i, 2i+1)\) của Query và Key một góc \(m\theta_i\) theo vị trí \(m\), khiến tích vô hướng \(Q_m \cdot K_n\) tự động chỉ phụ thuộc vào &lt;strong&gt;khoảng cách tương đối&lt;/strong&gt; \((m - n)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Grouped-Query Attention (GQA) và Sổ sách chi phí:&lt;/strong&gt; Chia sẻ \(n_{\text{kv}}\) đầu Key/Value cho \(n_q\) đầu Query (tỷ lệ nhóm \(G = n_q / n_{\text{kv}}\)), cắt giảm tuyến tính kích thước KV Cache lẫn trọng số \(W_K, W_V\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-rmsnorm-2d-và-phép-quay-vị-trí-tương-đối-rope&quot;&gt;Giải thích: Tính tay một bước RMSNorm 2D và phép quay vị trí tương đối RoPE&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Tính tay RMSNorm&lt;/strong&gt; cho vector đầu vào \(\mathbf{x} = [3{,}0,\; 4{,}0]\) với trọng số scale \(\boldsymbol{\gamma} = [1{,}0,\; 1{,}0]\) (\(\epsilon \approx 0\)):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Căn trung bình bình phương: \(\text{RMS}(\mathbf{x}) = \sqrt{\frac{3^2 + 4^2}{2}} = \sqrt{\frac{25}{2}} = \sqrt{12{,}5} \approx 3{,}5355\).&lt;/li&gt;
  &lt;li&gt;Đầu ra chuẩn hóa: \(\text{RMSNorm}(\mathbf{x}) = \left[\frac{3{,}0}{3{,}5355},\; \frac{4{,}0}{3{,}5355}\right] \approx [0{,}8485,\; 1{,}1314]\) (không cần tính trung bình \(\mu = 3{,}5\) và không có vector bias \(\boldsymbol{\beta}\)).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Kiểm chứng tính tương đối của RoPE trên 1 cặp chiều 2D:&lt;/strong&gt;
Giả sử \(\mathbf{q} = (1, 0)\) ở vị trí \(m = 3\) và \(\mathbf{k} = (1, 0)\) ở vị trí \(n = 1\), tần số góc \(\theta = 30^\circ\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Xoay \(\mathbf{q}\) góc \(3 \times 30^\circ = 90^\circ\) → \(\mathbf{q}_{\text{rot}} = (\cos 90^\circ, \sin 90^\circ) = (0, 1)\).&lt;/li&gt;
  &lt;li&gt;Xoay \(\mathbf{k}\) góc \(1 \times 30^\circ = 30^\circ\) → \(\mathbf{k}_{\text{rot}} = (\cos 30^\circ, \sin 30^\circ) = (0{,}866,\; 0{,}500)\).&lt;/li&gt;
  &lt;li&gt;Tích vô hướng: \(\mathbf{q}_{\text{rot}} \cdot \mathbf{k}_{\text{rot}} = 0(0{,}866) + 1(0{,}500) = 0{,}500 = \cos(60^\circ) = \cos((3 - 1)\cdot 30^\circ)\)!
Nếu dịch cả hai token lên vị trí \(m = 103, n = 101\), hiệu \(m - n\) vẫn bằng \(2\) nên tích vô hướng &lt;strong&gt;vẫn đúng bằng \(0{,}500\)&lt;/strong&gt; — đó chính là vẻ đẹp hình học tuyệt đối của RoPE!&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;nội-tại-decoder-hiện-đại-và-hạch-toán-chi-phí&quot;&gt;Nội tại decoder hiện đại và hạch toán chi phí&lt;/h1&gt;

&lt;p&gt;Chương 08 đã trình bày kiến trúc Transformer năm 2017. Bài này đi vào &lt;strong&gt;cấu trúc khối decoder thực tế&lt;/strong&gt; trong các mô hình giai đoạn 2024–2026: chuẩn hóa trước bằng RMSNorm, &lt;em&gt;attention&lt;/em&gt; nhân quả kết hợp RoPE, mạng truyền thẳng SwiGLU và KV-cache khi giải mã. Đồng thời, bài cung cấp &lt;strong&gt;các công thức ước lượng định lượng&lt;/strong&gt; thường dùng trong kỹ thuật hệ thống và phỏng vấn: đếm số tham số, ước lượng bộ nhớ kích hoạt, FLOPs huấn luyện và bộ nhớ suy luận.&lt;/p&gt;

&lt;p&gt;Nền tảng đại số của Transformer năm 2017 vẫn giữ nguyên; điểm thay đổi nằm ở cách đóng gói thành phần và tối ưu chi phí. Chi tiết từng thành phần riêng lẻ có thể xem thêm ở &lt;strong&gt;02-99&lt;/strong&gt; (SwiGLU / RMSNorm), &lt;strong&gt;08-01&lt;/strong&gt; (Transformer gốc) và &lt;strong&gt;07-99&lt;/strong&gt; (&lt;em&gt;attention&lt;/em&gt; hiệu quả); bài này ghép toàn bộ thành một ngăn xếp decoder hoàn chỉnh.&lt;/p&gt;

&lt;h2 id=&quot;1-cấu-trúc-khối-decoder-hiện-đại&quot;&gt;1. Cấu trúc khối decoder hiện đại&lt;/h2&gt;

&lt;p&gt;Một tầng trong các mô hình họ Llama vẫn tuân theo cấu trúc “trao đổi thông tin qua &lt;em&gt;attention&lt;/em&gt;, sau đó xử lý theo vị trí bằng FFN” với kết nối phần dư (&lt;em&gt;residual connection&lt;/em&gt;) bọc quanh từng nhánh con và chuẩn hóa đặt trước (&lt;em&gt;pre-norm&lt;/em&gt;):&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart TD
  x[&quot;Dong residual x&quot;] --&amp;gt; n1[&quot;RMSNorm&quot;]
  n1 --&amp;gt; attn[&quot;Attention nhan qua + RoPE&quot;]
  attn --&amp;gt; a1[&quot;Cong residual&quot;]
  a1 --&amp;gt; n2[&quot;RMSNorm&quot;]
  n2 --&amp;gt; ffn[&quot;FFN SwiGLU&quot;]
  ffn --&amp;gt; a2[&quot;Cong residual&quot;]
  a2 --&amp;gt; y[&quot;Dau ra khoi&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id=&quot;rmsnorm&quot;&gt;RMSNorm&lt;/h3&gt;

&lt;p&gt;LayerNorm chuẩn hóa bằng cách trừ trung bình rồi chia cho độ lệch chuẩn. &lt;strong&gt;RMSNorm&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/1910.07467&quot;&gt;Zhang &amp;amp; Sennrich, 2019&lt;/a&gt;) bỏ bước trừ trung bình, chỉ chuẩn hóa theo căn bậc hai trung bình bình phương (RMS) kèm hệ số tỉ lệ học được \(\gamma\) (thường không dùng &lt;em&gt;bias&lt;/em&gt;):&lt;/p&gt;

\[\mathrm{RMSNorm}(x) = \frac{x}{\sqrt{\frac{1}{d}\sum_{i=1}^{d} x_i^2 + \varepsilon}} \odot \gamma.\]

&lt;p&gt;Các họ mô hình như Llama, Gemma và Qwen sử dụng rộng rãi RMSNorm vì tính toán đơn giản hơn, không làm biến đổi giá trị trung bình của luồng phần dư, trong khi vẫn giữ vai trò ổn định biên độ trước các phép nhân ma trận kế tiếp (Chương 09).&lt;/p&gt;

&lt;h3 id=&quot;ffn-swiglu&quot;&gt;FFN SwiGLU&lt;/h3&gt;

&lt;p&gt;Trong khi FFN năm 2017 dùng công thức \(\mathrm{ReLU}(x W_1) W_2\), FFN có cổng hiện đại (&lt;a href=&quot;https://arxiv.org/abs/2002.05202&quot;&gt;Shazeer, 2020&lt;/a&gt;) có dạng:&lt;/p&gt;

\[\mathrm{SwiGLU}(x) = \big(\mathrm{SiLU}(x W_{\mathrm{gate}}) \odot (x W_{\mathrm{up}})\big) W_{\mathrm{down}},\]

&lt;p&gt;với \(\mathrm{SiLU}(z) = z\,\sigma(z)\) (còn gọi là Swish). Khối này gồm ba ma trận trọng số kết hợp tích theo phần tử (Hadamard). Khi thiết kế, chiều ẩn \(d_{\mathrm{ff}}\) thường được thu nhỏ lại (ví dụ khoảng \(\frac{8}{3}d\) thay vì \(4d\)) để tổng &lt;strong&gt;số tham số&lt;/strong&gt; tương đương FFN ReLU truyền thống.&lt;/p&gt;

&lt;h3 id=&quot;rope-mã-hóa-vị-trí-bằng-phép-quay-tương-đối&quot;&gt;RoPE: Mã hóa vị trí bằng phép quay tương đối&lt;/h3&gt;

&lt;p&gt;Thay vì cộng vectơ vị trí sin–cos cố định vào &lt;em&gt;embedding&lt;/em&gt; đầu vào, &lt;strong&gt;RoPE&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2104.09864&quot;&gt;Su et al., 2021/2023&lt;/a&gt;) &lt;em&gt;quay&lt;/em&gt; từng cặp chiều của vectơ &lt;em&gt;query&lt;/em&gt; và &lt;em&gt;key&lt;/em&gt; trong mặt phẳng 2-D theo một góc tỉ lệ với vị trí \(t\):&lt;/p&gt;

\[\begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}
\leftarrow
\begin{pmatrix} \cos(t\theta_i) &amp;amp; -\sin(t\theta_i) \\ \sin(t\theta_i) &amp;amp; \cos(t\theta_i) \end{pmatrix}
\begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix},\]

&lt;p&gt;và áp dụng tương tự cho \(k\) với các tần số cố định \(\theta_i = \mathrm{base}^{-2i/d}\). Khi đó, tích vô hướng \(q_t^\top k_s\) chỉ phụ thuộc vào khoảng cách tương đối \(t - s\) thay vì từng vị trí tuyệt đối riêng lẻ. Như vậy, &lt;strong&gt;thông tin vị trí tương đối được tích hợp trực tiếp vào điểm số attention&lt;/strong&gt; (xem thêm bài &lt;strong&gt;08-99&lt;/strong&gt;).&lt;/p&gt;

&lt;h3 id=&quot;gqa-và-mqa-thu-gọn-kv-cache&quot;&gt;GQA và MQA: Thu gọn KV-cache&lt;/h3&gt;

&lt;p&gt;Trong &lt;em&gt;multi-head attention&lt;/em&gt; (MHA) chuẩn, mỗi đầu &lt;em&gt;query&lt;/em&gt; có riêng một cặp đầu &lt;em&gt;key/value&lt;/em&gt;. &lt;strong&gt;Multi-query attention&lt;/strong&gt; (MQA, &lt;a href=&quot;https://arxiv.org/abs/1911.02150&quot;&gt;Shazeer, 2019&lt;/a&gt;) dùng chung duy nhất một cặp &lt;em&gt;K, V&lt;/em&gt; cho mọi đầu &lt;em&gt;query&lt;/em&gt;. &lt;strong&gt;Grouped-query attention&lt;/strong&gt; (GQA, &lt;a href=&quot;https://arxiv.org/abs/2305.13245&quot;&gt;Ainslie et al., 2023&lt;/a&gt;) nằm ở giữa: chia \(n_{\mathrm{q}}\) đầu &lt;em&gt;query&lt;/em&gt; thành các nhóm dùng chung \(n_{\mathrm{kv}} \ll n_{\mathrm{q}}\) cặp đầu &lt;em&gt;key/value&lt;/em&gt;. Công thức tính &lt;em&gt;attention&lt;/em&gt; không đổi, nhưng kích thước &lt;strong&gt;KV-cache&lt;/strong&gt; giảm đi theo tỉ lệ \(n_{\mathrm{kv}} / n_{\mathrm{q}}\), mang lại lợi ích trực tiếp cho tốc độ phục vụ (&lt;strong&gt;26-04&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;2-cơ-chế-của-flashattention&quot;&gt;2. Cơ chế của FlashAttention&lt;/h2&gt;

&lt;p&gt;Về mặt toán học, &lt;em&gt;attention&lt;/em&gt; vẫn là \(\mathrm{softmax}(QK^\top / \sqrt{d})\,V\). Tuy nhiên, cài đặt thông thường phải tạo và ghi toàn bộ ma trận điểm \(L \times L\) xuống bộ nhớ chính của GPU (HBM), gây nghẽn băng thông. &lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;Dao et al., 2022&lt;/a&gt; (&lt;strong&gt;FlashAttention&lt;/strong&gt;) khắc phục điều này bằng cách &lt;strong&gt;chia khối&lt;/strong&gt; (&lt;em&gt;tiling&lt;/em&gt;) các ma trận \(Q, K, V\) sao cho vừa vặn bộ nhớ đệm nhanh SRAM trên chip, đồng thời gộp bước softmax với phép nhân \(V\).&lt;/p&gt;

&lt;p&gt;Vì softmax đòi hỏi tổng hàm mũ trên cả hàng, FlashAttention dùng kỹ thuật &lt;strong&gt;softmax trực tuyến&lt;/strong&gt; (đã trình bày ở &lt;strong&gt;26-01&lt;/strong&gt;): duy trì giá trị cực đại tạm thời \(m\) và tổng chuẩn hóa \(s\) của \(e^{z-m}\) khi duyệt qua từng khối, rồi điều chỉnh lại tỉ lệ tổng có trọng số của \(V\) mỗi khi \(m\) thay đổi. Kết quả đầu ra chính xác tương đương về mặt đại số, nhưng lượng đọc/ghi HBM giảm mạnh. Các phiên bản FlashAttention-2 và FlashAttention-3 tiếp tục tối ưu mức độ song song và khai thác phần cứng mới (&lt;a href=&quot;https://arxiv.org/abs/2307.08691&quot;&gt;Dao, 2023&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2407.08608&quot;&gt;Shah et al., 2024&lt;/a&gt;; xem thêm &lt;strong&gt;07-99&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;3-hạch-toán-tham-số-flops-và-bộ-nhớ&quot;&gt;3. Hạch toán tham số, FLOPs và bộ nhớ&lt;/h2&gt;

&lt;p&gt;Các công thức dưới đây cho phép ước lượng nhanh theo thứ tự độ lớn từ các siêu tham số \(n_{\mathrm{layers}}\), \(d\), \(V\) và \(L\).&lt;/p&gt;

&lt;h3 id=&quot;đếm-số-tham-số-decoder-dày-đặc&quot;&gt;Đếm số tham số (decoder dày đặc)&lt;/h3&gt;

&lt;p&gt;Bỏ qua các hệ số &lt;em&gt;bias&lt;/em&gt; nhỏ và kiến trúc MoE:&lt;/p&gt;

\[\begin{aligned}
N_{\mathrm{embed}} &amp;amp;\approx 2\, V d
\quad \text{(bảng nhúng + đầu LM tách riêng; chỉ còn } Vd \text{ nếu chia sẻ trọng số)}, \\
N_{\mathrm{attn}} &amp;amp;\approx n_{\mathrm{layers}}\big( d\cdot d_{\mathrm{q}} + 2\, d\cdot d_{\mathrm{kv}} + d_{\mathrm{q}}\cdot d \big), \\
N_{\mathrm{ffn}} &amp;amp;\approx n_{\mathrm{layers}}\cdot 3\, d\, d_{\mathrm{ff}}
\quad \text{(SwiGLU: gate, up, down)}.
\end{aligned}\]

&lt;p&gt;Với kiến trúc nhiều đầu, \(d_{\mathrm{q}} = n_{\mathrm{q}} d_{\mathrm{head}}\) và \(d_{\mathrm{kv}} = n_{\mathrm{kv}} d_{\mathrm{head}}\). Khi dùng MHA chuẩn (\(n_{\mathrm{kv}} = n_{\mathrm{q}}\)), số tham số &lt;em&gt;attention&lt;/em&gt; vào khoảng \(4 n_{\mathrm{layers}} d^2\); với GQA, hai khối chiếu &lt;em&gt;K, V&lt;/em&gt; thu gọn thành \(2 d \cdot d_{\mathrm{kv}}\). Bảng nhúng chỉ chiếm tỉ trọng lớn khi \(d\) nhỏ hoặc \(V\) rất lớn; ở quy mô LLM thông thường, các tầng Transformer chiếm phần lớn tổng tham số.&lt;/p&gt;

&lt;h3 id=&quot;ước-lượng-bộ-nhớ-giá-trị-kích-hoạt-khi-huấn-luyện&quot;&gt;Ước lượng bộ nhớ giá trị kích hoạt khi huấn luyện&lt;/h3&gt;

&lt;p&gt;Các giá trị kích hoạt từ lượt lan truyền xuôi cần lưu lại cho lan truyền ngược tỉ lệ với:&lt;/p&gt;

\[n_{\mathrm{layers}} \times B \times L \times d\]

&lt;p&gt;cộng thêm các ma trận &lt;em&gt;attention&lt;/em&gt; nếu không tính lại. Kỹ thuật &lt;em&gt;activation checkpointing&lt;/em&gt; (tính lại kích hoạt ở lượt ngược) đánh đổi thêm FLOPs để giảm mạnh dung lượng bộ nhớ này. Đây là lý do &lt;strong&gt;kích thước micro-batch&lt;/strong&gt; và &lt;strong&gt;độ dài chuỗi&lt;/strong&gt; thường chạm trần VRAM trước cả bản thân bộ trọng số.&lt;/p&gt;

&lt;h3 id=&quot;ước-lượng-flops&quot;&gt;Ước lượng FLOPs&lt;/h3&gt;

&lt;p&gt;Một phép nhân ma trận trọng số kích thước \(n \times m\) với \(L\) token tốn khoảng \(2 n m L\) FLOPs (mỗi cặp nhân–cộng tính là 2 phép toán dấu phẩy động). Cộng gộp trên toàn bộ mô hình, quy tắc bậc nhất phổ biến (&lt;a href=&quot;https://arxiv.org/abs/2001.08361&quot;&gt;Kaplan et al., 2020&lt;/a&gt;) là:&lt;/p&gt;

\[\begin{aligned}
C_{\mathrm{fwd}} &amp;amp;\approx 2\, N_{\mathrm{params}}\, T, \\
C_{\mathrm{bwd}} &amp;amp;\approx 2\, C_{\mathrm{fwd}} \approx 4\, N_{\mathrm{params}}\, T, \\
C_{\mathrm{train}} &amp;amp;\approx 6\, N_{\mathrm{params}}\, T,
\end{aligned}\]

&lt;p&gt;trong đó \(T\) là tổng số &lt;strong&gt;token&lt;/strong&gt; (batch \(\times\) độ dài chuỗi \(\times\) số bước). Công thức xấp xỉ này bỏ qua số hạng \(O(L^2 d)\) của &lt;em&gt;attention&lt;/em&gt; (chỉ đáng kể khi độ dài chuỗi \(L\) rất lớn). Lượt lan truyền ngược tốn khoảng gấp đôi lượt xuôi vì mỗi tầng cần một phép nhân ma trận để tính gradient theo đầu vào và một phép nhân để tính gradient theo trọng số (Chương 03).&lt;/p&gt;

&lt;h3 id=&quot;bộ-nhớ-khi-suy-luận&quot;&gt;Bộ nhớ khi suy luận&lt;/h3&gt;

&lt;p&gt;Ở chế độ suy luận, hệ thống không cần lưu đồ thị tính toán hay trạng thái bộ tối ưu; bộ nhớ chính gồm trọng số mô hình và KV-cache:&lt;/p&gt;

\[\mathrm{mem} \approx \underbrace{N_{\mathrm{params}} \cdot b_{\mathrm{w}}}_{\text{trọng số}} + \underbrace{2 \cdot L \cdot n_{\mathrm{layers}} \cdot n_{\mathrm{kv}} \cdot d_{\mathrm{head}} \cdot b_{\mathrm{kv}}}_{\text{KV-cache}},\]

&lt;p&gt;với \(b_{\mathrm{w}}\) và \(b_{\mathrm{kv}}\) là số byte mỗi phần tử (ví dụ 2 byte cho FP16/BF16, 1 byte cho INT8). Số hạng KV-cache &lt;strong&gt;tăng tuyến tính theo độ dài chuỗi \(L\)&lt;/strong&gt;: lượng tử hóa trọng số giúp giảm số hạng đầu tiên, còn GQA giúp giảm số hạng thứ hai.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  prefill[&quot;Prefill: ghi K,V cho prompt&quot;] --&amp;gt; step[&quot;Giai ma mot token&quot;]
  step --&amp;gt; append[&quot;Noi them mot cap K,V moi moi tang&quot;]
  append --&amp;gt; grow[&quot;Do dai cache n, bo nho Theta cua n&quot;]
  grow --&amp;gt; step
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;4-định-luật-mở-rộng-tối-ưu-theo-tính-toán-kiểu-chinchilla&quot;&gt;4. Định luật mở rộng tối ưu theo tính toán (kiểu Chinchilla)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2001.08361&quot;&gt;Kaplan et al., 2020&lt;/a&gt; chỉ ra rằng trên một dải quy mô rộng, hàm mất mát tiền huấn luyện giảm theo quy luật lũy thừa theo kích thước mô hình, lượng dữ liệu và ngân sách tính toán; trong thiết lập ban đầu của họ, tăng số tham số nhanh hơn số token tỏ ra có lợi hơn. Sau đó, &lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Hoffmann et al., 2022&lt;/a&gt; (&lt;em&gt;Training Compute-Optimal Large Language Models&lt;/em&gt;, bài báo &lt;strong&gt;Chinchilla&lt;/strong&gt;) thiết kế lại thí nghiệm đồng mức tính toán (&lt;em&gt;isoFLOP&lt;/em&gt;) và rút ra kết luận khác: &lt;strong&gt;với một ngân sách FLOP huấn luyện cố định, cần tăng số tham số và số token theo tỉ lệ cân đối với nhau&lt;/strong&gt;, vì nhiều mô hình lớn trước đó thực chất bị thiếu dữ liệu huấn luyện.&lt;/p&gt;

&lt;p&gt;Các điểm cốt lõi cần ghi nhớ:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Ngân sách huấn luyện \(C \approx 6 N T\) phải được phân bổ hợp lý giữa kích thước mô hình \(N\) và lượng dữ liệu \(T\).&lt;/li&gt;
  &lt;li&gt;“Tối ưu tính toán” (&lt;em&gt;compute-optimal&lt;/em&gt;) nghĩa là chọn cặp \((N, T)\) trên cùng đường đồng mức FLOP để đạt &lt;em&gt;hàm mất mát thấp nhất&lt;/em&gt;, không phải để có mô hình nhiều tham số nhất.&lt;/li&gt;
  &lt;li&gt;Trong thiết lập của Hoffmann et al., điểm tối ưu rơi vào khoảng &lt;strong&gt;vài chục token cho mỗi tham số&lt;/strong&gt;. Tuy nhiên, nhiều mô hình thực tế sau này chủ động huấn luyện &lt;em&gt;vượt&lt;/em&gt; ngưỡng dữ liệu này (dùng nhiều token hơn cho một \(N\) nhỏ hơn) nhằm giảm chi phí phục vụ suy luận lâu dài.&lt;/li&gt;
  &lt;li&gt;Trong khi Chương 25 khảo sát rộng các xu hướng mở rộng (kể cả tính toán lúc suy luận ở &lt;strong&gt;25-99&lt;/strong&gt;), phần này tập trung vào đánh đổi phân bổ tài nguyên &lt;strong&gt;trong giai đoạn huấn luyện&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-so-sánh-rnn--lstm-transformer-và-mô-hình-không-gian-trạng-thái-ssm&quot;&gt;5. So sánh RNN / LSTM, Transformer và mô hình không gian trạng thái (SSM)&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Tiêu chí&lt;/th&gt;
      &lt;th&gt;RNN / LSTM (Ch. 05–06)&lt;/th&gt;
      &lt;th&gt;Decoder Transformer (Ch. 08, bài này)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Trạng thái&lt;/td&gt;
      &lt;td&gt;Một vectơ ẩn \(h_t\) cập nhật từ \(h_{t-1}\)&lt;/td&gt;
      &lt;td&gt;Toàn bộ tiền tố được trộn trực tiếp qua &lt;em&gt;attention&lt;/em&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Song song theo thời gian \(t\)&lt;/td&gt;
      &lt;td&gt;Tuần tự: bước \(t\) phụ thuộc bước \(t-1\)&lt;/td&gt;
      &lt;td&gt;Huấn luyện song song trên mọi vị trí trong cửa sổ&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Độ dài đường truyền thông tin&lt;/td&gt;
      &lt;td&gt;\(O(L)\) bước giữa hai token xa nhau&lt;/td&gt;
      &lt;td&gt;\(O(1)\) bước trực tiếp qua &lt;em&gt;attention&lt;/em&gt; trong cửa sổ&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Chi phí mỗi bước giải mã&lt;/td&gt;
      &lt;td&gt;Cập nhật trạng thái \(O(1)\)&lt;/td&gt;
      &lt;td&gt;Tính &lt;em&gt;attention&lt;/em&gt; trên KV-cache tốn \(O(L)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Xử lý ngữ cảnh dài&lt;/td&gt;
      &lt;td&gt;LSTM giảm triệt tiêu gradient nhưng vẫn nén vào trạng thái cố định&lt;/td&gt;
      &lt;td&gt;Truy cập trực tiếp trong phạm vi \(L\); đánh đổi bằng KV-cache và &lt;em&gt;prefill&lt;/em&gt; \(O(L^2)\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Về bản chất, các cổng của LSTM thực hiện thao tác ghi/quên trên một ô nhớ kích thước cố định, còn &lt;em&gt;attention&lt;/em&gt; truy xuất theo nội dung trên toàn bộ các &lt;em&gt;key&lt;/em&gt; đã lưu. Transformer chiếm ưu thế về tốc độ tiền huấn luyện song song và khả năng kết nối ngữ cảnh xa, trong khi RNN giữ chi phí không đổi ở mỗi bước sinh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mô hình không gian trạng thái (SSM):&lt;/strong&gt; Các kiến trúc hồi quy tuyến tính như S4 và Mamba (&lt;a href=&quot;https://arxiv.org/abs/2312.00752&quot;&gt;Gu &amp;amp; Dao, 2023&lt;/a&gt;) thay thế &lt;em&gt;attention&lt;/em&gt; bằng một trạng thái có cấu trúc cho phép tính song song như phép tích chập (hoặc &lt;em&gt;parallel scan&lt;/em&gt;) khi huấn luyện và cập nhật trạng thái \(O(1)\) khi giải mã — kết hợp tốc độ suy luận kiểu RNN với khả năng song song huấn luyện kiểu Transformer. Khi tiếp cận các mô hình SSM, hai câu hỏi trọng tâm là: &lt;em&gt;trạng thái ẩn lưu thông tin gì&lt;/em&gt; và &lt;em&gt;đường huấn luyện dùng tích chập hay scan song song&lt;/em&gt;?&lt;/p&gt;

&lt;h2 id=&quot;6-phụ-lục-ba-chiến-lược-song-song-hóa-huấn-luyện&quot;&gt;6. Phụ lục: Ba chiến lược song song hóa huấn luyện&lt;/h2&gt;

&lt;p&gt;Khi mô hình vượt quá dung lượng một GPU, hệ thống huấn luyện phân tán thường kết hợp ba trục song song hóa cơ bản:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Song song dữ liệu (&lt;em&gt;Data Parallelism&lt;/em&gt;):&lt;/strong&gt; Nhân bản toàn bộ mô hình lên nhiều GPU, chia nhỏ &lt;em&gt;batch&lt;/em&gt; dữ liệu và đồng bộ gradient qua phép &lt;em&gt;all-reduce&lt;/em&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  batch[&quot;Batch huan luyen&quot;] --&amp;gt; g1[&quot;Ban sao GPU 1&quot;]
  batch --&amp;gt; g2[&quot;Ban sao GPU 2&quot;]
  batch --&amp;gt; g3[&quot;Ban sao GPU 3&quot;]
  g1 --&amp;gt; avg[&quot;All-reduce gradient&quot;]
  g2 --&amp;gt; avg
  g3 --&amp;gt; avg
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Song song đường ống (&lt;em&gt;Pipeline Parallelism&lt;/em&gt;):&lt;/strong&gt; Chia &lt;em&gt;các tầng&lt;/em&gt; của mô hình sang nhiều thiết bị khác nhau và luân chuyển các &lt;em&gt;micro-batch&lt;/em&gt; qua từng chặng.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  mb[&quot;Micro-batch&quot;] --&amp;gt; p1[&quot;Thiet bi A: tang 1 den k&quot;]
  p1 --&amp;gt; p2[&quot;Thiet bi B: tang k+1 den 2k&quot;]
  p2 --&amp;gt; p3[&quot;Thiet bi C: cac tang con lai&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Song song tensor (&lt;em&gt;Tensor Parallelism&lt;/em&gt;):&lt;/strong&gt; Chia nhỏ &lt;em&gt;từng phép nhân ma trận&lt;/em&gt; (hoặc các nhóm đầu &lt;em&gt;attention&lt;/em&gt;) trên nhiều thiết bị rồi gom kết quả qua &lt;em&gt;all-gather&lt;/em&gt; hoặc &lt;em&gt;reduce-scatter&lt;/em&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  x[&quot;An x&quot;] --&amp;gt; col1[&quot;Thiet bi A: mot phan W&quot;]
  x --&amp;gt; col2[&quot;Thiet bi B: phan con lai cua W&quot;]
  col1 --&amp;gt; cat[&quot;All-gather hoac reduce-scatter&quot;]
  col2 --&amp;gt; cat
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Các hệ thống huấn luyện quy mô lớn thường kết hợp cả ba chiến lược cùng với ZeRO / FSDP (phân mảnh thêm trạng thái của bộ tối ưu). Nói gọn lại, mỗi chiến lược tương ứng với một trục phân chia: &lt;em&gt;batch&lt;/em&gt;, &lt;em&gt;độ sâu&lt;/em&gt; (tầng) hoặc &lt;em&gt;độ rộng&lt;/em&gt; (chiều ma trận). Các kỹ thuật nén ở Chương 23 (lượng tử hóa, chưng cất) bổ trợ trực tiếp bằng cách giảm kích thước \(N\) hoặc số bit lưu trữ.&lt;/p&gt;

&lt;h2 id=&quot;7-liên-kết-trong-chương-và-khóa-học&quot;&gt;7. Liên kết trong chương và khóa học&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;26-01:&lt;/strong&gt; Ôn lại cross-entropy, softmax, &lt;em&gt;online softmax&lt;/em&gt; và AdamW.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;26-04:&lt;/strong&gt; Tối ưu KV-cache, &lt;em&gt;continuous batching&lt;/em&gt;, &lt;em&gt;speculative decoding&lt;/em&gt; và lấy mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;08-01 / 08-99:&lt;/strong&gt; Chi tiết Transformer 2017 và giới thiệu ban đầu về RoPE.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;07-99:&lt;/strong&gt; Tài liệu tham khảo về FlashAttention và PagedAttention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;25 / 25-99:&lt;/strong&gt; Tổng quan hướng nghiên cứu mở và mở rộng tính toán lúc suy luận.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;đọc-thêm&quot;&gt;Đọc thêm&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Alisa Liu, &lt;em&gt;&lt;a href=&quot;https://alisawuffles.notion.site/alisa-s-book-of-llms&quot;&gt;Alisa’s Book of LLMs&lt;/a&gt;&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Alisa Liu, &lt;em&gt;&lt;a href=&quot;https://alisawuffles.notion.site/math-notes&quot;&gt;Math notes&lt;/a&gt;&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Kaplan et al., 2020. &lt;a href=&quot;https://arxiv.org/abs/2001.08361&quot;&gt;Scaling Laws for Neural Language Models&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Hoffmann et al., 2022. &lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Training Compute-Optimal Large Language Models&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Vaswani et al., 2017. &lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Su et al., 2023. &lt;a href=&quot;https://arxiv.org/abs/2104.09864&quot;&gt;RoFormer / RoPE&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Zhang &amp;amp; Sennrich, 2019. &lt;a href=&quot;https://arxiv.org/abs/1910.07467&quot;&gt;RMSNorm&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Shazeer, 2020. &lt;a href=&quot;https://arxiv.org/abs/2002.05202&quot;&gt;GLU Variants Improve Transformer&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Dao et al., 2022. &lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;FlashAttention&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Ainslie et al., 2023. &lt;a href=&quot;https://arxiv.org/abs/2305.13245&quot;&gt;GQA&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Gu &amp;amp; Dao, 2023. &lt;a href=&quot;https://arxiv.org/abs/2312.00752&quot;&gt;Mamba&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Khối decoder hiện đại gồm: RMSNorm → &lt;em&gt;attention&lt;/em&gt; nhân quả + RoPE → cộng phần dư → RMSNorm → SwiGLU → cộng phần dư.&lt;/li&gt;
  &lt;li&gt;GQA / MQA giảm số đầu lưu trong &lt;strong&gt;KV-cache&lt;/strong&gt;, còn FlashAttention giảm &lt;strong&gt;băng thông bộ nhớ I/O&lt;/strong&gt; mà không làm thay đổi phép toán &lt;em&gt;attention&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Ước lượng FLOPs: lượt xuôi \(\approx 2 N T\), lượt ngược \(\approx 4 N T\), huấn luyện \(\approx 6 N T\); bộ nhớ suy luận xấp xỉ tổng dung lượng trọng số và KV-cache.&lt;/li&gt;
  &lt;li&gt;Theo phân tích kiểu Chinchilla, cần phân bổ ngân sách FLOP cân đối cho cả số tham số \(N\) và số token \(T\) (và có thể huấn luyện thêm token khi ưu tiên giảm chi phí suy luận).&lt;/li&gt;
  &lt;li&gt;RNN nén lịch sử vào một trạng thái \(h_t\) kích thước cố định, Transformer truy cập trực tiếp KV-cache cỡ \(O(L)\), còn SSM hướng tới kết hợp ưu điểm của cả hai.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, tiếng Anh. Minh họa trực quan khối decoder (attention và MLP) làm nền cho sơ đồ kiến trúc trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=gBMO1JZav44&quot;&gt;How FlashAttention Accelerates Generative AI Revolution&lt;/a&gt; — Jia-Bin Huang, tiếng Anh. Giải thích FlashAttention dưới góc nhìn lưu lượng bộ nhớ HBM/SRAM.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PZXN7jm9IC0&quot;&gt;Chinchilla Explained: Compute-Optimal Massive Language Models&lt;/a&gt; — Edan Meyer, tiếng Anh. Trình bày phân tích định luật mở rộng Chinchilla tương ứng với phần hạch toán trong bài.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-06 Luyện phỏng vấn</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_06_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_06_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Phỏng vấn vị trí kỹ sư LLM năm 2026 không còn dừng ở việc đọc thuộc định nghĩa Self-Attention: nhà tuyển dụng sẽ đặt thẳng trước mặt bạn một bài toán sản phẩm thực tế — “Khi nào nên dùng Prompting, khi nào dùng RAG, khi nào phải Fine-Tune?” hay “Tại sao nhân \(T^2\) trong công thức chưng cất của Hinton?” Bài luyện phỏng vấn này tổng hợp các câu hỏi phân loại trình độ Senior/Staff kèm khung tư duy trả lời sắc bén và chính xác toán học.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trục-kiến-thức-trọng-tâm-trong-phỏng-vấn-kỹ-sư-llm&quot;&gt;Kiến thức cần nhớ: Bốn trục kiến thức trọng tâm trong phỏng vấn kỹ sư LLM&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bản chất mục tiêu tiền huấn luyện:&lt;/strong&gt; Phân biệt rõ dự đoán token kế tiếp (tối thiểu hóa phân kỳ KL tới phân phối văn bản) với “học sự thật khách quan”, từ đó giải thích căn nguyên toán học của hiện tượng ảo giác (&lt;em&gt;hallucination&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ma trận quyết định Prompting vs. RAG vs. Fine-Tuning:&lt;/strong&gt; Prompting cho định hướng nhanh; RAG cho tri thức động, riêng tư và cần trích dẫn nguồn; Fine-Tuning/LoRA cho thay đổi phong cách, định dạng chuyên sâu hoặc kỹ năng miền hẹp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chiến lược Chưng cất và Lượng tử hóa:&lt;/strong&gt; Giải thích rành mạch đánh đổi giữa chưng cất dữ liệu tổng hợp (hộp đen) vs. logit (hộp trắng), và vai trò hệ số \(T^2\) cân bằng độ lớn gradient theo nhiệt độ \(T\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hạch toán hệ thống suy luận (System Accounting):&lt;/strong&gt; Biết tính nhẩm VRAM trọng số, KV Cache, điểm chuyển đổi compute-bound/memory-bound và lý do cần GQA + Continuous Batching.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-chứng-minh-nhanh-bằng-số-vì-sao-công-thức-chưng-cất-phải-nhân-thêm-hệ-số-t2&quot;&gt;Giải thích: Chứng minh nhanh bằng số vì sao công thức chưng cất phải nhân thêm hệ số \(T^2\)&lt;/h3&gt;

&lt;p&gt;Trong chưng cất tri thức với nhiệt độ \(T\), xác suất làm mềm là \(q_i = \text{softmax}(z_i / T)\) và \(p_i = \text{softmax}(v_i / T)\). Khi \(T\) lớn (\(e^{z_i/T} \approx 1 + z_i/T\)) và giả sử logit có trung bình bằng 0, đạo hàm của phân kỳ KL theo logit học sinh \(z_i\) là:
\(\frac{\partial D_{\text{KL}}(p \| q)}{\partial z_i} = \frac{1}{T}(q_i - p_i) \approx \frac{1}{T}\left(\frac{1 + z_i/T}{K} - \frac{1 + v_i/T}{K}\right) = \frac{1}{K T^2}(z_i - v_i).\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiểm chứng bằng số với \(T = 4\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nếu &lt;strong&gt;không nhân \(T^2\)&lt;/strong&gt;: độ lớn gradient từ nhánh KL bị thu nhỏ đi \(T^2 = 4^2 = 16\text{ lần}\) so với nhánh Cross-Entropy nhãn cứng (ở \(T = 1\))!&lt;/li&gt;
  &lt;li&gt;Khi &lt;strong&gt;nhân thêm \(T^2 = 16\)&lt;/strong&gt; vào số hạng mất mát KL: nhân tử \(1/T^2\) bị triệt tiêu hoàn toàn, giữ cho cường độ gradient của nhánh thầy luôn cân bằng bất kể bạn thử nghiệm \(T = 2, 4\) hay \(8\)!&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;tùy-chọn-câu-hỏi-luyện-phỏng-vấn-về-llm&quot;&gt;Tùy chọn: Câu hỏi luyện phỏng vấn về LLM&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế nội dung các bài &lt;strong&gt;26-01&lt;/strong&gt; đến &lt;strong&gt;26-05&lt;/strong&gt; hay &lt;strong&gt;26-07&lt;/strong&gt;. Bộ câu hỏi dưới đây được biên soạn riêng cho khóa học để tự kiểm tra sau khi hoàn thành chương.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Hãy luyện tập khi đã nắm vững hàm mất mát dự đoán token kế tiếp, sự khác biệt giữa ICL và SFT, quy trình SFT → tối ưu sở thích, KV-cache, ba nhóm chưng cất và các công thức ước lượng FLOPs/bộ nhớ ở bài &lt;strong&gt;26-07&lt;/strong&gt;. Lộ trình luyện phỏng vấn toàn khóa nằm ở bài &lt;strong&gt;01-98&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;p1-tiền-huấn-luyện-thực-sự-tối-ưu-điều-gì&quot;&gt;P1. Tiền huấn luyện thực sự tối ưu điều gì?&lt;/h2&gt;

&lt;p&gt;Trong khoảng hai phút, hãy định nghĩa LLM theo phạm vi chương này trong một câu, nêu hàm mất mát tiền huấn luyện và những tính chất mà hàm mất mát đó &lt;em&gt;không&lt;/em&gt; tự đảm bảo.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Kiến trúc chỉ-decoder, dự đoán token kế tiếp, không đảm bảo tính đúng đắn sự kiện.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; LLM là mô hình ngôn ngữ Transformer nhân quả được huấn luyện bằng cross-entropy dự đoán token kế tiếp trên kho văn bản lớn. Hàm mất mát tối ưu hóa xác suất xuất hiện theo thống kê ngữ liệu, chứ không trực tiếp đảm bảo tính xác thực sự kiện, khả năng tuân thủ chỉ dẫn hay chi phí bộ nhớ thấp — những yêu cầu đó cần các bước thích nghi và tối ưu ở phía sau (&lt;strong&gt;26-02&lt;/strong&gt; đến &lt;strong&gt;26-04&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;p2-prompting-tinh-chỉnh-và-truy-hồi-rag&quot;&gt;P2. Prompting, tinh chỉnh và truy hồi (RAG)&lt;/h2&gt;

&lt;p&gt;Một đồng nghiệp yêu cầu “mô hình phải luôn trả về đúng cấu trúc JSON hóa đơn của công ty”. Hãy nêu một giải pháp bằng &lt;em&gt;prompting&lt;/em&gt;, một giải pháp cập nhật trọng số và một lý do vẫn có thể cần truy hồi thông tin.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Khuôn mẫu / ICL; SFT hoặc LoRA; phân biệt định dạng với dữ liệu sự kiện.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Ràng buộc định dạng JSON cố định có thể giải quyết bằng prompt có cấu trúc kèm ví dụ &lt;em&gt;few-shot&lt;/em&gt;, hoặc bằng SFT/LoRA nếu cần độ ổn định cao và prompt gọn. Trong khi đó, truy hồi (&lt;strong&gt;18-99&lt;/strong&gt;) vẫn cần thiết cho các dữ liệu thay đổi theo thời gian như danh mục mã sản phẩm (SKU) hay điều khoản hiện hành, vì prompting và căn chỉnh không thể tự tạo ra dữ liệu nghiệp vụ mới.&lt;/p&gt;

&lt;h2 id=&quot;p3-vì-sao-không-phải-lúc-nào-cũng-chưng-cất-theo-logit&quot;&gt;P3. Vì sao không phải lúc nào cũng chưng cất theo logit?&lt;/h2&gt;

&lt;p&gt;Nêu hai lý do khiến một nhóm kỹ sư chỉ sử dụng API hội thoại thương mại sẽ chọn &lt;strong&gt;chưng cất qua phản hồi&lt;/strong&gt; thay vì chưng cất đầy đủ phân bố token như công thức năm 2015.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Quyền truy cập và kích thước từ vựng \(V\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Thứ nhất, hầu hết API chỉ trả về văn bản (hoặc vài &lt;em&gt;logprob&lt;/em&gt; đầu), không cung cấp toàn bộ vectơ phân bố \(V\) chiều tại mỗi bước. Thứ hai, ngay cả khi có logit, việc lưu trữ và tính toán trên vectơ kích thước \(V\) cho các chuỗi dài vẫn rất tốn kém; do đó văn bản đầu ra là tín hiệu khả thi hơn về mặt kỹ thuật (và chỉ được phép sử dụng khi điều khoản dịch vụ cho phép).&lt;/p&gt;

&lt;h2 id=&quot;p4-vai-trò-của-nhiệt-độ-t-trong-chưng-cất&quot;&gt;P4. Vai trò của nhiệt độ \(T\) trong chưng cất&lt;/h2&gt;

&lt;p&gt;Một mô hình giáo viên đạt xác suất 99,9% cho lớp đúng trên ImageNet. Vì sao cần tăng nhiệt độ \(T\) trước khi tính phân kỳ KL, và điều gì xảy ra nếu tăng \(T\) quá lớn đồng thời bỏ hẳn số hạng nhãn cứng?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Tri thức ẩn đối lập với phân bố đều.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Tăng \(T\) làm nổi bật xác suất của các lớp ngoài lớp đúng, giúp bộc lộ mối quan hệ tương đồng giữa các lớp (tri thức ẩn). Tuy nhiên, khi \(T \to \infty\), phân bố tiến về phân bố đều, khiến mô hình học sinh mất thông tin phân biệt. Giữ số hạng cross-entropy trên nhãn cứng (hoặc chọn \(T\) vừa phải) giúp neo giữ đỉnh phân bố chính xác. Với phân bố token rất nhọn trong LLM, thực tế thường kết hợp cắt &lt;em&gt;top-k&lt;/em&gt; thay vì chỉ tăng \(T\) thật lớn.&lt;/p&gt;

&lt;h2 id=&quot;p5-tối-ưu-phục-vụ-trước-khi-chưng-cất&quot;&gt;P5. Tối ưu phục vụ trước khi chưng cất&lt;/h2&gt;

&lt;p&gt;Nêu hai biện pháp bạn sẽ thử &lt;strong&gt;trước khi&lt;/strong&gt; huấn luyện một mô hình học sinh 8B từ mô hình giáo viên 70B tự sở hữu, và một tình huống vẫn cần chưng cất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Thứ tự ưu tiên từ &lt;strong&gt;26-04&lt;/strong&gt; sang &lt;strong&gt;26-05&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Trước hết nên thử lượng tử hóa (4-bit / GGUF), cắt giảm ngữ cảnh thừa, áp dụng &lt;em&gt;continuous batching&lt;/em&gt; hoặc &lt;em&gt;speculative decoding&lt;/em&gt;. Chưng cất trở nên cần thiết khi &lt;em&gt;bản thân kiến trúc&lt;/em&gt; bắt buộc phải thu nhỏ (ví dụ triển khai trên thiết bị biên, cần phân khúc chi phí thấp hơn hoặc cần một mô hình nền nhỏ để gắn nhiều &lt;em&gt;adapter&lt;/em&gt; LoRA) — điều mà lượng tử hóa trên cùng bộ trọng số 70B không đáp ứng được.&lt;/p&gt;

&lt;h2 id=&quot;p6-phân-biệt-chưng-cất-hợp-lệ-và-sử-dụng-trái-điều-khoản&quot;&gt;P6. Phân biệt chưng cất hợp lệ và sử dụng trái điều khoản&lt;/h2&gt;

&lt;p&gt;Trong bốn câu, hãy phân biệt giữa chưng cất hợp lệ và việc thu thập dữ liệu đầu ra trái phép.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Quyền sở hữu mô hình giáo viên và mục đích của giao diện API.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Khi bạn sở hữu mô hình giáo viên hoặc sử dụng mô hình nguồn mở có giấy phép cho phép chưng cất và sinh dữ liệu tổng hợp, chưng cất là kỹ thuật nén và tối ưu sản phẩm hoàn toàn hợp lệ. Ngược lại, với API dịch vụ của bên thứ ba, văn bản đầu ra chịu ràng buộc của điều khoản sử dụng và thường bị cấm dùng để huấn luyện mô hình cạnh tranh. Mâu thuẫn mang tính cấu trúc này xuất phát từ việc một API hữu ích tự nhiên phát ra chuỗi token mang giá trị như tín hiệu huấn luyện.&lt;/p&gt;

&lt;h2 id=&quot;p7-đạo-hàm-softmax-và-cơ-chế-softmax-trực-tuyến&quot;&gt;P7. Đạo hàm softmax và cơ chế softmax trực tuyến&lt;/h2&gt;

&lt;p&gt;Viết biểu thức \(\partial\mathcal{L}/\partial z\) cho cross-entropy theo token sau softmax. Sau đó nêu ngắn gọn vai trò của &lt;em&gt;log-sum-exp&lt;/em&gt; và đóng góp của &lt;em&gt;online softmax&lt;/em&gt; trong FlashAttention.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; \(p - t\) và giá trị lớn nhất cập nhật theo khối.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Với nhãn &lt;em&gt;one-hot&lt;/em&gt; \(t\), đạo hàm là \(\partial\mathcal{L}/\partial z = p - t\). Phép &lt;em&gt;log-sum-exp&lt;/em&gt; trừ đi giá trị lớn nhất của hàng để tránh tràn số khi tính \(e^z\). &lt;em&gt;Online softmax&lt;/em&gt; duy trì giá trị cực đại tạm thời, tổng chuẩn hóa và tổng có trọng số của \(V\) khi duyệt qua từng khối, giúp FlashAttention không phải lưu toàn bộ ma trận \(L \times L\) xuống HBM (&lt;strong&gt;26-01&lt;/strong&gt;, &lt;strong&gt;26-07&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;p8-cấu-trúc-khối-decoder-hiện-đại-và-ước-lượng-chi-phí&quot;&gt;P8. Cấu trúc khối decoder hiện đại và ước lượng chi phí&lt;/h2&gt;

&lt;p&gt;Phác thảo một tầng decoder hiện đại (RMSNorm → attention nhân quả + RoPE → residual → RMSNorm → SwiGLU → residual), sau đó nêu ước lượng thứ tự độ lớn cho FLOPs lan truyền xuôi mỗi token và hai thành phần chính của bộ nhớ suy luận.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; \(2N\) FLOPs; trọng số cộng KV-cache.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Lan truyền xuôi tốn khoảng \(2 N_{\mathrm{params}}\) FLOPs cho mỗi token, lan truyền ngược tốn khoảng gấp đôi (\(\approx 4 N_{\mathrm{params}}\)), nên toàn bộ huấn luyện xấp xỉ \(6 N T\) FLOPs. Bộ nhớ suy luận gồm dung lượng lưu trọng số cộng KV-cache; phần KV-cache tăng tuyến tính theo độ dài chuỗi \(L\) và tỉ lệ với số đầu \(n_{\mathrm{kv}}\) (giảm nhờ GQA). Khi ước lượng cụ thể, luôn tính từ \(d\), \(n_{\mathrm{layers}}\) và \(V\) thay vì đoán số.&lt;/p&gt;

&lt;h2 id=&quot;p9-speculative-decoding-khác-gì-với-chưng-cất&quot;&gt;P9. Speculative Decoding khác gì với chưng cất?&lt;/h2&gt;

&lt;p&gt;Một đồng nghiệp nói: “&lt;em&gt;Speculative decoding&lt;/em&gt; là cách chúng ta huấn luyện mô hình học sinh 8B”. Hãy chỉnh lại nhận định này trong bốn câu và viết công thức lấy mẫu theo nhiệt độ cùng &lt;em&gt;top-p&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Giữ nguyên phân bố mô hình đích so với huấn luyện bộ trọng số \(\theta\) mới.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; &lt;em&gt;Speculative decoding&lt;/em&gt; là kỹ thuật tối ưu ở tầng &lt;em&gt;phục vụ&lt;/em&gt;: mô hình nháp nhỏ đề xuất trước vài token và mô hình đích lớn kiểm định song song, giữ nguyên chính xác phân bố đầu ra của mô hình đích (&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Leviathan et al., 2023&lt;/a&gt;). Ngược lại, chưng cất huấn luyện một bộ trọng số \(\theta\) hoàn toàn mới cho mô hình nhỏ hơn. Khi lấy mẫu, phân bố theo nhiệt độ là \(p_i^{(T)} \propto e^{z_i / T}\), còn &lt;em&gt;top-p&lt;/em&gt; giữ lại tập token nhỏ nhất có tổng xác suất tích lũy \(\ge p\) rồi chuẩn hóa lại (&lt;strong&gt;26-04&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;p10-phân-bổ-tối-ưu-theo-tính-toán-kaplan-và-chinchilla&quot;&gt;P10. Phân bổ tối ưu theo tính toán (Kaplan và Chinchilla)&lt;/h2&gt;

&lt;p&gt;Với ngân sách FLOP huấn luyện cố định \(C \approx 6NT\), kết luận ban đầu của Kaplan et al. nhấn mạnh điều gì và nghiên cứu Chinchilla của Hoffmann et al. đã điều chỉnh ra sao (không cần nêu số mũ thực nghiệm)?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Tỉ lệ cân đối giữa số tham số \(N\) và số token \(T\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Kaplan et al. (2020) cho thấy trong thiết lập của họ, tăng số tham số \(N\) nhanh hơn số token \(T\) có vẻ hiệu quả hơn. Hoffmann et al. (2022) chạy lại thí nghiệm theo đường đồng mức FLOP (&lt;em&gt;isoFLOP&lt;/em&gt;) và chỉ ra nhiều mô hình trước đó bị thiếu dữ liệu huấn luyện, nên cần mở rộng &lt;strong&gt;đồng thời cả \(N\) và \(T\)&lt;/strong&gt;. Trong thực tế sản phẩm sau này, nhiều mô hình còn được huấn luyện &lt;em&gt;vượt&lt;/em&gt; ngưỡng Chinchilla (nhiều token hơn cho cùng \(N\)) để đổi lấy mô hình nhỏ hơn và rẻ hơn khi phục vụ suy luận (&lt;strong&gt;26-07&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;cách-sử-dụng-bài-luyện&quot;&gt;Cách sử dụng bài luyện&lt;/h2&gt;

&lt;p&gt;Hãy tự trình bày câu trả lời thành lời trong khoảng 90 giây trước khi đối chiếu với phần thảo luận. Nếu cần ôn lại toán RL, xem &lt;strong&gt;21-99&lt;/strong&gt;; công thức KD cổ điển nằm ở &lt;strong&gt;23-01&lt;/strong&gt; và &lt;strong&gt;26-05&lt;/strong&gt;; sơ đồ khối decoder và hạch toán FLOPs nằm ở &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=7xTGNNLPyMI&quot;&gt;Deep Dive into LLMs like ChatGPT&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Hệ thống hóa quá trình huấn luyện và phục vụ LLM trước khi tự trả lời các câu hỏi phỏng vấn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is cross-entropy?&lt;/td&gt;
          &lt;td&gt;Compression is Intelligence Part 2](https://www.youtube.com/watch?v=GlYgs6v2YfU) — 3Blue1Brown, tiếng Anh. Ôn trực quan cross-entropy và đạo hàm softmax cho câu P7.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, tiếng Anh. Minh họa cấu trúc khối Transformer phục vụ câu hỏi P8.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-05 Chưng cất mô hình cho LLM</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_05_Model_Distillation_for_LLMs/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_05_Model_Distillation_for_LLMs</id>
   <content type="html">&lt;p&gt;Ở Chương 23, chưng cất tri thức (Knowledge Distillation) trông rất gọn gàng: chỉ cần lấy toàn bộ vector logit của mô hình thầy chia nhiệt độ \(T\) rồi dạy mô hình học sinh. Nhưng bước sang thế giới LLM, công thức đó lập tức vấp phải ba bức tường thực tế: từ điển thầy–trò có thể khác nhau, ma trận logit cho chuỗi 4.096 token với từ điển 128.000 từ nặng hàng gigabyte, và nhiều mô hình thầy mạnh nhất chỉ mở qua API “hộp đen”! Bài học này giải mã ba trường phái chưng cất LLM hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-chưng-cất-mô-hình-cho-llm&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Chưng cất Mô hình cho LLM&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Ôn lại KD cổ điển và điểm nghẽn trên LLM:&lt;/strong&gt; Khi $$&lt;/td&gt;
          &lt;td&gt;V&lt;/td&gt;
          &lt;td&gt;= 128{,}000$$, việc lưu và truyền phân phối Softmax đầy đủ trên mỗi token trở nên quá đắt đỏ, chưa kể bài toán lệch bộ tách từ (&lt;em&gt;tokenizer mismatch&lt;/em&gt;).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhóm 1 — Chưng cất hộp đen qua dữ liệu tổng hợp (Sequence-Level / CoT Distillation):&lt;/strong&gt; Dùng mô hình thầy sinh lời giải kèm chuỗi tư duy chi tiết, lọc chất lượng bằng bộ kiểm chứng (verifier), rồi huấn luyện SFT cho học sinh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhóm 2 — Chưng cất hộp trắng cấp Logit (Forward KL, Reverse KL, Skew KL):&lt;/strong&gt; Chỉ dùng Top-\(k\) logit hoặc đảo chiều phân kỳ KL (Reverse KL tập trung vào mode chính thay vì trải phẳng &lt;em&gt;mode-covering&lt;/em&gt; như Forward KL).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhóm 3 — Chưng cất On-Policy (GKD / MiniLLM):&lt;/strong&gt; Để chính mô hình học sinh tự sinh chuỗi rồi nhờ thầy chấm logit ngay trên quỹ đạo đó, khắc phục triệt để lệch phân phối (&lt;em&gt;exposure bias&lt;/em&gt;) lúc suy luận.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-dung-lượng-lưu-trữ-ma-trận-logit-đầy-đủ-vs-top-k-và-so-sánh-forward-kl-vs-reverse-kl&quot;&gt;Giải thích: Tính dung lượng lưu trữ ma trận Logit đầy đủ vs. Top-\(k\) và so sánh Forward KL vs. Reverse KL&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Vì sao không thể lưu toàn bộ Logit của LLM?&lt;/strong&gt;
Xét chỉ &lt;strong&gt;1 chuỗi&lt;/strong&gt; dài \(L = 4{,}096\) token với từ điển \(|V| = 128{,}000\) lưu ở FP16 (\(2\text{ byte/số}\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Lưu toàn bộ logit: \(4{,}096 \times 128{,}000 \times 2\text{ byte} \approx 1{,}05\text{ GB}\) cho &lt;em&gt;một&lt;/em&gt; ví dụ duy nhất! Với 1 triệu ví dụ sẽ tốn hơn &lt;strong&gt;1 Petabyte&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;Chỉ lưu Top-\(k = 64\) logit cao nhất (kèm chỉ số token 4 byte): \(4{,}096 \times 64 \times (2 + 4)\text{ byte} \approx 1{,}57\text{ MB}\) — &lt;strong&gt;nhỏ hơn 668 lần&lt;/strong&gt; mà vẫn giữ gần trọn khối xác suất.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Khác biệt hành vi giữa Forward KL và Reverse KL:&lt;/strong&gt;
Giả sử thầy đặt xác suất lên 2 câu trả lời hợp lệ \(p = [0{,}5,\; 0{,}5,\; 0{,}0]\) (token 3 sai hoàn toàn), còn học sinh nhỏ chỉ đủ sức học 1 kiểu trả lời:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Forward KL&lt;/strong&gt; \(\sum p_i \ln(p_i/q_i)\): nếu học sinh gán \(q_2 \to 0\) thì \(0{,}5\ln(0{,}5/0) \to +\infty\) → ép học sinh trải đều xác suất (dễ rớt vào vùng trung bình vô nghĩa).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Reverse KL&lt;/strong&gt; \(\sum q_i \ln(q_i/p_i)\): cho phép học sinh tập trung vào 1 mode tốt (\(q = [0{,}98, 0{,}02, 0]\) chỉ chịu phạt hữu hạn \(\approx 0{,}60\)) nhưng phạt cực nặng nếu học sinh lỡ gán xác suất cho token sai \(p_3 = 0\) — giúp LLM học sinh ít bịa đặt hơn!&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;chưng-cất-mô-hình-cho-llm&quot;&gt;Chưng cất mô hình cho LLM&lt;/h1&gt;

&lt;p&gt;Chương 23 đã giới thiệu &lt;strong&gt;chưng cất tri thức (KD)&lt;/strong&gt; như một phương pháp nén mô hình: huấn luyện một mạng học sinh nhỏ khớp theo dự đoán của mạng giáo viên lớn. Nguyên lý đó vẫn giữ nguyên đối với LLM, nhưng có hai điểm thay đổi quan trọng: &lt;em&gt;không gian đầu ra&lt;/em&gt; là một từ vựng rất lớn dự đoán tuần tự từng bước, và &lt;em&gt;mức độ truy cập&lt;/em&gt; tới giáo viên có thể chỉ là đầu ra văn bản thay vì toàn bộ trọng số.&lt;/p&gt;

&lt;p&gt;Bài này ôn lại KD cổ điển, phân tích lý do công thức năm 2015 trở nên khó áp dụng trực tiếp cho mô hình ngôn ngữ tự hồi quy, sau đó phân loại ba nhóm phương pháp chưng cất hiện đại kèm mã minh họa.&lt;/p&gt;

&lt;h2 id=&quot;1-ôn-tập-kd-cổ-điển-nền-tảng-chương-23&quot;&gt;1. Ôn tập KD cổ điển (nền tảng Chương 23)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/1503.02531&quot;&gt;Hinton, Vinyals và Dean, 2015&lt;/a&gt; (&lt;em&gt;Distilling the Knowledge in a Neural Network&lt;/em&gt;) huấn luyện mô hình học sinh trên phân bố xác suất &lt;strong&gt;mềm&lt;/strong&gt; của mô hình giáo viên thay vì chỉ dùng nhãn cứng &lt;em&gt;one-hot&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lợi ích của mục tiêu mềm:&lt;/strong&gt; Nhãn cứng chỉ cho biết “ảnh này thuộc lớp 7”. Một mô hình giáo viên đã huấn luyện có thể dự đoán “lớp 7: 0,80; lớp 3: 0,15; lớp 8: 0,04…”. Phần xác suất phân bổ trên các lớp còn lại thể hiện &lt;em&gt;mức độ tương đồng giữa các lớp&lt;/em&gt; — điều mà Hinton et al. gọi là &lt;strong&gt;tri thức ẩn&lt;/strong&gt; (&lt;em&gt;dark knowledge&lt;/em&gt;), cung cấp tín hiệu gradient giàu thông tin hơn so với nhãn đúng/sai đơn thuần.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vai trò của nhiệt độ \(T\):&lt;/strong&gt; Ở \(T = 1\), phân bố của giáo viên thường quá nhọn (gần như &lt;em&gt;one-hot&lt;/em&gt;), làm mờ phần tri thức ẩn. Softmax có nhiệt độ:&lt;/p&gt;

\[p_i^{(T)} = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}\]

&lt;p&gt;làm phẳng phân bố khi tăng \(T &amp;gt; 1\). Mô hình học sinh khớp theo \(p_{\mathrm{teacher}}^{(T)}\) bằng phân kỳ KL kết hợp với hàm mất mát trên nhãn cứng:&lt;/p&gt;

\[\mathcal{L} = \alpha\, T^{2}\, \mathrm{KL}\big(p_{\mathrm{teacher}}^{(T)} \,\|\, p_{\mathrm{student}}^{(T)}\big) + (1-\alpha)\,\mathrm{CE}(y, z_{\mathrm{student}}).\]

&lt;p&gt;Hệ số \(T^{2}\) bù lại sự suy giảm biên độ gradient khi tăng \(T\), còn \(\alpha\) cân bằng giữa việc học theo giáo viên và khớp nhãn gốc. Đây là thiết lập chuẩn cho bài toán &lt;strong&gt;phân loại với số lớp \(K\) cố định&lt;/strong&gt; (như ImageNet; xem lại bài &lt;strong&gt;23-01&lt;/strong&gt; nếu cần).&lt;/p&gt;

&lt;h2 id=&quot;2-vì-sao-kd-logit-cổ-điển-khó-áp-dụng-trực-tiếp-cho-llm&quot;&gt;2. Vì sao KD logit cổ điển khó áp dụng trực tiếp cho LLM?&lt;/h2&gt;

&lt;p&gt;Một LLM chỉ-decoder thực hiện phân loại &lt;em&gt;tại mọi vị trí trong chuỗi&lt;/em&gt; với số lớp \(K = V\) lên tới hàng chục hoặc hàng trăm nghìn. Điều này gây ra bốn trở ngại thực tế:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Chi phí lưu trữ và tính toán:&lt;/strong&gt; Lưu hoặc truyền toàn bộ phân bố giáo viên tại mỗi token đòi hỏi bộ nhớ và I/O cỡ \(O(V)\), nhanh chóng vượt trội chi phí tính toán của chính mô hình học sinh trên chuỗi dài.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính thưa của phân bố:&lt;/strong&gt; Dù có tăng nhẹ nhiệt độ \(T\), phần lớn xác suất vẫn dồn vào một số ít token; khớp toàn bộ \(V\) phần tử gây lãng phí trừ khi cắt theo &lt;em&gt;top-k&lt;/em&gt; hoặc lấy mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giới hạn quyền truy cập:&lt;/strong&gt; KD theo logit đòi hỏi quyền truy cập &lt;strong&gt;hộp trắng&lt;/strong&gt; (hoặc ít nhất truy cập đầy đủ logit) vào mô hình giáo viên, trong khi nhiều giao diện API chỉ trả về văn bản (hoặc một vài &lt;em&gt;logprob&lt;/em&gt; đầu bảng).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính tuần tự của chuỗi:&lt;/strong&gt; Sai số tích lũy dần qua từng bước sinh; khớp phân bố token của giáo viên &lt;em&gt;trên tiền tố của giáo viên&lt;/em&gt; không hoàn toàn đồng nghĩa với khớp &lt;em&gt;toàn bộ câu trả lời&lt;/em&gt; khi học sinh tự sinh.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Vì vậy, KD theo logit vẫn được dùng trong nội bộ các tổ chức sở hữu cả giáo viên lẫn học sinh (thường kết hợp cắt &lt;em&gt;top-k&lt;/em&gt;), nhưng hiếm khi được dùng trực tiếp như công thức mặc định cho mọi bài toán LLM.&lt;/p&gt;

&lt;h2 id=&quot;3-ba-nhóm-phương-pháp-chưng-cất-hiện-đại&quot;&gt;3. Ba nhóm phương pháp chưng cất hiện đại&lt;/h2&gt;

&lt;p&gt;Các phương pháp chưng cất LLM có thể phân nhóm theo &lt;strong&gt;mục tiêu học sinh cần khớp&lt;/strong&gt; và &lt;strong&gt;mức độ truy cập giáo viên yêu cầu&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;31-chưng-cất-qua-dữ-liệu-tổng-hợp--phản-hồi-hộp-đen&quot;&gt;3.1 Chưng cất qua dữ liệu tổng hợp / phản hồi (hộp đen)&lt;/h3&gt;

&lt;p&gt;Mô hình giáo viên sinh các câu trả lời mẫu — gồm đáp án, chuỗi suy luận từng bước, mã nguồn hoặc bản viết lại tài liệu. Ta lưu tập cặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(prompt, teacher_text)&lt;/code&gt; rồi huấn luyện mô hình học sinh bằng SFT dự đoán token kế tiếp thông thường (có thể trộn thêm dữ liệu do con người viết).&lt;/p&gt;

&lt;p&gt;Đây là hướng tiếp cận &lt;strong&gt;hộp đen&lt;/strong&gt; phổ biến nhất vì chỉ cần mẫu văn bản đầu ra từ giáo viên mà không cần logit hay trạng thái ẩn. Nhiều dự án tinh chỉnh mô hình nhỏ tuân thủ chỉ dẫn, cũng như các mô hình học sinh học theo chuỗi suy luận dài từ mô hình suy luận lớn, đều thuộc nhóm này.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Giới hạn cần lưu ý:&lt;/strong&gt; Học sinh học được hành vi bề mặt và phong cách xử lý trong phạm vi các prompt đã phủ, nhưng không tự động kế thừa độ hiệu chỉnh xác suất trên toàn từ vựng hay các năng lực không xuất hiện trong tập dữ liệu sinh. Vì giáo viên có thể sinh các mẫu khác nhau cho cùng một prompt, khâu thiết kế tập prompt, lọc chất lượng và trộn dữ liệu thật đóng vai trò quyết định không kém hàm mất mát.&lt;/p&gt;

&lt;h3 id=&quot;32-chưng-cất-đặc-trưng--trạng-thái-ẩn-hộp-trắng&quot;&gt;3.2 Chưng cất đặc trưng / trạng thái ẩn (hộp trắng)&lt;/h3&gt;

&lt;p&gt;Mô hình học sinh được huấn luyện để khớp các biểu diễn trung gian của giáo viên như trạng thái ẩn, bản đồ &lt;em&gt;attention&lt;/em&gt; hoặc phép chiếu luồng phần dư (&lt;em&gt;residual stream&lt;/em&gt;). Cách này đòi hỏi &lt;strong&gt;quyền truy cập hộp trắng&lt;/strong&gt; vào mô hình giáo viên cùng các lớp chiếu trung gian (&lt;em&gt;adapter&lt;/em&gt;) khi số chiều hoặc độ sâu khác nhau, tương tự các phương pháp khớp đặc trưng trong thị giác máy tính.&lt;/p&gt;

&lt;h3 id=&quot;33-chưng-cất-logit--phân-bố-token-hộp-trắng&quot;&gt;3.3 Chưng cất logit / phân bố token (hộp trắng)&lt;/h3&gt;

&lt;p&gt;Áp dụng trực tiếp ý tưởng năm 2015 tại từng vị trí chuỗi: khớp \(p_{\mathrm{student}}(\cdot \mid x_{&amp;lt;t})\) với \(p_{\mathrm{teacher}}(\cdot \mid x_{&amp;lt;t})\), thường kết hợp nhiệt độ, cắt &lt;em&gt;top-k&lt;/em&gt; hoặc biến thể &lt;em&gt;reverse-KL&lt;/em&gt; để mô hình học sinh tập trung vào các chế độ xác suất chính. &lt;a href=&quot;https://arxiv.org/abs/1910.01108&quot;&gt;Sanh et al., 2019&lt;/a&gt; (DistilBERT) là ví dụ kinh điển cho kiến trúc encoder, còn với mô hình sinh tự hồi quy có các nghiên cứu như MiniLLM (&lt;a href=&quot;https://arxiv.org/abs/2306.08543&quot;&gt;Gu et al., 2024&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Đây là cách chuyển giao phân bố sát nhất nhưng đòi hỏi điều kiện chặt chẽ nhất: dùng chung tokenizer (hoặc có ánh xạ tương thích), đủ tài nguyên tính hoặc lưu logit giáo viên và thống nhất chính sách chọn tiền tố.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Nhóm phương pháp&lt;/th&gt;
      &lt;th&gt;Mục tiêu học sinh khớp&lt;/th&gt;
      &lt;th&gt;Quyền truy cập giáo viên&lt;/th&gt;
      &lt;th&gt;Ứng dụng phổ biến&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Phản hồi / dữ liệu tổng hợp&lt;/td&gt;
      &lt;td&gt;Văn bản đầu ra (và chuỗi suy luận nếu có)&lt;/td&gt;
      &lt;td&gt;Chỉ cần mẫu đầu ra&lt;/td&gt;
      &lt;td&gt;Giáo viên nguồn mở, tập SFT sản phẩm&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Đặc trưng / trạng thái ẩn&lt;/td&gt;
      &lt;td&gt;Giá trị kích hoạt ở các tầng trung gian&lt;/td&gt;
      &lt;td&gt;Hộp trắng&lt;/td&gt;
      &lt;td&gt;Nội bộ, kiến trúc cùng họ&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Logit / phân bố token&lt;/td&gt;
      &lt;td&gt;Phân bố softmax trên từ vựng \(V\)&lt;/td&gt;
      &lt;td&gt;Hộp trắng (hoặc đủ &lt;em&gt;logprob&lt;/em&gt;)&lt;/td&gt;
      &lt;td&gt;Nội bộ, dùng chung tokenizer&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Trong thực tế, nhiều quy trình kết hợp hai hướng: tạo tập SFT tổng hợp rồi bổ sung thêm số hạng khớp logit trên một tập con token khi cả hai mô hình cùng chạy nội bộ.&lt;/p&gt;

&lt;h2 id=&quot;4-sử-dụng-hợp-lệ-và-giới-hạn-điều-khoản&quot;&gt;4. Sử dụng hợp lệ và giới hạn điều khoản&lt;/h2&gt;

&lt;p&gt;Chưng cất là kỹ thuật nén và tối ưu hóa tiêu chuẩn khi bạn &lt;strong&gt;có quyền hợp lệ để huấn luyện từ trọng số hoặc đầu ra của mô hình giáo viên&lt;/strong&gt;, chẳng hạn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Thu nhỏ chính mô hình lớn của tổ chức mình thành phiên bản nhẹ hơn cho thiết bị biên, xử lý lô hoặc triển khai nội bộ.&lt;/li&gt;
  &lt;li&gt;Sử dụng các mô hình &lt;strong&gt;giấy phép mở&lt;/strong&gt; cho phép rõ ràng việc chưng cất hoặc sinh dữ liệu tổng hợp.&lt;/li&gt;
  &lt;li&gt;Nghiên cứu trên các mô hình công khai trong phạm vi điều khoản cho phép.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Vấn đề pháp lý và sản phẩm phát sinh từ đặc điểm cố hữu: &lt;strong&gt;đầu ra văn bản của một API đủ hữu ích cũng đồng thời là tín hiệu huấn luyện&lt;/strong&gt;. Do đó, nhiều nhà cung cấp đặt ra &lt;strong&gt;điều khoản dịch vụ&lt;/strong&gt; và biện pháp kỹ thuật (giới hạn tần suất, phát hiện lạm dụng) nhằm ngăn việc thu thập đầu ra API để huấn luyện mô hình cạnh tranh.&lt;/p&gt;

&lt;p&gt;Nguyên tắc thực hành rõ ràng: nếu bạn không sở hữu mô hình giáo viên và điều khoản dịch vụ cấm dùng đầu ra để huấn luyện mô hình khác, không nên xây dựng tập dữ liệu chưng cất từ API đó; hãy sử dụng mô hình giáo viên có giấy phép mở phù hợp, mô hình tự huấn luyện hoặc tập dữ liệu công khai. Nếu muốn đọc thêm góc nhìn tổng quan về chủ đề này, có thể tham khảo bài viết &lt;a href=&quot;https://machinelearningmastery.com/a-gentle-introduction-to-model-distillation/&quot;&gt;A Gentle Introduction to Model Distillation&lt;/a&gt; trên Machine Learning Mastery (Chugani, 2026).&lt;/p&gt;

&lt;h2 id=&quot;5-mã-minh-họa&quot;&gt;5. Mã minh họa&lt;/h2&gt;

&lt;h3 id=&quot;51-chưng-cất-có-nhiệt-độ-cho-bài-toán-phân-loại-cố-định&quot;&gt;5.1 Chưng cất có nhiệt độ cho bài toán phân loại cố định&lt;/h3&gt;

&lt;p&gt;Đoạn mã minh họa thiết lập của Chương 23, làm rõ vai trò hệ số \(T^{2}\) và chiều tính phân kỳ KL:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;classification_kd_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;teacher_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                           &lt;span class=&quot;n&quot;&gt;temperature&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Soft-target KD for a shared, small class set.

    student_logits, teacher_logits: (batch, num_classes)
    labels: (batch,) integer class ids
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temperature&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;hard&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;log_p_s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;p_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;teacher_logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# KL(teacher || student); T^2 restores gradient scale as T grows
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;soft&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;kl_div&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_p_s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reduction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;batchmean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;soft&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hard&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Khi mở rộng sang LLM, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;num_classes&lt;/code&gt; trở thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vocab_size&lt;/code&gt; lặp qua từng bước thời gian kèm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ignore_index&lt;/code&gt; cho phần đệm — từ đó thấy rõ vì sao thực tế thường chuyển sang cắt &lt;em&gt;top-k&lt;/em&gt; hoặc SFT trên văn bản.&lt;/p&gt;

&lt;h3 id=&quot;52-chưng-cất-qua-phản-hồi-dưới-dạng-tập-dữ-liệu-sft&quot;&gt;5.2 Chưng cất qua phản hồi dưới dạng tập dữ liệu SFT&lt;/h3&gt;

&lt;p&gt;Không cần định nghĩa hàm mất mát mới; dữ liệu do giáo viên sinh được tổ chức như một tập tinh chỉnh chỉ dẫn thông thường:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Mỗi hàng là văn bản giáo viên sinh; học sinh phải gán likelihood cao.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sft_rows&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;prompt&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Give a one-paragraph intuition for dropout.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;completion&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dropout randomly masks units at train time so ...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;prompt&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Now show a tiny numeric example.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;completion&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Suppose a hidden layer has four units and p=0.5 ...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Huấn luyện bằng CE token kế trên `completion` (và khuôn chat), như 26-01 / 26-02.
# Tùy chọn: giữ một phần do người viết để học sinh không chỉ chép tật của giáo viên.
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Nếu giáo viên sinh kèm chuỗi lập luận, phần lập luận đó được lưu ngay trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;completion&lt;/code&gt; (hoặc một trường riêng nối trước đáp án); thuật toán huấn luyện vẫn là SFT chuẩn, điểm khác biệt nằm ở nguồn tạo dữ liệu mục tiêu.&lt;/p&gt;

&lt;h2 id=&quot;6-đọc-thêm&quot;&gt;6. Đọc thêm&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Hinton, G., Vinyals, O. và Dean, J. (2015). &lt;a href=&quot;https://arxiv.org/abs/1503.02531&quot;&gt;Distilling the Knowledge in a Neural Network&lt;/a&gt; — bài báo gốc về mục tiêu mềm, nhiệt độ và tri thức ẩn.&lt;/li&gt;
  &lt;li&gt;Machine Learning Mastery — &lt;a href=&quot;https://machinelearningmastery.com/a-gentle-introduction-to-model-distillation/&quot;&gt;A Gentle Introduction to Model Distillation&lt;/a&gt; (Chugani, 2026) — tổng quan nhập môn so sánh chưng cất cổ điển và chưng cất thời LLM.&lt;/li&gt;
  &lt;li&gt;Các bài liên quan trong khóa học: &lt;strong&gt;23-01 Nén mô hình&lt;/strong&gt; (cắt tỉa, lượng tử hóa, KD cổ điển), &lt;strong&gt;23-99&lt;/strong&gt; (GPTQ, AWQ, &lt;em&gt;speculative decoding&lt;/em&gt;), &lt;strong&gt;26-04&lt;/strong&gt; (tối ưu phục vụ trước khi chưng cất) và &lt;strong&gt;26-07&lt;/strong&gt; (ước lượng FLOPs và bộ nhớ khi chọn kích thước học sinh).&lt;/li&gt;
  &lt;li&gt;Tài liệu kỹ thuật mở rộng: DistilBERT (&lt;a href=&quot;https://arxiv.org/abs/1910.01108&quot;&gt;Sanh et al., 2019&lt;/a&gt;), Distilling Step-by-Step (&lt;a href=&quot;https://arxiv.org/abs/2305.02301&quot;&gt;Hsieh et al., 2023&lt;/a&gt;) và MiniLLM (&lt;a href=&quot;https://arxiv.org/abs/2306.08543&quot;&gt;Gu et al., 2024&lt;/a&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;KD cổ điển huấn luyện học sinh khớp phân bố lớp mềm của giáo viên; tham số nhiệt độ giúp bộc lộ tri thức ẩn giữa các lớp.&lt;/li&gt;
  &lt;li&gt;Với LLM tự hồi quy, khớp đầy đủ logit trên toàn bộ từ vựng vừa tốn chi phí vừa thường không khả thi nếu thiếu quyền truy cập hộp trắng.&lt;/li&gt;
  &lt;li&gt;Các phương pháp chưng cất LLM hiện đại chia thành ba nhóm chính: &lt;strong&gt;phản hồi (dữ liệu tổng hợp)&lt;/strong&gt;, &lt;strong&gt;đặc trưng ẩn&lt;/strong&gt; và &lt;strong&gt;logit&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Chưng cất hợp lệ dựa trên mô hình tự sở hữu hoặc giấy phép mở cho phép; thu thập đầu ra API trái điều khoản là vấn đề pháp lý và hợp đồng.&lt;/li&gt;
  &lt;li&gt;Phân kỳ KL có nhiệt độ giúp hiểu bản chất lý thuyết, còn tập SFT sinh bởi giáo viên là định dạng huấn luyện phổ biến nhất cho các mô hình học sinh LLM.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=jrJKRYAdh7I&quot;&gt;Knowledge Distillation: How LLMs train each other&lt;/a&gt; — Julia Turc, tiếng Anh. Giải thích cách mô hình ngôn ngữ lớn huấn luyện mô hình nhỏ hơn, bám sát phần chưng cất hiện đại trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[2.3 Knowledge Distillation&lt;/td&gt;
          &lt;td&gt;Geoffery Hinton&lt;/td&gt;
          &lt;td&gt;Soft Labels&lt;/td&gt;
          &lt;td&gt;Softmax with Temperature](https://www.youtube.com/watch?v=g1r4Esohw-g) — AI_Snippets, tiếng Anh. Ôn lại chưng cất nhãn mềm và nhiệt độ của Hinton từ Chương 23.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, tiếng Anh. Giúp thấy bối cảnh chi phí bộ nhớ khi làm việc với từ vựng lớn, làm rõ hạn chế của KD logit thuần túy.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-04 Phục vụ và hiệu năng cho LLM</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_04_Serving_and_Efficiency/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_04_Serving_and_Efficiency</id>
   <content type="html">&lt;p&gt;Tại sao khi bạn gửi một văn bản dài 2.000 từ cho LLM, nó chỉ mất chưa đầy 1 giây để “đọc” hết toàn bộ văn bản đó, nhưng sau đó lại phải mất tới 5 giây chỉ để “viết” ra 200 từ trả lời? Bí mật nằm ở hai pha vật lý hoàn toàn trái ngược nhau trên GPU: &lt;strong&gt;Prefill&lt;/strong&gt; (nghẽn tính toán — compute-bound, chạy song song toàn bộ prompt) và &lt;strong&gt;Decode&lt;/strong&gt; (nghẽn băng thông bộ nhớ — memory-bandwidth-bound, sinh từng token một). Bài học này mở khóa toàn bộ nghệ thuật phục vụ LLM tốc độ cao.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-phục-vụ-và-hiệu-năng-suy-luận-llm&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Phục vụ và Hiệu năng suy luận LLM&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hai pha Prefill vs. Decode và hai thước đo TTFT / TPOT:&lt;/strong&gt; Tách biệt &lt;em&gt;Time-To-First-Token&lt;/em&gt; (độ trễ pha Prefill) với &lt;em&gt;Time-Per-Output-Token&lt;/em&gt; (tốc độ sinh từng token ở pha Decode) để chẩn đoán đúng nút cổ chai phần cứng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;KV Cache, PagedAttention và Continuous Batching:&lt;/strong&gt; Tái sử dụng vector Key/Value của các token cũ tránh tính lại bậc hai, quản lý VRAM không phân mảnh theo trang (kiểu hệ điều hành), và chèn/nhả yêu cầu ở cấp độ từng token.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chiến lược giải mã lấy mẫu (Temperature, Top-\(k\), Top-\(p\) Nucleus):&lt;/strong&gt; Kiểm soát trực tiếp sự đánh đổi giữa tính xác định chính xác (code, toán) và độ sáng tạo đa dạng (viết lách).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Speculative Decoding và Disaggregated Serving:&lt;/strong&gt; Dùng mô hình nháp kiểm định song song nhiều token một lượt để bẻ gãy nút cổ chai băng thông của pha Decode.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-tác-động-của-nhiệt-độ-t-và-lọc-top-p-nucleus-sampling-lên-phân-phối-token&quot;&gt;Giải thích: Tính tay tác động của Nhiệt độ \(T\) và lọc Top-\(p\) (Nucleus Sampling) lên phân phối token&lt;/h3&gt;

&lt;p&gt;Giả sử tại bước sinh hiện tại, 4 token ứng viên có logit là \(\mathbf{z} = [4{,}0,\; 3{,}0,\; 2{,}0,\; 1{,}0]\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Ở nhiệt độ chuẩn \(T = 1{,}0\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Trừ cực đại \(4{,}0\) được \([0, -1, -2, -3]\) → hàm mũ \([1{,}000,\; 0{,}368,\; 0{,}135,\; 0{,}050]\) (tổng \(1{,}553\)).&lt;/li&gt;
      &lt;li&gt;Xác suất: \([64{,}4\%,\; 23{,}7\%,\; 8{,}7\%,\; 3{,}2\%]\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Áp dụng Top-\(p = 0{,}85\):&lt;/strong&gt; Tổng xác suất tích lũy sau token 1 là \(64{,}4\% &amp;lt; 85\%\); sau token 2 là \(64{,}4\% + 23{,}7\% = 88{,}1\% \ge 85\%\) → &lt;strong&gt;chỉ giữ 2 token đầu&lt;/strong&gt;, chuẩn hóa lại thành \([73{,}1\%,\; 26{,}9\%]\) (cắt bỏ hoàn toàn đuôi nhiễu 2 token cuối).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khi giảm nhiệt độ \(T = 0{,}5\) (làm nhọn phân phối cho bài toán code/toán):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Logit chia \(0{,}5\) thành \([0, -2, -4, -6]\) → hàm mũ \([1{,}000,\; 0{,}135,\; 0{,}018,\; 0{,}002]\) (tổng \(1{,}155\)).&lt;/li&gt;
      &lt;li&gt;Xác suất token đứng đầu vọt từ \(64{,}4\%\) lên &lt;strong&gt;\(86{,}6\%\)&lt;/strong&gt; — mô hình trở nên tập trung và ít sinh từ ngẫu nhiên sai lệch hơn hẳn!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;phục-vụ-và-hiệu-năng-cho-llm&quot;&gt;Phục vụ và hiệu năng cho LLM&lt;/h1&gt;

&lt;p&gt;Một mô hình decoder đã qua tiền huấn luyện, SFT và căn chỉnh vẫn có chi phí vận hành cao &lt;strong&gt;trên từng token sinh ra&lt;/strong&gt;. Trong khi huấn luyện là khoản chi một lần (hoặc theo chu kỳ dài), chi phí phục vụ suy luận tăng liên tục theo số lượng người dùng. Bài này trình bày các kỹ thuật tối ưu phục vụ nên cân nhắc trước khi quyết định huấn luyện một mô hình học sinh qua chưng cất.&lt;/p&gt;

&lt;p&gt;Phần toán học nền tảng về nén mô hình nằm ở &lt;strong&gt;Chương 23&lt;/strong&gt;, còn các phương pháp lượng tử hóa riêng cho LLM (GPTQ, AWQ, GGUF) nằm ở &lt;strong&gt;23-99&lt;/strong&gt;. Ở đây, trọng tâm là phân tích &lt;em&gt;yếu tố nào gây tốn kém khi giải mã và khi nào chưng cất là bước tiếp theo hợp lý&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;1-hai-pha-suy-luận-prefill-và-decode&quot;&gt;1. Hai pha suy luận: Prefill và Decode&lt;/h2&gt;

&lt;p&gt;Quá trình sinh tự hồi quy gồm hai pha có đặc tính tính toán khác nhau:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pha Prefill:&lt;/strong&gt; Toàn bộ prompt đầu vào (gồm &lt;em&gt;system prompt&lt;/em&gt;, lịch sử hội thoại, câu hỏi người dùng và văn bản truy hồi) được xử lý song song. Mô hình tính &lt;em&gt;attention&lt;/em&gt; trên toàn bộ prompt một lần và lưu kết quả vào &lt;strong&gt;KV-cache&lt;/strong&gt;: với mỗi tầng và mỗi token đầu vào, các vectơ &lt;em&gt;key&lt;/em&gt; và &lt;em&gt;value&lt;/em&gt; được giữ lại trong bộ nhớ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pha Decode:&lt;/strong&gt; Mô hình sinh từng token mới một cách tuần tự. Nếu không có &lt;em&gt;cache&lt;/em&gt;, mỗi bước \(t\) sẽ phải tính lại &lt;em&gt;attention&lt;/em&gt; từ đầu cho toàn bộ tiền tố (độ phức tạp khoảng \(O(t^2)\)). Nhờ KV-cache, mỗi bước chỉ cần nối thêm một cặp \(k, v\) mới và tính &lt;em&gt;attention&lt;/em&gt; với tiền tố đã lưu (chi phí &lt;em&gt;attention&lt;/em&gt; khoảng \(O(t)\) mỗi token mới, cộng thêm tầng MLP).&lt;/p&gt;

&lt;p&gt;Các hệ thống phục vụ như vLLM, SGLang hay llama.cpp tập trung tối ưu đúng ba việc: quản lý đồng thời nhiều KV-cache, gom phép nhân ma trận hiệu quả và che giấu độ trễ truy xuất bộ nhớ (I/O).&lt;/p&gt;

&lt;p&gt;Trong pha &lt;em&gt;decode&lt;/em&gt;, &lt;strong&gt;dung lượng và băng thông bộ nhớ&lt;/strong&gt; thường là nút thắt lớn hơn cả FLOPs. Dung lượng KV-cache cho một chuỗi có độ dài \(L\) xấp xỉ:&lt;/p&gt;

\[\mathrm{bytes} \approx 2 \cdot L \cdot n_{\mathrm{layers}} \cdot n_{\mathrm{kv\_heads}} \cdot d_{\mathrm{head}} \cdot b\]

&lt;p&gt;trong đó hệ số 2 ứng với &lt;em&gt;key&lt;/em&gt; và &lt;em&gt;value&lt;/em&gt;, còn \(b\) là số byte cho mỗi phần tử (kỹ thuật &lt;em&gt;grouped-query attention&lt;/em&gt; giúp giảm \(n_{\mathrm{kv\_heads}}\)). Vì vậy, độ dài cửa sổ ngữ cảnh không chỉ là bài toán chất lượng mà còn là bài toán chi phí hạ tầng trực tiếp.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  prefill[&quot;Prefill prompt&quot;] --&amp;gt; kv[&quot;Ghi K,V cho moi token prompt&quot;]
  kv --&amp;gt; d1[&quot;Giai ma token t&quot;]
  d1 --&amp;gt; app[&quot;Noi them mot K,V moi&quot;]
  app --&amp;gt; d2[&quot;Giai ma token t+1&quot;]
  d2 --&amp;gt; lin[&quot;Do dai cache tang O cua n&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Lưu ý phân biệt vai trò của hai tối ưu phổ biến: GQA / MQA (&lt;strong&gt;26-07&lt;/strong&gt;, &lt;strong&gt;07-99&lt;/strong&gt;) trực tiếp giảm kích thước KV-cache qua việc giảm \(n_{\mathrm{kv\_heads}}\), trong khi FlashAttention &lt;strong&gt;không&lt;/strong&gt; làm nhỏ KV-cache mà giảm lượng truyền tải bộ nhớ khi tính &lt;em&gt;attention&lt;/em&gt; trên cache đó (chia khối kết hợp &lt;em&gt;online softmax&lt;/em&gt;, xem &lt;strong&gt;26-01&lt;/strong&gt; và &lt;strong&gt;26-07&lt;/strong&gt;). Phần ước lượng FLOPs và bộ nhớ chi tiết nằm ở bài &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;2-gom-batch-liên-tục-và-đóng-gói-chuỗi&quot;&gt;2. Gom batch liên tục và đóng gói chuỗi&lt;/h2&gt;

&lt;p&gt;Mỗi bước &lt;em&gt;decode&lt;/em&gt; đơn lẻ thực chất là một phép nhân ma trận dạng mảnh (batch = 1, độ dài chuỗi = 1, nhưng ma trận trọng số rất lớn), nên không tận dụng hết năng lực tính toán song song của GPU. &lt;strong&gt;Continuous batching&lt;/strong&gt; (gom batch liên tục theo từng bước giải mã, đặc trưng của vLLM) cho phép nạp ngay yêu cầu mới vào vị trí của yêu cầu vừa kết thúc thay vì chờ cả lô tĩnh hoàn thành. Tương tự ở pha huấn luyện, &lt;strong&gt;đóng gói chuỗi&lt;/strong&gt; (&lt;em&gt;sequence packing&lt;/em&gt;) ghép nhiều văn bản ngắn vào cùng một cửa sổ kèm mặt nạ chặn &lt;em&gt;attention&lt;/em&gt; chéo giữa các văn bản để không lãng phí tính toán vào &lt;em&gt;padding&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Ngoài ra, phần &lt;em&gt;prefill&lt;/em&gt; của &lt;em&gt;system prompt&lt;/em&gt; dùng chung giữa nhiều người dùng có thể tính một lần rồi tái sử dụng qua &lt;strong&gt;prefix caching&lt;/strong&gt; (lưu đệm tiền tố).&lt;/p&gt;

&lt;h2 id=&quot;3-chiến-lược-lấy-mẫu-nhiệt-độ-top-k-và-top-p&quot;&gt;3. Chiến lược lấy mẫu: Nhiệt độ, top-\(k\) và top-\(p\)&lt;/h2&gt;

&lt;p&gt;Quá trình giải mã không nhất thiết luôn chọn token có xác suất cao nhất (\(\arg\max\)). Từ vectơ logit \(z\), phân bố điều chỉnh theo nhiệt độ \(T\) là:&lt;/p&gt;

\[p_i^{(T)} = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}.\]

&lt;p&gt;Khi \(T \to 0\), phân bố tiến về giải mã tham lam; \(T = 1\) giữ nguyên phân bố đã học; \(T &amp;gt; 1\) làm phẳng phân bố (tăng tính đa dạng nhưng cũng dễ sinh nội dung lạc đề hơn). &lt;strong&gt;Top-\(k\)&lt;/strong&gt; chỉ giữ lại \(k\) token có logit cao nhất rồi chuẩn hóa lại xác suất. &lt;strong&gt;Nucleus / top-\(p\)&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/1904.09751&quot;&gt;Holtzman et al., 2020&lt;/a&gt;) giữ lại &lt;em&gt;tập nhỏ nhất&lt;/em&gt; các token có tổng xác suất tích lũy đạt ít nhất \(p\) rồi chuẩn hóa lại. Nói ngắn gọn, nhiệt độ điều chỉnh &lt;em&gt;hình dạng&lt;/em&gt; phân bố, còn &lt;em&gt;top-k&lt;/em&gt; / &lt;em&gt;top-p&lt;/em&gt; giới hạn &lt;em&gt;tập ứng viên hợp lệ&lt;/em&gt;; thực tế thường kết hợp theo thứ tự: chia logit cho \(T\), lọc theo &lt;em&gt;top-k&lt;/em&gt;/&lt;em&gt;top-p&lt;/em&gt;, rồi lấy mẫu.&lt;/p&gt;

&lt;p&gt;Cần phân biệt nhiệt độ \(T\) lúc giải mã với nhiệt độ \(T\) trong chưng cất tri thức (&lt;strong&gt;26-05&lt;/strong&gt;): cùng công thức toán học nhưng mục đích khác nhau (điều chỉnh độ đa dạng đầu ra so với làm mềm phân bố mục tiêu của mô hình giáo viên).&lt;/p&gt;

&lt;h2 id=&quot;4-speculative-decoding-mô-hình-nháp-và-xác-nhận&quot;&gt;4. Speculative Decoding (mô hình nháp và xác nhận)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Leviathan et al., 2023&lt;/a&gt; (cùng các nghiên cứu song song) dùng một mô hình &lt;strong&gt;nháp&lt;/strong&gt; (&lt;em&gt;draft model&lt;/em&gt;) nhỏ, chạy nhanh để đề xuất trước \(k\) token liên tiếp, sau đó mô hình &lt;strong&gt;đích&lt;/strong&gt; (&lt;em&gt;target model&lt;/em&gt;) lớn kiểm tra toàn bộ tiền tố đó trong một lượt lan truyền xuôi song song. Các token phù hợp với phân bố của mô hình đích được chấp nhận ngay; tại vị trí bất đồng đầu tiên, hệ thống lấy mẫu lại từ phân bố hiệu chỉnh của mô hình đích và bỏ phần nháp phía sau. Khi cài đặt đúng, phân bố đầu ra vẫn &lt;strong&gt;giữ nguyên chính xác&lt;/strong&gt; như mô hình đích, đồng thời giảm số lượt gọi tuần tự của mô hình lớn.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;sequenceDiagram
  participant Draft as Mo hinh nhap
  participant Target as Mo hinh dich
  Draft-&amp;gt;&amp;gt;Draft: De xuat k token
  Draft-&amp;gt;&amp;gt;Target: Giao tien to nhap
  Target-&amp;gt;&amp;gt;Target: Xac nhan tien to song song
  Target-&amp;gt;&amp;gt;Draft: Nhan mot tien to plus mot lan lay mau lai
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Speculative decoding&lt;/em&gt; là kỹ thuật tối ưu ở tầng &lt;em&gt;phục vụ&lt;/em&gt;, không tạo ra một mô hình học sinh mới. Nếu bài toán thực sự cần một kiến trúc gọn nhẹ hơn, cần chuyển sang chưng cất (&lt;strong&gt;26-05&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;5-lượng-tử-hóa-bước-tối-ưu-chi-phí-thấp-đầu-tiên&quot;&gt;5. Lượng tử hóa: Bước tối ưu chi phí thấp đầu tiên&lt;/h2&gt;

&lt;p&gt;Giảm độ chính xác trọng số từ 32-bit xuống 16-bit, rồi 8-bit hoặc 4-bit giúp giảm mạnh dung lượng bộ nhớ và cải thiện tốc độ pha &lt;em&gt;decode&lt;/em&gt; (vốn bị giới hạn bởi băng thông bộ nhớ). Các phương pháp thực dụng cho mô hình 7B–70B như GPTQ, AWQ và GGUF đã được giới thiệu ở &lt;strong&gt;23-99&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Lượng tử hóa &lt;strong&gt;không&lt;/strong&gt; huấn luyện lại mô hình mới mà chỉ biểu diễn xấp xỉ cùng bộ trọng số \(\theta\) bằng ít bit hơn. Nên ưu tiên lượng tử hóa khi:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Bạn sở hữu hoặc có quyền sử dụng hợp lệ bản trọng số gốc.&lt;/li&gt;
  &lt;li&gt;Mức suy giảm chất lượng sau kiểm thử nằm trong ngưỡng chấp nhận được.&lt;/li&gt;
  &lt;li&gt;Mục tiêu là giữ hành vi tương tự với mức tiêu thụ RAM/VRAM thấp hơn (trên máy cá nhân, một GPU hoặc thiết bị biên).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nếu lượng tử hóa 4-bit vẫn chưa đáp ứng yêu cầu độ trễ hay chi phí, giải pháp tiếp theo là giảm kích thước kiến trúc, dùng mô hình thưa kiểu MoE (&lt;strong&gt;23-99&lt;/strong&gt;) hoặc huấn luyện một &lt;strong&gt;mô hình học sinh&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;6-các-đòn-bẩy-tối-ưu-khác-trước-khi-chưng-cất&quot;&gt;6. Các đòn bẩy tối ưu khác trước khi chưng cất&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cache tiền tố (&lt;em&gt;prefix caching&lt;/em&gt;):&lt;/strong&gt; Tái sử dụng kết quả &lt;em&gt;prefill&lt;/em&gt; cho các &lt;em&gt;system prompt&lt;/em&gt; dùng chung.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Truy hồi thay cho ngữ cảnh quá dài:&lt;/strong&gt; Đưa toàn bộ tài liệu lớn vào cửa sổ \(L\) thường chậm và kém hiệu quả hơn kết hợp truy hồi (RAG, &lt;strong&gt;18-99&lt;/strong&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adapter (LoRA / QLoRA):&lt;/strong&gt; Phục vụ nhiều tác vụ chuyên biệt trên cùng một mô hình nền thay vì nhân bản toàn bộ trọng số (xem bài tùy chọn Chương 15).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ước lượng định lượng:&lt;/strong&gt; Khi cần tính số tham số \(N\), kích thước giá trị kích hoạt hay ngân sách \(C \approx 6NT\), dùng các công thức ở bài &lt;strong&gt;26-07&lt;/strong&gt; thay vì ước đoán cảm tính.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tất cả các kỹ thuật trên giúp chạy mô hình giáo viên rẻ hơn mà chưa thay đổi kiến trúc mô hình.&lt;/p&gt;

&lt;h2 id=&quot;7-khi-nào-nên-chuyển-sang-chưng-cất&quot;&gt;7. Khi nào nên chuyển sang chưng cất?&lt;/h2&gt;

&lt;p&gt;Nên cân nhắc chưng cất (&lt;strong&gt;26-05&lt;/strong&gt;) khi đáp ứng ít nhất một trong các điều kiện sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cần thu nhỏ kiến trúc thực sự:&lt;/strong&gt; Lượng tử hóa không thể giảm số tầng hay độ rộng; muốn chuyển từ mô hình 70B xuống 7–8B (hoặc cỡ di động) cần huấn luyện một bộ tham số \(\theta\) mới.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cần phiên bản sản phẩm chi phí thấp hơn&lt;/strong&gt; có hành vi tương đương trên miền tác vụ mục tiêu, sử dụng mô hình giáo viên mà bạn có quyền huấn luyện từ đó.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cần tinh chỉnh nhiều mô hình chuyên biệt:&lt;/strong&gt; Chưng cất một mô hình học sinh tổng quát một lần rồi gắn các &lt;em&gt;adapter&lt;/em&gt; LoRA riêng cho từng tác vụ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Có quyền truy cập hộp trắng&lt;/strong&gt; vào mô hình giáo viên và muốn khớp trạng thái ẩn hoặc phân bố token, không chỉ văn bản đầu ra.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Lưu ý thực hành:&lt;/strong&gt; Không nên vội triển khai chưng cất trước khi đã thử lượng tử hóa 4-bit, kiểm soát độ dài ngữ cảnh hợp lý và áp dụng &lt;em&gt;continuous batching&lt;/em&gt;, bởi chưng cất là một dự án huấn luyện đầy đủ trong khi các kỹ thuật phục vụ thường chỉ cần cấu hình triển khai. Đồng thời, chỉ thực hiện chưng cất từ mô hình giáo viên có giấy phép hoặc quyền sử dụng hợp lệ (phân tích chi tiết ở bài &lt;strong&gt;26-05&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;đọc-thêm&quot;&gt;Đọc thêm&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Leviathan et al., 2023. &lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Fast Inference from Transformers via Speculative Decoding&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Holtzman et al., 2020. &lt;a href=&quot;https://arxiv.org/abs/1904.09751&quot;&gt;The Curious Case of Neural Text Degeneration&lt;/a&gt; (nucleus sampling).&lt;/li&gt;
  &lt;li&gt;Kwon et al., 2023. &lt;a href=&quot;https://arxiv.org/abs/2309.06180&quot;&gt;Efficient Memory Management for Large Language Model Serving with PagedAttention&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Tài liệu tham khảo mở rộng: &lt;a href=&quot;https://alisawuffles.notion.site/alisa-s-book-of-llms&quot;&gt;Alisa’s Book of LLMs&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Chi phí pha &lt;em&gt;decode&lt;/em&gt; gồm MLP và &lt;em&gt;attention&lt;/em&gt; trên &lt;strong&gt;KV-cache&lt;/strong&gt; tăng tuyến tính \(O(n)\) theo độ dài chuỗi.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Continuous batching&lt;/em&gt; và đóng gói chuỗi tối ưu mức sử dụng GPU; &lt;em&gt;speculative decoding&lt;/em&gt; tăng tốc bằng cơ chế đề xuất–xác nhận song song mà vẫn giữ nguyên phân bố đích.&lt;/li&gt;
  &lt;li&gt;Nhiệt độ điều chỉnh hình dạng phân bố \(p\); &lt;em&gt;top-k&lt;/em&gt; và &lt;em&gt;top-p&lt;/em&gt; giới hạn tập token ứng viên.&lt;/li&gt;
  &lt;li&gt;Lượng tử hóa, quản lý ngữ cảnh và gom batch là nhóm tối ưu nên áp dụng trước (&lt;strong&gt;Chương 23 / 23-99&lt;/strong&gt;).&lt;/li&gt;
  &lt;li&gt;Chưng cất dành cho trường hợp cần một mạng &lt;em&gt;nhỏ hơn, có bộ tham số mới&lt;/em&gt; học lại hành vi của mô hình giáo viên.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=VkWlLSTdHs8&quot;&gt;Faster LLMs: Accelerate Inference with Speculative Decoding&lt;/a&gt; — IBM Technology, tiếng Anh. Giải thích trực quan cơ chế đề xuất–xác nhận của &lt;em&gt;speculative decoding&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, tiếng Anh. Trình bày nền tảng lượng tử hóa — bước tối ưu phục vụ chi phí thấp đầu tiên.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Có phần cài đặt lấy mẫu theo nhiệt độ để đối chiếu trực tiếp với &lt;em&gt;top-k&lt;/em&gt; và &lt;em&gt;top-p&lt;/em&gt; trong bài.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-03 Căn chỉnh: SFT đến tối ưu sở thích</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_03_Alignment_SFT_to_Preference/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_03_Alignment_SFT_to_Preference</id>
   <content type="html">&lt;p&gt;Một mô hình vừa hoàn tất tiền huấn luyện trên toàn bộ Internet giống như một thư viện khổng lồ biết mọi thứ — từ thơ lục bát đến mã độc mạng — nhưng hoàn toàn không biết phân biệt điều gì hữu ích, trung thực hay an toàn khi trò chuyện với con người. &lt;strong&gt;Căn chỉnh (Alignment)&lt;/strong&gt; là quy trình “điêu khắc” hành vi từ khối đá thô đó qua ba bước kinh điển: &lt;strong&gt;SFT → Mô hình phần thưởng (RM) → Tối ưu sở thích (RLHF / DPO)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-căn-chỉnh-llm-từ-sft-đến-dporlhf&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Căn chỉnh LLM (từ SFT đến DPO/RLHF)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tinh chỉnh có giám sát (SFT — Supervised Fine-Tuning):&lt;/strong&gt; Dùng tập dữ liệu hội thoại chất lượng cao để dạy định dạng lượt nói, cấu trúc suy luận và chỉ tính loss trên phần phản hồi của trợ lý (&lt;em&gt;assistant token masking&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình hóa sở thích con người (Bradley–Terry Reward Model):&lt;/strong&gt; Thay vì yêu cầu con người chấm điểm tuyệt đối từ 1–10 (rất nhiễu), chỉ cần so sánh cặp \((y_w \succ y_l)\) và tối ưu \(\mathcal{L}_{\text{RM}} = -\ln\sigma(r_\phi(x, y_w) - r_\phi(x, y_l))\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tối ưu hóa chính sách có ràng buộc KL (PPO &amp;amp; DPO):&lt;/strong&gt; Cân bằng giữa nâng cao điểm sở thích và giữ mô hình không trôi quá xa \(\pi_{\text{ref}}\) để tránh sụp đổ ngôn ngữ hoặc &lt;em&gt;reward hacking&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ranh giới của căn chỉnh:&lt;/strong&gt; Nhận rõ căn chỉnh định hình &lt;em&gt;phong cách, độ an toàn và tính tuân thủ&lt;/em&gt;, nhưng &lt;strong&gt;không thể thay thế&lt;/strong&gt; tri thức bị thiếu từ tiền huấn luyện hay hệ thống truy hồi RAG cho dữ liệu thời gian thực.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-hàm-mất-mát-dpo-trên-cặp-phản-hồi-y_w-y_l&quot;&gt;Giải thích: Tính tay một bước hàm mất mát DPO trên cặp phản hồi \((y_w, y_l)\)&lt;/h3&gt;

&lt;p&gt;Hàm mất mát &lt;strong&gt;Direct Preference Optimization (DPO)&lt;/strong&gt; cho một cặp phản hồi được chọn \(y_w\) và bị từ chối \(y_l\) với hệ số kiểm soát KL \(\beta = 0{,}1\) là:
\(\mathcal{L}_{\text{DPO}} = -\ln \sigma\!\left(\beta \ln\frac{\pi_\theta(y_w\mid x)}{\pi_{\text{ref}}(y_w\mid x)} - \beta \ln\frac{\pi_\theta(y_l\mid x)}{\pi_{\text{ref}}(y_l\mid x)}\right).\)&lt;/p&gt;

&lt;p&gt;Giả sử tổng log-xác suất trên toàn câu phản hồi tại bước hiện tại là:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Với câu tốt \(y_w\): \(\ln \pi_\theta(y_w\mid x) = -12{,}0\), \(\ln \pi_{\text{ref}}(y_w\mid x) = -14{,}0\) (tỷ số log \(= +2{,}0\)).&lt;/li&gt;
  &lt;li&gt;Với câu xấu \(y_l\): \(\ln \pi_\theta(y_l\mid x) = -15{,}0\), \(\ln \pi_{\text{ref}}(y_l\mid x) = -13{,}0\) (tỷ số log \(= -2{,}0\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính phần thưởng ngầm (Implicit Reward) cho từng câu:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(\hat{r}_w = 0{,}1 \times (+2{,}0) = +0{,}20\); \(\hat{r}_l = 0{,}1 \times (-2{,}0) = -0{,}20\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng cách sở thích (Margin):&lt;/strong&gt; \(\Delta = \hat{r}_w - \hat{r}_l = 0{,}20 - (-0{,}20) = +0{,}40\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính DPO Loss:&lt;/strong&gt; \(\sigma(0{,}40) \approx 0{,}5987 \implies \mathcal{L}_{\text{DPO}} = -\ln(0{,}5987) \approx 0{,}5130\).
Trọng số gradient tỷ lệ với \(1 - \sigma(\Delta) \approx 0{,}4013\): càng phân tách sai (\(\Delta &amp;lt; 0\)), DPO càng phạt mạnh để đẩy \(\pi_\theta(y_w)\) lên và kéo \(\pi_\theta(y_l)\) xuống!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;căn-chỉnh-sft-đến-tối-ưu-sở-thích&quot;&gt;Căn chỉnh: SFT đến tối ưu sở thích&lt;/h1&gt;

&lt;p&gt;Tiền huấn luyện dạy mô hình &lt;em&gt;cấu trúc và phân bố của văn bản&lt;/em&gt;. Tinh chỉnh có giám sát (SFT) dạy mô hình &lt;em&gt;cách phản hồi một yêu cầu&lt;/em&gt;. &lt;strong&gt;Căn chỉnh&lt;/strong&gt; (&lt;em&gt;alignment&lt;/em&gt;) là bước tiếp theo: trong số nhiều câu trả lời cùng trôi chảy, ưu tiên những câu trả lời được con người (hoặc mô hình đánh giá) xếp hạng cao hơn về mức độ hữu ích, trung thực và an toàn.&lt;/p&gt;

&lt;p&gt;Bài này cung cấp &lt;strong&gt;bức tranh tổng thể&lt;/strong&gt; về quy trình căn chỉnh trong LLM, không lặp lại toàn bộ phần chứng minh học tăng cường (MDP, hàm lợi thế và PPO đã nằm ở Chương 20–21, còn hệ sinh thái thực tế 2022–2026 nằm ở bài &lt;strong&gt;21-99&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;1-quy-trình-ba-giai-đoạn-phổ-biến&quot;&gt;1. Quy trình ba giai đoạn phổ biến&lt;/h2&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;LM tiền huấn luyện  →  SFT (minh họa)  →  tối ưu sở thích
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Giai đoạn A — Tinh chỉnh có giám sát (SFT).&lt;/strong&gt; Thu thập các cặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(prompt, câu trả lời mẫu)&lt;/code&gt; và tối thiểu hóa hàm mất mát dự đoán token kế tiếp trên phần câu trả lời mẫu (đã giới thiệu ở &lt;strong&gt;26-02&lt;/strong&gt;). Về bản chất, đây là học có giám sát trên một tập dữ liệu được chọn lọc kỹ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Giai đoạn B — Huấn luyện theo mô hình phần thưởng (RLHF cổ điển).&lt;/strong&gt; Thu thập các cặp so sánh \((y_w, y_l)\) cho cùng một prompt, trong đó \(y_w\) là câu trả lời được ưa chuộng hơn (&lt;em&gt;win&lt;/em&gt;) và \(y_l\) là câu trả lời kém hơn (&lt;em&gt;lose&lt;/em&gt;). Trước tiên, huấn luyện mô hình phần thưởng \(r_\phi\) sao cho \(r_\phi(x, y_w) &amp;gt; r_\phi(x, y_l)\) (thường bằng hàm mất mát Bradley–Terry / logistic). Sau đó, xem LLM như một chính sách \(\pi_\theta\) sinh từng token (hành động) và tối đa hóa phần thưởng kỳ vọng kèm &lt;strong&gt;số hạng phạt KL&lt;/strong&gt; giữ \(\pi_\theta\) không lệch quá xa mô hình SFT tham chiếu, tránh việc mô hình sinh ra văn bản bất thường chỉ để đánh lừa \(r_\phi\).&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Ouyang et al., 2022&lt;/a&gt; (InstructGPT) phổ biến hóa quy trình này với thuật toán PPO (xem thêm Chương 21 và bài &lt;strong&gt;21-99&lt;/strong&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Giai đoạn C — Tối ưu sở thích trực tiếp không cần vòng lấy mẫu RL.&lt;/strong&gt; &lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Rafailov et al., 2023&lt;/a&gt; (DPO) biến đổi bài toán tối ưu có ràng buộc KL thành một hàm mất mát phân loại trực tiếp trên các cặp \((y_w, y_l)\), đối chiếu \(\pi_\theta\) với mô hình tham chiếu đóng băng \(\pi_{\mathrm{ref}}\). Do không cần huấn luyện mô hình phần thưởng riêng và không cần vòng lấy mẫu trực tuyến của PPO, DPO trở thành lựa chọn phổ biến trong hệ sinh thái mã nguồn mở giai đoạn 2024–2025 (như thư viện &lt;a href=&quot;https://github.com/huggingface/trl&quot;&gt;trl&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Nguyên tắc cốt lõi cần nhớ về vai trò của hai bước:&lt;/p&gt;

\[\text{SFT xác định miền hành vi khả dĩ; tối ưu sở thích phân bổ lại xác suất trên miền hành vi đó.}\]

&lt;p&gt;Nếu dữ liệu SFT không chứa các mẫu từ chối phù hợp, trích dẫn nguồn hay gọi công cụ, thì bước tối ưu sở thích chỉ dựa trên tín hiệu so sánh hơn/kém rất khó tự tạo ra những kỹ năng đó.&lt;/p&gt;

&lt;h2 id=&quot;2-các-hàm-mục-tiêu-cốt-lõi&quot;&gt;2. Các hàm mục tiêu cốt lõi&lt;/h2&gt;

&lt;p&gt;Xem LLM là chính sách \(\pi_\theta(y\mid x)\) sinh chuỗi token \(y\) ứng với prompt \(x\). Dưới đây là bốn biểu thức nền tảng thường gặp trong tài liệu (chi tiết chứng minh và các biến thể như IPO, KTO, ORPO có thể xem thêm ở Chương 20–21 và bài &lt;strong&gt;21-99&lt;/strong&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gradient chính sách (dạng REINFORCE).&lt;/strong&gt; Nhân hàm lợi thế hoặc phần thưởng \(\hat{A}\) với gradient của log-xác suất:&lt;/p&gt;

\[\nabla_\theta J(\theta) \approx \mathbb{E}_{x,y\sim\pi_\theta}\big[\,\hat{A}(x,y)\,\nabla_\theta \log\pi_\theta(y\mid x)\,\big].\]

&lt;p&gt;Với mô hình tự hồi quy, \(\log\pi_\theta(y\mid x) = \sum_t \log\pi_\theta(y_t\mid x, y_{&amp;lt;t})\) — có cùng cấu trúc tổng như hàm mất mát NLL của SFT, nhưng mỗi mẫu được nhân thêm trọng số \(\hat{A}\) thay vì luôn bằng 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;RLHF với số hạng phạt KL.&lt;/strong&gt; Sau khi huấn luyện mô hình phần thưởng \(r_\phi\), hàm mục tiêu chuẩn (&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Ouyang et al., 2022&lt;/a&gt;) là:&lt;/p&gt;

\[\max_\theta\; \mathbb{E}_{x\sim\mathcal{D},\, y\sim\pi_\theta}\big[r_\phi(x,y)\big] - \beta\,\mathrm{KL}\big(\pi_\theta(\cdot\mid x)\,\|\,\pi_{\mathrm{ref}}(\cdot\mid x)\big).\]

&lt;p&gt;Số hạng KL ngăn chính sách mới bị sụp đổ hoặc khai thác kẽ hở của \(r_\phi\) (&lt;em&gt;reward hacking&lt;/em&gt;); thông thường \(\pi_{\mathrm{ref}}\) là bản lưu sau SFT.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mục tiêu cắt ngưỡng của PPO.&lt;/strong&gt; PPO (&lt;a href=&quot;https://arxiv.org/abs/1707.06347&quot;&gt;Schulman et al., 2017&lt;/a&gt;) tối đa hóa hàm thay thế có cắt ngưỡng trên tỉ số xác suất \(r_t(\theta) = \pi_\theta(a_t\mid s_t)/\pi_{\mathrm{old}}(a_t\mid s_t)\):&lt;/p&gt;

\[L^{\mathrm{CLIP}}(\theta) = \mathbb{E}\Big[\min\big(r_t(\theta)\,\hat{A}_t,\; \mathrm{clip}(r_t(\theta), 1-\varepsilon, 1+\varepsilon)\,\hat{A}_t\big)\Big].\]

&lt;p&gt;Trong bối cảnh LLM, hành động \(a_t\) là token tại bước \(t\) và trạng thái \(s_t\) là chuỗi tiền tố. InstructGPT sử dụng vòng lặp này, nhưng chi phí triển khai khá cao (cần lấy mẫu trực tuyến, thường phải duy trì thêm mạng giá trị và dễ nhạy siêu tham số).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DPO (tối ưu sở thích trực tiếp).&lt;/strong&gt; &lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Rafailov et al., 2023&lt;/a&gt; rút gọn bài toán tối ưu có phạt KL về dạng đóng, thu được hàm mất mát phân loại trên các cặp \((y_w, y_l)\):&lt;/p&gt;

\[\mathcal{L}_{\mathrm{DPO}}(\theta) = -\log\sigma\Big(\beta\log\frac{\pi_\theta(y_w\mid x)}{\pi_{\mathrm{ref}}(y_w\mid x)} - \beta\log\frac{\pi_\theta(y_l\mid x)}{\pi_{\mathrm{ref}}(y_l\mid x)}\Big).\]

&lt;p&gt;Về trực giác, DPO tăng khoảng cách phần thưởng ẩn giữa phản hồi thắng và phản hồi thua, đo bằng tỉ lệ log-xác suất so với mô hình tham chiếu \(\pi_{\mathrm{ref}}\), mà không cần mô hình \(r_\phi\) hay vòng &lt;em&gt;rollout&lt;/em&gt; của PPO.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  sft[&quot;Chinh sach SFT&quot;] --&amp;gt; pairs[&quot;Cap so thich thang / thua&quot;]
  pairs --&amp;gt; rm[&quot;RLHF: khop mo hinh thuong&quot;]
  rm --&amp;gt; ppo[&quot;PPO voi thuong tru KL&quot;]
  pairs --&amp;gt; dpo[&quot;DPO: phan loai cap vs tham chieu&quot;]
  ppo --&amp;gt; aligned[&quot;Chinh sach da can chinh&quot;]
  dpo --&amp;gt; aligned
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;3-căn-chỉnh-không-thay-thế-những-gì&quot;&gt;3. Căn chỉnh &lt;em&gt;không&lt;/em&gt; thay thế những gì?&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Không thay thế truy hồi thông tin:&lt;/strong&gt; Tối ưu sở thích không tự bổ sung dữ kiện thực tế vốn không có trong tiền huấn luyện hoặc ngữ cảnh (xem RAG ở Chương 18-99).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không phải đảm bảo an toàn tuyệt đối:&lt;/strong&gt; Dữ liệu phản hồi chỉ mã hóa một chính sách mong muốn chứ không chứng minh độ vững chắc trước mọi đầu vào; tấn công vượt rào (&lt;em&gt;jailbreak&lt;/em&gt;) và dịch chuyển phân bố vẫn đòi hỏi đánh giá riêng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không đồng nhất với riêng RL:&lt;/strong&gt; RLHF chỉ là một phương pháp cài đặt; DPO, các hàm mất mát so sánh cặp khác hay quy trình SFT chọn lọc kỹ đều thuộc phạm vi căn chỉnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khác với chưng cất mô hình:&lt;/strong&gt; Chưng cất sao chép hành vi của mô hình giáo viên sang mô hình học sinh nhỏ hơn (&lt;strong&gt;26-05&lt;/strong&gt;), còn căn chỉnh thay đổi &lt;em&gt;hành vi nào&lt;/em&gt; được ưu tiên. Trong thực tế, người ta thường căn chỉnh mô hình lớn trước rồi mới chưng cất xuống phiên bản nhỏ hơn.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-tóm-tắt-quy-trình-trên-một-prompt-mẫu&quot;&gt;4. Tóm tắt quy trình trên một prompt mẫu&lt;/h2&gt;

&lt;p&gt;Với một prompt \(x\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Lấy mẫu (hoặc biên soạn) hai câu trả lời \(y_1, y_2\) từ mô hình SFT.&lt;/li&gt;
  &lt;li&gt;Người đánh giá (hoặc mô hình đánh giá) chọn cặp ưu tiên \(y_w \succ y_l\).&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Nhánh RLHF:&lt;/em&gt; huấn luyện mô hình phần thưởng \(r_\phi\), sau đó tối ưu \(\pi_\theta\) bằng PPO với phần thưởng hiệu chỉnh \(r_\phi - \beta \log(\pi_\theta/\pi_{\mathrm{ref}})\).&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Nhánh DPO:&lt;/em&gt; tăng \(\log\pi_\theta(y_w\mid x)\) tương đối so với \(\log\pi_\theta(y_l\mid x)\), chuẩn hóa theo các giá trị tương ứng của \(\pi_{\mathrm{ref}}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;5-kết-nối-với-các-bài-liên-quan&quot;&gt;5. Kết nối với các bài liên quan&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Chương 20–21:&lt;/strong&gt; Nền tảng trạng thái, hành động, lợi tức và PPO.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài 21-99:&lt;/strong&gt; RLHF, DPO và GRPO cho mô hình suy luận.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài 26-04:&lt;/strong&gt; Tối ưu chi phí phục vụ chính sách đã căn chỉnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài 26-05:&lt;/strong&gt; Thu nhỏ mô hình đã căn chỉnh qua chưng cất mà không phải thu thập lại toàn bộ dữ liệu sở thích.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;đọc-thêm&quot;&gt;Đọc thêm&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Ouyang et al., 2022. &lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Training language models to follow instructions with human feedback&lt;/a&gt; (InstructGPT / RLHF + PPO).&lt;/li&gt;
  &lt;li&gt;Schulman et al., 2017. &lt;a href=&quot;https://arxiv.org/abs/1707.06347&quot;&gt;Proximal Policy Optimization Algorithms&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Rafailov et al., 2023. &lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Direct Preference Optimization&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Tài liệu tham khảo mở rộng: &lt;a href=&quot;https://alisawuffles.notion.site/alisa-s-book-of-llms&quot;&gt;Alisa’s Book of LLMs&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Quy trình căn chỉnh phổ biến gồm SFT rồi tối ưu lại phân bố phản hồi theo sở thích.&lt;/li&gt;
  &lt;li&gt;Ba công thức cốt lõi cần nắm: gradient chính sách \(\hat{A}\nabla\log\pi\), mục tiêu RLHF (phần thưởng trừ \(\beta\,\mathrm{KL}\) so với mô hình tham chiếu) và hàm mục tiêu cắt ngưỡng của PPO.&lt;/li&gt;
  &lt;li&gt;DPO chuyển cùng bài toán tối ưu có phạt KL thành hàm mất mát logistic trực tiếp trên cặp \((y_w, y_l)\), không cần mô hình phần thưởng riêng lúc huấn luyện.&lt;/li&gt;
  &lt;li&gt;Năng lực và tri thức đến từ dữ liệu (cùng công cụ); căn chỉnh giúp ưu tiên những hành vi mong muốn trong số năng lực đã có.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qPN_XZcJf_s&quot;&gt;Reinforcement Learning with Human Feedback (RLHF), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Trình bày bức tranh ba giai đoạn tiền huấn luyện, SFT và tối ưu sở thích.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=k2pD3k1485A&quot;&gt;Direct Preference Optimization (DPO) - How to fine-tune LLMs directly without reinforcement learning&lt;/a&gt; — Luis Serrano Academy, tiếng Anh. Giải thích trực quan hàm mục tiêu DPO và lý do không cần vòng lặp RL.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=T_X4XFwKX8k&quot;&gt;Reinforcement Learning from Human Feedback (RLHF) Explained&lt;/a&gt; — IBM Technology, tiếng Anh. Tóm tắt cơ chế RLHF dùng mô hình phần thưởng để đối chiếu với DPO.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-02 Prompting, học trong ngữ cảnh và tuân thủ chỉ dẫn</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_02_Prompting_and_In_Context_Learning/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_02_Prompting_and_In_Context_Learning</id>
   <content type="html">&lt;p&gt;Một trong những phát hiện làm ngỡ ngàng chính các tác giả GPT-3 vào năm 2020 là &lt;strong&gt;Học trong Ngữ cảnh (In-Context Learning — ICL)&lt;/strong&gt;: không hề chạy một bước lan truyền ngược hay cập nhật bất kỳ trọng số nào, chỉ cần bạn đặt 3 ví dụ minh họa ngay trong phần mở đầu câu lệnh, mô hình bỗng “hiểu luật chơi” và giải đúng mẫu thứ 4! Bài học này giải mã bản chất thực sự của Prompting, sự khác biệt giữa mô hình nền (base model) với mô hình đã qua SFT, và cách viết prompt như một kỹ sư hệ thống.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-prompting-và-học-trong-ngữ-cảnh-icl&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Prompting và Học trong Ngữ cảnh (ICL)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Prompt là điều kiện hóa xác suất trên chuỗi đầu vào:&lt;/strong&gt; Về mặt toán học, mọi kỹ thuật viết prompt đều là nghệ thuật chọn tiền tố \(x_{1:k}\) sao cho phân phối có điều kiện \(P_\theta(x_{k+1:T} \mid x_{1:k})\) tập trung vào vùng lời giải mong muốn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Zero-shot, Few-shot và In-Context Learning:&lt;/strong&gt; Cung cấp cặp (đầu vào → đầu ra) trong ngữ cảnh giúp các đầu chú ý (như Induction Heads) tự căn chỉnh định dạng, phân phối nhãn và phong cách mà không đổi trọng số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vai trò quyết định của SFT trong tuân thủ chỉ dẫn:&lt;/strong&gt; Hiểu vì sao mô hình nền thuần tiền huấn luyện thường &lt;em&gt;viết tiếp&lt;/em&gt; câu hỏi của bạn thay vì trả lời, còn mô hình hậu huấn luyện SFT biết đóng vai trợ lý tuân thủ chỉ dẫn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỹ thuật thiết kế Prompt có hệ thống:&lt;/strong&gt; Chỉ rõ vai trò, ràng buộc định dạng đầu ra, phân tách rõ dữ liệu với chỉ dẫn (chống prompt injection) và cung cấp ví dụ biên (edge cases).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-phân-tích-sự-thay-đổi-phân-phối-xác-suất-token-khi-chuyển-từ-zero-shot-sang-few-shot-icl&quot;&gt;Giải thích: Phân tích sự thay đổi phân phối xác suất token khi chuyển từ Zero-shot sang Few-shot ICL&lt;/h3&gt;

&lt;p&gt;Xét bài toán phân loại cảm xúc đánh giá sản phẩm chỉ được trả về đúng 1 từ trong tập &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{Tích cực, Tiêu cực}&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Prompt Zero-shot mơ hồ trên mô hình nền:&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Đánh giá: Giao hàng chậm quá! Cảm xúc:&lt;/code&gt;
    &lt;ul&gt;
      &lt;li&gt;Phân phối xác suất token kế tiếp bị phân tán rộng: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rất&lt;/code&gt; (\(0{,}22\)), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;khó&lt;/code&gt; (\(0{,}18\)), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bực&lt;/code&gt; (\(0{,}15\)), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tiêu&lt;/code&gt; (\(0{,}08\)), các từ khác (\(0{,}37\)) — entropy cao và dễ trả lời sai định dạng JSON/nhãn.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prompt Few-shot (2 ví dụ định khung):&lt;/strong&gt;
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Đánh giá: Máy chạy êm -&amp;gt; Nhãn: Tích cực&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Đánh giá: Pin tụt nhanh -&amp;gt; Nhãn: Tiêu cực&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Đánh giá: Giao hàng chậm quá! -&amp;gt; Nhãn:&lt;/code&gt;
    &lt;ul&gt;
      &lt;li&gt;Các đầu chú ý so khớp mẫu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-&amp;gt; Nhãn:&lt;/code&gt; lặp lại 2 lần trước đó và dồn khối xác suất trực tiếp vào đúng 2 token nhãn đã thấy: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tiêu&lt;/code&gt; (\(0{,}93\)), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tích&lt;/code&gt; (\(0{,}05\)), khác (\(0{,}02\)).&lt;/li&gt;
      &lt;li&gt;Entropy Shannon giảm mạnh từ \(&amp;gt; 2{,}5\text{ nat}\) xuống còn \(-0{,}93\ln(0{,}93) - 0{,}05\ln(0{,}05) - 0{,}02\ln(0{,}02) \approx 0{,}295\text{ nat}\) — độ tin cậy và tính tuân thủ định dạng tăng vọt mà không cần cập nhật một trọng số nào!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;prompting-học-trong-ngữ-cảnh-và-tuân-thủ-chỉ-dẫn&quot;&gt;Prompting, học trong ngữ cảnh và tuân thủ chỉ dẫn&lt;/h1&gt;

&lt;p&gt;Sau giai đoạn tiền huấn luyện, bộ trọng số \(\theta\) hiện thực một mô hình dự đoán token kế tiếp. &lt;strong&gt;Prompting&lt;/strong&gt; là cách ít tốn kém nhất để điều hướng mô hình: ta chỉ thay đổi chuỗi tiền tố \(x_{&amp;lt;t}\) mà không thay đổi \(\theta\). Ngược lại, &lt;strong&gt;tinh chỉnh&lt;/strong&gt; (&lt;em&gt;fine-tuning&lt;/em&gt;) cập nhật trực tiếp \(\theta\). Trong thực tế, phần lớn hệ thống LLM kết hợp cả hai cách tiếp cận này.&lt;/p&gt;

&lt;p&gt;Bài này phân biệt rõ ba khái niệm thường bị trộn lẫn: &lt;em&gt;prompting zero-shot&lt;/em&gt;, học trong ngữ cảnh (&lt;em&gt;in-context learning&lt;/em&gt;, ICL / &lt;em&gt;few-shot&lt;/em&gt;) và khả năng tuân thủ chỉ dẫn sau tinh chỉnh có giám sát.&lt;/p&gt;

&lt;h2 id=&quot;1-prompt-là-một-phần-của-chuỗi-đầu-vào&quot;&gt;1. Prompt là một phần của chuỗi đầu vào&lt;/h2&gt;

&lt;p&gt;Do \(p_\theta(x_t \mid x_{&amp;lt;t})\) điều kiện hóa trên &lt;em&gt;toàn bộ&lt;/em&gt; chuỗi trong cửa sổ ngữ cảnh, các thành phần như &lt;em&gt;system prompt&lt;/em&gt;, tài liệu truy hồi, kết quả trả về từ công cụ và câu hỏi người dùng thực chất đều là các token nối tiếp nhau. Kiến trúc Transformer không có cổng nhập “chỉ dẫn” tách biệt. Các quy ước định dạng (khuôn mẫu hội thoại, thẻ dạng XML, cấu trúc JSON) có tác dụng vì chúng tạo thành những &lt;strong&gt;tiền tố có cấu trúc ổn định&lt;/strong&gt; mà mô hình đã gặp khi huấn luyện.&lt;/p&gt;

&lt;p&gt;Khi mô hình có vẻ “bỏ qua chỉ dẫn”, trước hết nên kiểm tra xem chỉ dẫn có bị đẩy ra khỏi cửa sổ ngữ cảnh hay khuôn mẫu hội thoại (&lt;em&gt;chat template&lt;/em&gt;) có khớp với phiên bản mô hình hay không — đây thường là lỗi định dạng hoặc cắt chuỗi hơn là lỗi kiến trúc.&lt;/p&gt;

&lt;h2 id=&quot;2-zero-shot-và-học-trong-ngữ-cảnh-in-context-learning&quot;&gt;2. Zero-shot và học trong ngữ cảnh (In-Context Learning)&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Zero-shot:&lt;/strong&gt; Người dùng mô tả trực tiếp yêu cầu bằng ngôn ngữ tự nhiên (ví dụ “Dịch sang tiếng Việt:”) rồi để mô hình sinh tiếp. Mô hình tổng quát hóa từ các mẫu tương tự đã xuất hiện trong dữ liệu tiền huấn luyện.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Học trong ngữ cảnh (ICL / few-shot):&lt;/strong&gt; Người dùng đặt một vài cặp ví dụ đầu vào–đầu ra vào ngay trong tiền tố trước câu hỏi mới. &lt;a href=&quot;https://arxiv.org/abs/2005.14165&quot;&gt;Brown et al., 2020&lt;/a&gt; (GPT-3) cho thấy ở quy mô đủ lớn, mô hình có thể thích nghi với tác vụ mới &lt;em&gt;mà không cần cập nhật gradient&lt;/em&gt;. Về bản chất, cơ chế vẫn là dự đoán token kế tiếp: các ví dụ mẫu làm tăng xác suất của kiểu câu trả lời mong muốn.&lt;/p&gt;

&lt;p&gt;So sánh học trong ngữ cảnh với tinh chỉnh cổ điển:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Tiêu chí&lt;/th&gt;
      &lt;th&gt;Học trong ngữ cảnh (ICL)&lt;/th&gt;
      &lt;th&gt;Tinh chỉnh cổ điển (Fine-tuning)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Thành phần thay đổi&lt;/td&gt;
      &lt;td&gt;Chuỗi token trong cửa sổ ngữ cảnh&lt;/td&gt;
      &lt;td&gt;Tham số \(\theta\) (hoặc &lt;em&gt;adapter&lt;/em&gt;)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Tính bền vững&lt;/td&gt;
      &lt;td&gt;Không lưu lại sau khi đổi prompt&lt;/td&gt;
      &lt;td&gt;Giữ cố định qua mọi truy vấn&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Chi phí chính&lt;/td&gt;
      &lt;td&gt;Tốn thêm token &lt;em&gt;prefill&lt;/em&gt; và bộ nhớ cache mỗi lần gọi&lt;/td&gt;
      &lt;td&gt;Tốn tính toán huấn luyện ban đầu, nhưng prompt ngắn và rẻ hơn khi phục vụ&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Yêu cầu dữ liệu&lt;/td&gt;
      &lt;td&gt;Vài ví dụ minh họa, chỉnh sửa tức thì&lt;/td&gt;
      &lt;td&gt;Tập dữ liệu huấn luyện và quy trình tối ưu&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Nên ưu tiên ICL khi tác vụ mới, dữ liệu có nhãn còn ít, hoặc cần thay đổi hành vi linh hoạt theo từng truy vấn (ví dụ từng khách hàng hoặc từng định dạng khác nhau). Ngược lại, nên chọn tinh chỉnh khi cần hành vi ổn định lâu dài, khi prompt ngày càng phình to hoặc khi cần chuyển sang một mô hình chuyên biệt nhỏ và nhanh hơn (thường kết hợp chưng cất ở bài &lt;strong&gt;26-05&lt;/strong&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chuỗi suy nghĩ&lt;/strong&gt; (&lt;em&gt;chain-of-thought&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.11903&quot;&gt;Wei et al., 2022&lt;/a&gt;) là một kỹ thuật &lt;em&gt;prompting&lt;/em&gt; yêu cầu mô hình trình bày các bước suy luận trung gian trước khi đưa ra đáp án cuối. Kỹ thuật này không bổ sung mô-đun kiến trúc mới mà dành thêm token giải mã để chia nhỏ phép tính phức tạp thành các bước dễ kiểm soát hơn. Về sau, các mô hình suy luận chuyên biệt &lt;em&gt;huấn luyện&lt;/em&gt; trực tiếp thói quen này (xem Chương 25-99).&lt;/p&gt;

&lt;h2 id=&quot;3-khả-năng-tuân-thủ-chỉ-dẫn-đến-từ-sft&quot;&gt;3. Khả năng tuân thủ chỉ dẫn đến từ SFT&lt;/h2&gt;

&lt;p&gt;Mô hình ngôn ngữ thô sau tiền huấn luyện có xu hướng viết tiếp theo ngữ cảnh: nếu đầu vào là một đoạn bài viết, nó sẽ viết tiếp bài viết đó thay vì trả lời câu hỏi. Tuy nhiên, người dùng cần một &lt;strong&gt;trợ lý&lt;/strong&gt; biết thực hiện yêu cầu, từ chối khi phù hợp và giữ phong cách nhất quán.&lt;/p&gt;

&lt;p&gt;Bước thích nghi đầu tiên thường là &lt;strong&gt;tinh chỉnh có giám sát (SFT)&lt;/strong&gt; trên tập dữ liệu các cặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(chỉ dẫn, câu trả lời)&lt;/code&gt; do con người biên soạn, chọn lọc hoặc do một mô hình mạnh hơn sinh ra và được kiểm duyệt. Hàm mất mát vẫn là cross-entropy dự đoán token kế tiếp, nhưng &lt;em&gt;phân bố dữ liệu&lt;/em&gt; đã chuyển từ “viết tiếp văn bản web” sang “trả lời đúng yêu cầu”.&lt;/p&gt;

&lt;p&gt;Sau SFT, &lt;em&gt;prompting&lt;/em&gt; vẫn rất hữu ích (cho gọi công cụ, RAG và định dạng), nhưng mô hình đã nhận diện văn bản người dùng như một &lt;em&gt;tác vụ cần thực hiện&lt;/em&gt;. Giai đoạn tối ưu theo sở thích ở bài sau tiếp tục xếp hạng những câu trả lời hợp lệ nào được ưa chuộng hơn.&lt;/p&gt;

&lt;p&gt;So với học chuyển giao cổ điển (Chương 15) vốn thay đầu phân loại cho một tập nhãn cố định, SFT theo chỉ dẫn vẫn dùng chung đầu sinh ngôn ngữ cho nhiều tác vụ khác nhau mô tả bằng văn bản — cùng cơ chế tối ưu nhưng khác giao diện tác vụ.&lt;/p&gt;

&lt;h2 id=&quot;4-danh-mục-kiểm-tra-khi-viết-prompt&quot;&gt;4. Danh mục kiểm tra khi viết prompt&lt;/h2&gt;

&lt;p&gt;Khi thử nghiệm trên các mô hình &lt;em&gt;instruct&lt;/em&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Xác định rõ &lt;strong&gt;vai trò&lt;/strong&gt; và &lt;strong&gt;định dạng đầu ra&lt;/strong&gt; (văn bản thuần, các khóa JSON, ngôn ngữ).&lt;/li&gt;
  &lt;li&gt;Đặt các &lt;strong&gt;ràng buộc bắt buộc&lt;/strong&gt; trước phần ngữ cảnh truy hồi dài để tránh bị cắt khỏi cửa sổ \(L\).&lt;/li&gt;
  &lt;li&gt;Khi dùng &lt;em&gt;few-shot&lt;/em&gt; (ICL), giữ các ví dụ minh họa &lt;strong&gt;đồng nhất định dạng&lt;/strong&gt; với truy vấn thực tế.&lt;/li&gt;
  &lt;li&gt;Nếu cần dữ liệu trích dẫn xác thực, hãy truy hồi trước bằng RAG (Chương 18-99) thay vì yêu cầu mô hình tự nhớ.&lt;/li&gt;
  &lt;li&gt;Nếu cần duy trì hành vi cố định trên quy mô lớn, nên lên kế hoạch SFT hoặc dùng &lt;em&gt;adapter&lt;/em&gt; thay vì để prompt phình dài tới hàng nghìn token.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;Prompting&lt;/em&gt; điều chỉnh tiền tố điều kiện; tinh chỉnh cập nhật trực tiếp trọng số mô hình.&lt;/li&gt;
  &lt;li&gt;Học trong ngữ cảnh (ICL) là cơ chế &lt;em&gt;few-shot&lt;/em&gt; ngay trong cửa sổ ngữ cảnh, không cập nhật tham số.&lt;/li&gt;
  &lt;li&gt;Khả năng tuân thủ chỉ dẫn chủ yếu đến từ việc thay đổi phân bố &lt;strong&gt;dữ liệu&lt;/strong&gt; qua SFT trên cùng hàm mất mát dự đoán token kế tiếp.&lt;/li&gt;
  &lt;li&gt;Căn chỉnh theo sở thích (&lt;strong&gt;26-03&lt;/strong&gt;) là bước bổ sung tiếp theo, không thay thế cho việc viết prompt rõ ràng.&lt;/li&gt;
  &lt;li&gt;Các tham số lấy mẫu khi giải mã (nhiệt độ, &lt;em&gt;top-k&lt;/em&gt;, &lt;em&gt;top-p&lt;/em&gt;) thuộc lớp phục vụ (&lt;strong&gt;26-04&lt;/strong&gt;), không phải dạng &lt;em&gt;prompting&lt;/em&gt; mới.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=As9a15poQHs&quot;&gt;What Is In-Context Learning in Deep Learning?&lt;/a&gt; — Deep Learning with Yacine, tiếng Anh. Giải thích cơ chế học trong ngữ cảnh thông qua các ví dụ đặt trực tiếp trong prompt.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Minh họa cách prompt chỉ là các token tiền tố đi vào cùng một mô hình dự đoán token kế tiếp.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Cho thấy trực tiếp trong mã nguồn rằng prompt chính là chuỗi tiền tố để bộ lấy mẫu sinh tiếp.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-01 Tiền huấn luyện và tokenization</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_01_Pretraining_and_Tokenization/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_01_Pretraining_and_Tokenization</id>
   <content type="html">&lt;p&gt;Trước khi một dòng văn bản kịp chạm tới tầng Attention đầu tiên, nó phải đi qua “cánh cửa” &lt;strong&gt;Tokenizer&lt;/strong&gt; — nơi một câu tiếng Việt có thể bị cắt thành vài token đẹp đẽ hoặc vụn vỡ thành hàng chục mảnh byte tùy cách huấn luyện BPE. Ngay sau đó là trái tim toán học của tiền huấn luyện LLM: công thức đạo hàm siêu gọn \(\partial\mathcal{L}/\partial z = p - t\), mẹo &lt;strong&gt;Log-Sum-Exp&lt;/strong&gt; chống tràn số mũ (tiền đề của FlashAttention), và quy ước chuyển vị \(X W^\top\) của PyTorch.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-tiền-huấn-luyện-và-tokenization&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Tiền huấn luyện và Tokenization&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình hóa ngôn ngữ tự hồi quy (Next-Token Prediction):&lt;/strong&gt; Tối ưu hóa trung bình Negative Log-Likelihood trên toàn chuỗi \(\mathcal{L} = -\frac{1}{T}\sum_{t=1}^T \ln P_\theta(x_t \mid x_{&amp;lt;t})\), liên hệ trực tiếp với chỉ số Perplexity \(\text{PPL} = e^{\mathcal{L}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Softmax + Cross-Entropy và đạo hàm \(p - t\):&lt;/strong&gt; Rút gọn đạo hàm của tổ hợp hai hàm phức tạp thành hiệu trực giác giữa phân phối dự đoán \(p\) và nhãn one-hot \(t\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ổn định số học Log-Sum-Exp và Online Softmax:&lt;/strong&gt; Trừ giá trị cực đại \(m = \max_i z_i\) trước khi lấy hàm mũ để không bao giờ gặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Inf&lt;/code&gt;, đồng thời cập nhật thống kê trượt từng khối (tiling) trong FlashAttention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy ước hình học tầng tuyến tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Linear&lt;/code&gt;:&lt;/strong&gt; Phân biệt công thức toán học \(Y = X W\) với cách lưu ma trận chuyển vị &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(out_features, in_features)&lt;/code&gt; của PyTorch để tránh sai lệch khi tính FLOPs hay ghép ma trận LoRA.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-softmax-ổn-định-số-học-cross-entropy-perplexity-và-gradient-p---t&quot;&gt;Giải thích: Tính tay Softmax ổn định số học, Cross-Entropy, Perplexity và gradient \(p - t\)&lt;/h3&gt;

&lt;p&gt;Giả sử từ điển thu nhỏ có 3 token &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[mèo, chó, cá]&lt;/code&gt;, nhãn đúng là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt; (\(\mathbf{t} = [1, 0, 0]\)), và tầng chiếu cuối xuất ra logit rất lớn \(\mathbf{z} = [1002{,}0,\; 1000{,}0,\; 1000{,}0]\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nếu tính ngây thơ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;exp(1002)&lt;/code&gt;:&lt;/strong&gt; Vượt quá giới hạn FP32 (\(\approx 3{,}4 \times 10^{38}\)) → lập tức trả về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Inf / Inf = NaN&lt;/code&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng mẹo trừ cực đại \(m = \max(\mathbf{z}) = 1002{,}0\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Logit dịch chuyển: \(\tilde{\mathbf{z}} = [0{,}0,\; -2{,}0,\; -2{,}0]\).&lt;/li&gt;
      &lt;li&gt;Hàm mũ an toàn: \([e^0,\; e^{-2},\; e^{-2}] \approx [1{,}0000,\; 0{,}1353,\; 0{,}1353]\) (tổng \(Z = 1{,}2706\)).&lt;/li&gt;
      &lt;li&gt;Phân phối xác suất: \(\mathbf{p} \approx [0{,}7870,\; 0{,}1065,\; 0{,}1065]\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-Entropy Loss &amp;amp; Perplexity:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(\mathcal{L} = -\ln(0{,}7870) \approx 0{,}2395\) → Perplexity tương ứng \(\text{PPL} = e^{0{,}2395} \approx 1{,}27\) (mô hình chỉ phân vân tương đương \(1{,}27\) lựa chọn).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient theo logit (\(\mathbf{p} - \mathbf{t}\)):&lt;/strong&gt;
\(\frac{\partial \mathcal{L}}{\partial \mathbf{z}} = [0{,}7870 - 1,\; 0{,}1065 - 0,\; 0{,}1065 - 0] = [-0{,}2130,\; +0{,}1065,\; +0{,}1065].\)
Hạ gradient sẽ trừ đi giá trị này: &lt;strong&gt;tăng&lt;/strong&gt; logit của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt; thêm \(0{,}213\eta\) và &lt;strong&gt;giảm&lt;/strong&gt; logit của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chó&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cá&lt;/code&gt; mỗi từ \(0{,}1065\eta\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tiền-huấn-luyện-và-tokenization&quot;&gt;Tiền huấn luyện và tokenization&lt;/h1&gt;

&lt;p&gt;Mô hình ngôn ngữ lớn (LLM) hiện đại được tiền huấn luyện với mục tiêu &lt;strong&gt;dự đoán token kế tiếp&lt;/strong&gt;. Mọi năng lực phía sau — &lt;em&gt;prompting&lt;/em&gt;, tuân thủ chỉ dẫn hay sử dụng công cụ — đều xây dựng trên một mô hình nhận chuỗi token tiền tố \(x_1,\ldots,x_{t-1}\) và xuất ra phân bố xác suất cho token kế tiếp \(x_t\).&lt;/p&gt;

&lt;p&gt;Bài này tập trung vào ba nền tảng cốt lõi ở mức khái niệm và toán học: hàm mục tiêu tiền huấn luyện, bộ tách token xác định tập ký hiệu đầu vào, và cửa sổ ngữ cảnh giới hạn phạm vi thông tin mô hình xử lý được.&lt;/p&gt;

&lt;h2 id=&quot;1-dự-đoán-token-kế-tiếp&quot;&gt;1. Dự đoán token kế tiếp&lt;/h2&gt;

&lt;p&gt;Gọi \(x = (x_1,\ldots,x_T)\) là một chuỗi token. Mô hình ngôn ngữ nhân quả phân rã xác suất đồng thời của chuỗi thành tích các xác suất có điều kiện:&lt;/p&gt;

\[p_\theta(x) = \prod_{t=1}^{T} p_\theta(x_t \mid x_{&amp;lt;t}).\]

&lt;p&gt;Quá trình huấn luyện tối thiểu hóa log-likelihood âm trung bình (hàm mất mát cross-entropy) trên kho văn bản:&lt;/p&gt;

\[\mathcal{L}(\theta) = -\frac{1}{T}\sum_{t=1}^{T} \log p_\theta(x_t \mid x_{&amp;lt;t}).\]

&lt;p&gt;Tại mỗi vị trí, mạng xuất ra vectơ logit \(z \in \mathbb{R}^{V}\) (với \(V\) là kích thước từ vựng), sau đó hàm softmax chuyển đổi thành phân bố \(p_\theta(\cdot \mid x_{&amp;lt;t})\). Vì “nhãn” chính là token kế tiếp có sẵn trong văn bản gốc mà không cần gán nhãn thủ công, đây là dạng &lt;strong&gt;học tự giám sát&lt;/strong&gt; theo tinh thần Chương 16 dù hàm mất mát có dạng phân loại thông thường.&lt;/p&gt;

&lt;p&gt;Hai hệ quả trực tiếp ảnh hưởng đến các bài sau trong chương:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Không gian đầu ra &lt;strong&gt;rất lớn&lt;/strong&gt; (thường \(V \sim 32\mathrm{k}\)–\(200\mathrm{k}+\)). Vì vậy, chưng cất tri thức cổ điển khớp toàn bộ softmax như trên tập 1.000 lớp (Chương 23) không còn rẻ khi chuyển sang LLM — xem thêm bài &lt;strong&gt;26-05&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Huấn luyện sử dụng cơ chế &lt;strong&gt;teacher forcing&lt;/strong&gt;: mô hình luôn dự đoán dựa trên tiền tố &lt;em&gt;thật&lt;/em&gt; từ dữ liệu, còn khi sinh văn bản thực tế nó phải dựa trên các token do chính mình sinh ra. Sự khác biệt giữa huấn luyện và suy luận là đặc trưng cố hữu; các kỹ thuật căn chỉnh và lấy mẫu được thiết kế để xử lý hiện tượng này.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Đoạn mã minh họa hàm mất mát trong PyTorch:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;next_token_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# logits: (batch, seq, vocab) cho vị trí 0..T-1
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# targets: token kế tại mỗi vị trí
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;ignore_index&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# padding
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Các mục dưới đây tóm tắt phần toán học trực tiếp tại tầng đầu ra, tầng tuyến tính và bộ tối ưu trong bối cảnh LLM (các chứng minh đầy đủ đã có ở Chương 02–03 và Chương 10).&lt;/p&gt;

&lt;h2 id=&quot;2-softmax-cross-entropy-và-partialmathcallpartial-z--p---t&quot;&gt;2. Softmax, cross-entropy và \(\partial\mathcal{L}/\partial z = p - t\)&lt;/h2&gt;

&lt;p&gt;Tại mỗi vị trí, mô hình sinh ra vectơ logit \(z \in \mathbb{R}^{V}\). Hàm softmax cho xác suất từng token:&lt;/p&gt;

\[p_i = \frac{e^{z_i}}{\sum_{j=1}^{V} e^{z_j}}.\]

&lt;p&gt;Với nhãn mục tiêu dạng &lt;em&gt;one-hot&lt;/em&gt; \(t\) (chỉ bằng 1 tại chỉ số token đúng \(t^*\)), hàm mất mát cross-entropy là:&lt;/p&gt;

\[\mathcal{L} = -\sum_{i=1}^{V} t_i \log p_i = -\log p_{t^*}.\]

&lt;p&gt;Lấy đạo hàm theo vectơ logit \(z\) thu được hằng đẳng thức quen thuộc:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial z} = p - t.\]

&lt;p&gt;Đây chính là kết quả giản ước của cross-entropy kết hợp softmax từ Chương 03, nhưng ở LLM phép tính này diễn ra tại mọi vị trí trong chuỗi trên từ vựng cỡ hàng chục đến hàng trăm nghìn phần tử.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quan hệ giữa CE, KL và entropy.&lt;/strong&gt; Với hai phân bố rời rạc bất kỳ \(p^*\) và \(p\):&lt;/p&gt;

\[\mathrm{CE}(p^*, p) = H(p^*) + \mathrm{KL}(p^* \| p).\]

&lt;p&gt;Khi \(p^*\) là phân bố &lt;em&gt;one-hot&lt;/em&gt;, entropy \(H(p^*) = 0\), nên cross-entropy trùng khớp hoàn toàn với \(\mathrm{KL}(\text{one-hot} \| p)\) và log-likelihood âm. Khi mục tiêu là phân bố &lt;em&gt;mềm&lt;/em&gt; từ mô hình giáo viên trong chưng cất (&lt;strong&gt;26-05&lt;/strong&gt;), \(H(p^*)\) là hằng số đối với mô hình học sinh nên tín hiệu tối ưu chính là phân kỳ KL.&lt;/p&gt;

&lt;h2 id=&quot;3-log-sum-exp-và-cơ-chế-softmax-trực-tuyến-trong-flashattention&quot;&gt;3. Log-sum-exp và cơ chế “softmax trực tuyến” trong FlashAttention&lt;/h2&gt;

&lt;p&gt;Tính trực tiếp \(e^{z_i}\) dễ gây tràn số khi giá trị logit lớn. Để ổn định số học, ta trừ đi giá trị lớn nhất trên hàng \(m = \max_j z_j\):&lt;/p&gt;

\[\log\sum_j e^{z_j} = m + \log\sum_j e^{z_j - m}, \qquad p_i = \exp\big(z_i - \mathrm{LSE}(z)\big).\]

&lt;p&gt;Kỹ thuật &lt;strong&gt;log-sum-exp&lt;/strong&gt; này có thể cập nhật &lt;em&gt;tăng dần&lt;/em&gt; theo từng khối: nếu đã có giá trị lớn nhất tạm thời \(m\) và tổng chuẩn hóa \(s = \sum e^{z-m}\) trên phần tiền tố, khi nhận thêm một khối logit mới với cực đại \(m&apos;\), ta cập nhật:&lt;/p&gt;

\[s \leftarrow s\, e^{m - m_{\mathrm{new}}} + \sum_{\text{new}} e^{z - m_{\mathrm{new}}}, \quad m_{\mathrm{new}} = \max(m, m&apos;).\]

&lt;p&gt;Kết hợp cập nhật tương tự cho tổng có trọng số của các vectơ &lt;em&gt;value&lt;/em&gt;, ta thu được &lt;strong&gt;softmax trực tuyến&lt;/strong&gt; (&lt;em&gt;online softmax&lt;/em&gt;) — nền tảng số học của &lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;FlashAttention&lt;/a&gt;. Nhờ đó, như sẽ thấy ở bài &lt;strong&gt;26-07&lt;/strong&gt;, GPU không cần lưu toàn bộ ma trận điểm \(L \times L\) xuống bộ nhớ HBM.&lt;/p&gt;

&lt;h2 id=&quot;4-tầng-tuyến-tính-quy-ước-toán-học-xw-và-pytorch&quot;&gt;4. Tầng tuyến tính: Quy ước toán học \(XW\) và PyTorch&lt;/h2&gt;

&lt;p&gt;Với một batch trạng thái ẩn \(X \in \mathbb{R}^{B \times d_{\mathrm{in}}}\), sách giáo khoa thường viết:&lt;/p&gt;

\[Y = X W + b, \qquad W \in \mathbb{R}^{d_{\mathrm{in}} \times d_{\mathrm{out}}}.\]

&lt;p&gt;Trong khi đó, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.Linear(n_in, n_out)&lt;/code&gt; lưu thuộc tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight&lt;/code&gt; theo kích thước &lt;strong&gt;\((n_{\mathrm{out}}, n_{\mathrm{in}})\)&lt;/strong&gt; và tính \(X W^\top + b\). Hai cách biểu diễn mô tả cùng một ánh xạ tuyến tính, chỉ khác nhau ở phép chuyển vị. Khi đếm số tham số ở bài &lt;strong&gt;26-07&lt;/strong&gt;, mỗi phép chiếu vẫn có \(d_{\mathrm{in}} \times d_{\mathrm{out}}\) trọng số; khi cài đặt lại một bài báo, cần kiểm tra rõ quy ước chiều ma trận của tác giả.&lt;/p&gt;

&lt;h2 id=&quot;5-hàm-kích-hoạt-trong-tầng-ffn&quot;&gt;5. Hàm kích hoạt trong tầng FFN&lt;/h2&gt;

&lt;p&gt;Các hàm kích hoạt đã trình bày ở Chương 02; trong LLM có ba công thức quan trọng:&lt;/p&gt;

\[\begin{aligned}
\mathrm{ReLU}(z) &amp;amp;= \max(0, z), \\
\mathrm{SiLU}(z) = \mathrm{Swish}(z) &amp;amp;= z\,\sigma(z), \\
\mathrm{SwiGLU}(x) &amp;amp;= \big(\mathrm{SiLU}(x W_{\mathrm{gate}}) \odot (x W_{\mathrm{up}})\big) W_{\mathrm{down}}.
\end{aligned}\]

&lt;p&gt;ReLU được dùng trong Transformer năm 2017; SiLU là hàm cổng trơn; còn SwiGLU là khối FFN có cổng gồm ba ma trận trọng số kết hợp tích theo phần tử (Hadamard), được sử dụng phổ biến trong các decoder hiện đại (&lt;strong&gt;26-07&lt;/strong&gt;). Một số mô hình kiểu GPT đời cũ dùng GELU (Chương 02).&lt;/p&gt;

&lt;h2 id=&quot;6-adam--adamw-moment-và-quy-ước-áp-dụng-weight-decay&quot;&gt;6. Adam / AdamW: Moment và quy ước áp dụng weight decay&lt;/h2&gt;

&lt;p&gt;Tiền huấn luyện LLM hầu như luôn dùng &lt;strong&gt;AdamW&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/1711.05101&quot;&gt;Loshchilov &amp;amp; Hutter, 2019&lt;/a&gt;) thay vì Adam gốc (&lt;a href=&quot;https://arxiv.org/abs/1412.6980&quot;&gt;Kingma &amp;amp; Ba, 2015&lt;/a&gt;). Hai ước lượng moment bậc một và bậc hai giữ nguyên như Chương 10:&lt;/p&gt;

\[\begin{aligned}
m_t &amp;amp;= \beta_1 m_{t-1} + (1-\beta_1) g_t, \\
v_t &amp;amp;= \beta_2 v_{t-1} + (1-\beta_2) g_t^{\odot 2}, \\
\hat{m}_t &amp;amp;= \frac{m_t}{1-\beta_1^t}, \quad
\hat{v}_t = \frac{v_t}{1-\beta_2^t}.
\end{aligned}\]

&lt;p&gt;Nếu cộng trực tiếp số hạng chính quy hóa L2 vào hàm mất mát trong Adam, gradient của L2 cũng bị chia bởi \(\sqrt{\hat{v}_t}\) nên suy giảm trọng số không còn đồng đều. AdamW &lt;strong&gt;tách riêng&lt;/strong&gt; bước suy giảm trọng số (&lt;em&gt;decoupled weight decay&lt;/em&gt;):&lt;/p&gt;

\[\theta_t = \theta_{t-1} - \eta \left( \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\varepsilon} + \lambda \theta_{t-1} \right).\]

&lt;p&gt;&lt;strong&gt;Tham số nào nhận \(\lambda &amp;gt; 0\)?&lt;/strong&gt; Theo quy ước phổ biến trong các trình huấn luyện LLM (như Hugging Face &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AdamW&lt;/code&gt; hay các cấu hình họ Llama), &lt;em&gt;weight decay&lt;/em&gt; được áp dụng cho các &lt;strong&gt;ma trận trọng số 2-D&lt;/strong&gt; (các phép chiếu &lt;em&gt;attention&lt;/em&gt;, FFN, và thường cả bảng nhúng / đầu LM), nhưng &lt;strong&gt;không&lt;/strong&gt; áp dụng cho các tensor 1-D như hệ số điều chỉnh (&lt;em&gt;bias&lt;/em&gt;) và hệ số tỉ lệ (&lt;em&gt;gain&lt;/em&gt;) của RMSNorm / LayerNorm để tránh xung đột với vai trò chuẩn hóa của chúng (xem thêm &lt;strong&gt;10-01&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;7-tại-sao-dùng-tokenization-dưới-từ-thay-vì-ký-tự-hoặc-từ-nguyên-vẹn&quot;&gt;7. Tại sao dùng tokenization dưới từ thay vì ký tự hoặc từ nguyên vẹn?&lt;/h2&gt;

&lt;p&gt;Tách theo từng ký tự khiến chuỗi đầu vào quá dài và tiêu tốn năng lực mô hình cho chính tả. Ngược lại, tách theo từ nguyên vẹn khiến từ vựng phình to và dễ gặp lỗi với từ hiếm hoặc từ mới. &lt;strong&gt;Tokenization dưới từ&lt;/strong&gt; (&lt;em&gt;subword tokenization&lt;/em&gt;) cân bằng hai cực này: giữ nguyên các từ phổ biến thành một token và tách các từ hiếm thành các mảnh ghép tái sử dụng được.&lt;/p&gt;

&lt;p&gt;Hai thuật toán phổ biến nhất trong thực tế:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Byte Pair Encoding (BPE):&lt;/strong&gt; Bắt đầu từ tập ký tự (hoặc byte) rồi lặp lại việc gộp cặp token liền kề xuất hiện nhiều nhất thành một token mới; bảng các quy tắc gộp tạo thành bộ tokenizer. &lt;a href=&quot;https://arxiv.org/abs/1508.07909&quot;&gt;Sennrich et al., 2016&lt;/a&gt; áp dụng BPE cho dịch máy nơ-ron, và các tokenizer kiểu GPT-2 kế thừa trực tiếp phương pháp này. Thư viện &lt;a href=&quot;https://github.com/openai/tiktoken&quot;&gt;tiktoken&lt;/a&gt; của OpenAI là bản cài đặt tối ưu tốc độ của BPE.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Unigram / SentencePiece:&lt;/strong&gt; Thay vì gộp tham lam từ dưới lên, mô hình Unigram khởi tạo một tập từ vựng ứng viên lớn rồi loại bỏ dần các token ít làm giảm hàm likelihood. &lt;a href=&quot;https://arxiv.org/abs/1808.06226&quot;&gt;Kudo &amp;amp; Richardson, 2018&lt;/a&gt; (SentencePiece) là công cụ phổ biến cho phép huấn luyện trực tiếp trên văn bản thô (hỗ trợ cả BPE và Unigram), được dùng rộng rãi trong nhiều mô hình đa ngôn ngữ mở.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Một số đặc điểm thực hành quan trọng:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Tokenization là &lt;strong&gt;bước tiền xử lý tất định&lt;/strong&gt;: mô hình chỉ nhìn thấy chuỗi chỉ số token chứ không thấy trực tiếp cấu trúc ký tự bên trong, và không thể sinh ra ID nằm ngoài bảng từ vựng.&lt;/li&gt;
  &lt;li&gt;Cùng một từ có thể tương ứng 1 token ở bộ từ vựng này nhưng 3 token ở bộ từ vựng khác; do đó &lt;strong&gt;chi phí và độ dài ngữ cảnh luôn được tính theo token, không phải theo từ&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Các token đặc biệt (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;bos&amp;gt;&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;eos&amp;gt;&lt;/code&gt;, thẻ định dạng hội thoại, thẻ gọi công cụ) là thành phần chính thức của từ vựng; cấu hình sai chúng có thể làm lãng phí ngữ cảnh hoặc phá vỡ khuôn mẫu hội thoại.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bảng nhúng \(E \in \mathbb{R}^{V \times d}\) của Chương 18 chính là tầng đầu tiên (tầng 0) của mô hình ngôn ngữ: mỗi ID token được ánh xạ thành một vectơ, sau đó thông tin vị trí (như RoPE, bài tùy chọn &lt;strong&gt;08-99&lt;/strong&gt;) được đưa vào bên trong cơ chế &lt;em&gt;attention&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;8-cửa-sổ-ngữ-cảnh&quot;&gt;8. Cửa sổ ngữ cảnh&lt;/h2&gt;

&lt;p&gt;Cơ chế &lt;em&gt;self-attention&lt;/em&gt; chuẩn tính tương tác giữa mọi cặp vị trí trong cửa sổ. Với độ dài ngữ cảnh \(L\), độ phức tạp của &lt;em&gt;attention&lt;/em&gt; tại mỗi tầng là \(O(L^2)\), khiến \(L\) đồng thời là giới hạn về &lt;strong&gt;khả năng nắm bắt ngữ cảnh&lt;/strong&gt; lẫn &lt;strong&gt;tính toán và bộ nhớ&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Trong thực tế, cửa sổ ngữ cảnh quy định ba điều:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Mô hình chỉ điều kiện hóa trực tiếp trên tối đa \(L\) token (gồm prompt, lịch sử hội thoại, đoạn truy hồi RAG từ Chương 18-99 và phần đã sinh).&lt;/li&gt;
  &lt;li&gt;Các tài liệu quá dài phải được chia nhỏ, tóm tắt hoặc truy hồi theo đoạn; việc một ứng dụng xử lý tài liệu PDF 200 trang thường dựa vào hệ thống truy hồi đưa các đoạn liên quan vào trong giới hạn \(L\).&lt;/li&gt;
  &lt;li&gt;Khi giải mã, các vectơ &lt;em&gt;key&lt;/em&gt; và &lt;em&gt;value&lt;/em&gt; của toàn bộ tiền tố được lưu lại trong &lt;strong&gt;KV-cache&lt;/strong&gt; để tái sử dụng (xem bài &lt;strong&gt;26-04&lt;/strong&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Các cải tiến như cửa sổ trượt (&lt;em&gt;sliding window&lt;/em&gt;), &lt;em&gt;grouped-query attention&lt;/em&gt; hay mở rộng RoPE giúp giảm hằng số tính toán và bộ nhớ, nhưng không thay đổi bản chất rằng mô hình vẫn làm việc trên một vùng nhớ ngữ cảnh hữu hạn.&lt;/p&gt;

&lt;h2 id=&quot;9-dữ-liệu-tiền-huấn-luyện&quot;&gt;9. Dữ liệu tiền huấn luyện&lt;/h2&gt;

&lt;p&gt;Kho dữ liệu tiền huấn luyện thường kết hợp văn bản web đã lọc, sách, mã nguồn và các tài liệu chuyên ngành. Ba điểm cốt lõi cần lưu ý:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Hàm mất mát thưởng cho &lt;strong&gt;độ trôi chảy và mức độ phù hợp thống kê với ngữ liệu&lt;/strong&gt;, không đảm bảo tính đúng đắn sự kiện; hiện tượng ảo giác (&lt;em&gt;hallucination&lt;/em&gt;) là hệ quả tự nhiên khi lấy mẫu từ một phân bố \(p_\theta\) chưa hoàn hảo.&lt;/li&gt;
  &lt;li&gt;Quy trình lọc dữ liệu và khử trùng lặp là một phần quan trọng quyết định chất lượng mô hình: hai mô hình giống hệt kiến trúc có thể cho hành vi rất khác nhau nếu huấn luyện trên hai kho dữ liệu khác nhau.&lt;/li&gt;
  &lt;li&gt;Định luật mở rộng (Chương 25 và bài &lt;strong&gt;26-07&lt;/strong&gt;) liên kết hàm mất mát với số tham số, số token và ngân sách tính toán.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Tiền huấn luyện LLM là tối đa hóa xác suất dự đoán token kế tiếp dưới mặt nạ nhân quả.&lt;/li&gt;
  &lt;li&gt;Softmax kết hợp cross-entropy cho đạo hàm đơn giản \(\partial\mathcal{L}/\partial z = p - t\); cross-entropy bằng tổng entropy và phân kỳ KL (trùng với NLL khi nhãn là &lt;em&gt;one-hot&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Log-sum-exp&lt;/em&gt; ổn định phép tính softmax, còn biến thể trực tuyến theo khối là nền tảng của FlashAttention (&lt;strong&gt;26-07&lt;/strong&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Linear&lt;/code&gt; của PyTorch lưu trọng số kích thước \((n_{\mathrm{out}}, n_{\mathrm{in}})\) và tính \(X W^\top\); AdamW thường áp dụng &lt;em&gt;weight decay&lt;/em&gt; cho ma trận trọng số 2-D và bỏ qua các tham số chuẩn hóa 1-D.&lt;/li&gt;
  &lt;li&gt;Tokenizer dưới từ (BPE, SentencePiece) xác định tập ký hiệu rời rạc của mô hình.&lt;/li&gt;
  &lt;li&gt;Độ dài ngữ cảnh \(L\) quyết định phạm vi chú ý của &lt;em&gt;attention&lt;/em&gt; và dung lượng KV-cache khi phục vụ.&lt;/li&gt;
  &lt;li&gt;Chính kích thước từ vựng \(V\) lớn khiến chưng cất logit cổ điển trở nên đắt đỏ với LLM (xem tiếp ở bài &lt;strong&gt;26-05&lt;/strong&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=zduSFxRajkE&quot;&gt;Let’s build the GPT Tokenizer&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Hướng dẫn xây dựng chi tiết bộ tokenizer BPE, bổ sung trực tiếp cho phần tokenization trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=hL4ZnAWSyuU&quot;&gt;LLM Tokenizers Explained: BPE Encoding, WordPiece and SentencePiece&lt;/a&gt; — DataMListic, tiếng Anh. So sánh ngắn gọn giữa BPE, WordPiece và SentencePiece trước khi đi sâu vào cài đặt.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Minh họa hàm mất mát cross-entropy dự đoán ký tự kế tiếp — nền tảng của mục tiêu tiền huấn luyện trước khi áp dụng tokenization dưới từ.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26 Mô hình ngôn ngữ lớn</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter26/26_00_Introduction</id>
   <content type="html">&lt;p&gt;Thật khó tin khi toàn bộ năng lực viết thơ, gỡ lỗi mã nguồn C++, tóm tắt hợp đồng pháp lý và giải toán Olympiad của một Mô hình Ngôn ngữ Lớn (LLM) lại khởi nguồn từ đúng một bài toán tưởng chừng đơn giản đến bất ngờ: &lt;strong&gt;đoán từ tiếp theo&lt;/strong&gt; trên hàng nghìn tỷ từ văn bản! Chương 26 kết nối toàn bộ nền móng học sâu bạn đã học suốt 25 chương trước — từ đại số tuyến tính, Softmax, Transformer đến RLHF và nén mô hình — thành một bức tranh hoàn chỉnh từ tiền huấn luyện đến triển khai thực tế của LLM hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-vòng-đời-mô-hình-ngôn-ngữ-lớn-llm&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của vòng đời Mô hình Ngôn ngữ Lớn (LLM)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tiền huấn luyện và Tokenization (26-01):&lt;/strong&gt; Biến văn bản thành chuỗi token BPE, tối ưu dự đoán token kế tiếp bằng Cross-Entropy và FlashAttention ổn định số học.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học trong ngữ cảnh và Căn chỉnh (26-02 &amp;amp; 26-03):&lt;/strong&gt; Biến mô hình “tiếp nối văn bản” thành trợ lý hữu ích nhờ Prompting/ICL, Tinh chỉnh có giám sát (SFT) và tối ưu sở thích (RLHF/DPO).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phục vụ suy luận và Chưng cất (26-04 &amp;amp; 26-05):&lt;/strong&gt; Vượt qua nút cổ chai bộ nhớ KV Cache ở pha Decode bằng Continuous Batching, Speculative Decoding và chưng cất dữ liệu tổng hợp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nội tại Decoder hiện đại và Hạch toán chi phí (26-06 &amp;amp; 26-07):&lt;/strong&gt; Giải phẫu từng mảnh ghép kiến trúc Llama/Qwen/Gemma (RMSNorm, SwiGLU, RoPE, GQA) và tự tay tính toán chính xác FLOPs, tham số và VRAM.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-nhẩm-chi-phí-lưu-trữ-kv-cache-cho-một-phiên-hội-thoại-8192-token&quot;&gt;Giải thích: Tính nhẩm chi phí lưu trữ KV Cache cho một phiên hội thoại 8.192 token&lt;/h3&gt;

&lt;p&gt;Để hiểu ngay vì sao kỹ thuật hệ thống lại quan trọng trong chương này, hãy tính dung lượng &lt;strong&gt;KV Cache&lt;/strong&gt; của một mô hình Transformer chuẩn \(32\) tầng, \(32\) đầu chú ý, chiều mỗi đầu \(d_h = 128\), lưu ở FP16 (\(2\text{ byte/số}\)) cho đúng &lt;strong&gt;1 người dùng&lt;/strong&gt; có ngữ cảnh dài \(L = 8{,}192\) token:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bộ nhớ cho 1 token trên 1 tầng (cả Key và Value):&lt;/strong&gt;
\(2 \times 32 \times 128 \times 2\text{ byte} = 16{,}384\text{ byte} = 16\text{ KB/token/tầng}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cho cả 32 tầng trên 1 token:&lt;/strong&gt; \(32 \times 16\text{ KB} = 512\text{ KB/token}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cho toàn bộ ngữ cảnh \(L = 8{,}192\) token:&lt;/strong&gt;
\(8{,}192 \times 512\text{ KB} = 4{,}194{,}304\text{ KB} = 4{,}0\text{ GB VRAM}\) cho chỉ &lt;em&gt;một&lt;/em&gt; người dùng!
Nếu có 16 người dùng cùng lúc, riêng KV Cache đã ngốn \(64\text{ GB}\) — giải thích ngay vì sao bài &lt;strong&gt;26-07&lt;/strong&gt; dùng &lt;strong&gt;Grouped-Query Attention (GQA)&lt;/strong&gt; để nén bộ nhớ KV đi \(4\text{–}8\times\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;chương-26--mô-hình-ngôn-ngữ-lớn&quot;&gt;Chương 26 — Mô hình ngôn ngữ lớn&lt;/h1&gt;

&lt;p&gt;Chương này đóng vai trò &lt;strong&gt;trung tâm tổng hợp về mô hình ngôn ngữ lớn (LLM)&lt;/strong&gt; của khóa học. Các chương trước đã xây dựng từng mảnh ghép riêng lẻ: cơ chế &lt;em&gt;attention&lt;/em&gt; (Chương 07), khối Transformer (Chương 08), nhúng từ tĩnh và theo ngữ cảnh (Chương 18), nén mô hình (Chương 23) và căn chỉnh theo sở thích dưới góc nhìn học tăng cường (Chương 20–21). Chương này ghép các thành phần đó thành một lộ trình thống nhất, xét trực tiếp &lt;strong&gt;mô hình ngôn ngữ Transformer chỉ-decoder ở quy mô lớn&lt;/strong&gt; qua toàn bộ vòng đời: tiền huấn luyện, &lt;em&gt;prompting&lt;/em&gt;, căn chỉnh, phục vụ suy luận và chưng cất.&lt;/p&gt;

&lt;p&gt;Trong khi Chương 25 khảo sát rộng các hướng nghiên cứu mở, chương này đi thẳng vào những kiến thức cốt lõi để &lt;em&gt;sử dụng và phân tích&lt;/em&gt; LLM hiện đại mà không cần chứng minh lại toàn bộ Transformer từ đầu. Bài &lt;strong&gt;26-07&lt;/strong&gt; tổng hợp cấu trúc khối decoder giai đoạn 2024–2026, cách ước lượng FLOPs và bộ nhớ thường gặp khi phỏng vấn, cùng phân tích định luật mở rộng kiểu Chinchilla.&lt;/p&gt;

&lt;h2 id=&quot;tại-sao-cần-chương-này&quot;&gt;Tại sao cần chương này?&lt;/h2&gt;

&lt;p&gt;Trong phạm vi chương này, một LLM là &lt;strong&gt;mô hình ngôn ngữ Transformer nhân quả (chỉ-decoder)&lt;/strong&gt; được huấn luyện để dự đoán token kế tiếp trên kho văn bản quy mô rất lớn, sau đó thường được tinh chỉnh để tuân thủ chỉ dẫn và đáp ứng các yêu cầu về an toàn cũng như phong cách sản phẩm.&lt;/p&gt;

&lt;p&gt;Định nghĩa này hàm chứa bốn lựa chọn thiết kế cốt lõi:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc chỉ-decoder&lt;/strong&gt; — mô hình chỉ điều kiện hóa trên ngữ cảnh phía bên trái nhờ mặt nạ nhân quả (&lt;em&gt;causal mask&lt;/em&gt;), không tách riêng nhánh encoder như kiến trúc encoder–decoder gốc của Vaswani (dù dòng encoder–decoder như T5 vẫn tồn tại).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mục tiêu mô hình ngôn ngữ&lt;/strong&gt; — tối ưu hóa khả năng dự đoán token tiếp theo thay vì phân loại theo tập nhãn thủ công.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy mô lớn&lt;/strong&gt; — độ rộng, độ sâu, lượng dữ liệu và năng lực tính toán đủ lớn để &lt;em&gt;prompting&lt;/em&gt; và học trong ngữ cảnh trở thành giao diện sử dụng hiệu quả.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thích nghi sau tiền huấn luyện&lt;/strong&gt; — mô hình dự đoán token thô chỉ hoàn thiện tiếp văn bản; để làm trợ lý hữu ích, mô hình cần học cách làm theo chỉ dẫn và căn chỉnh theo sở thích con người.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nếu đã nắm được cấu trúc một tầng Transformer ở Chương 08, bạn đã có nền tảng kiến trúc; chương này tập trung trả lời câu hỏi: &lt;em&gt;vận hành và tối ưu hệ thống đó như thế nào khi triển khai thành sản phẩm?&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;liên-kết-với-các-chương-trước&quot;&gt;Liên kết với các chương trước&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Chương trước&lt;/th&gt;
      &lt;th&gt;Kiến thức được sử dụng lại ở đây&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;01–03, 10 Toán / huấn luyện&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Nhân ma trận theo batch, đạo hàm softmax + cross-entropy, Adam / AdamW — ôn lại ở &lt;strong&gt;26-01&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;02 Kích hoạt / MLP&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;ReLU, SiLU/Swish, cấu trúc SwiGLU (&lt;strong&gt;02-99&lt;/strong&gt;); dùng lại ở &lt;strong&gt;26-07&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;05–06 RNN / LSTM&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Đối chiếu với &lt;em&gt;attention&lt;/em&gt; và trạng thái KV tăng theo độ dài chuỗi (&lt;strong&gt;26-07&lt;/strong&gt;)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;07 Attention&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;em&gt;Scaled dot-product&lt;/em&gt;, mặt nạ nhân quả, &lt;em&gt;multi-head&lt;/em&gt;; FlashAttention và GQA ở &lt;strong&gt;07-99&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08 Transformer&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Khối phần dư, chuẩn hóa và FFN; RoPE và KV-cache ở bài tùy chọn &lt;strong&gt;08-99&lt;/strong&gt;, tổng hợp lại cho LLM ở &lt;strong&gt;26-07&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;18 NLP / embedding&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Bảng nhúng token ở tầng đầu tiên; biểu diễn tĩnh và theo ngữ cảnh; RAG ở &lt;strong&gt;18-99&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;20–21 RL / RL sâu&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Quy trình RLHF (mô hình phần thưởng + PPO) và DPO — chương này phác họa đường ống tổng thể&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;23 Học sâu hiệu quả&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Lượng tử hóa, cắt tỉa và chưng cất tri thức &lt;em&gt;cổ điển&lt;/em&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;25 Hướng tương lai&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Tổng quan định luật mở rộng và tính toán lúc suy luận — phần tối ưu tính toán lúc huấn luyện kiểu Chinchilla ở &lt;strong&gt;26-07&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Tách riêng phần chưng cất:&lt;/strong&gt; Chương 23 trình bày chưng cất tri thức (KD) cổ điển cho không gian đầu ra cố định (như phân loại ảnh). Bài &lt;strong&gt;26-05&lt;/strong&gt; tiếp nối trong bối cảnh LLM: giải thích vì sao khớp logit toàn bộ từ vựng trở nên tốn kém và vì sao chưng cất qua dữ liệu tổng hợp / phản hồi được dùng rộng rãi.&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành chương này, người học cần có khả năng:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Định nghĩa LLM như mô hình ngôn ngữ Transformer nhân quả quy mô lớn và phân biệt với kiến trúc encoder (kiểu BERT) cũng như encoder–decoder (kiểu T5).&lt;/li&gt;
  &lt;li&gt;Giải thích cơ chế tiền huấn luyện dự đoán token kế tiếp, tokenization dưới từ và giới hạn thực tế của cửa sổ ngữ cảnh.&lt;/li&gt;
  &lt;li&gt;Phân biệt rõ &lt;strong&gt;prompting / học trong ngữ cảnh&lt;/strong&gt; với &lt;strong&gt;tinh chỉnh cập nhật tham số&lt;/strong&gt;, biết khi nào nên chọn phương án nào.&lt;/li&gt;
  &lt;li&gt;Phác họa quy trình căn chỉnh &lt;strong&gt;SFT → tối ưu sở thích (RLHF / DPO)&lt;/strong&gt; và biết phần toán RL chi tiết nằm ở Chương 20–21.&lt;/li&gt;
  &lt;li&gt;Viết được đạo hàm của softmax kết hợp cross-entropy \(\partial\mathcal{L}/\partial z = p - t\), công thức &lt;em&gt;log-sum-exp&lt;/em&gt; ổn định số học và mối liên hệ giữa CE, KL và entropy.&lt;/li&gt;
  &lt;li&gt;Trình bày các yếu tố then chốt khi phục vụ giải mã (KV-cache, gom batch, &lt;em&gt;speculative decoding&lt;/em&gt;, lấy mẫu) và xác định &lt;strong&gt;khi nào nên chuyển sang chưng cất&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Vẽ cấu trúc một tầng decoder hiện đại (RMSNorm → attention + RoPE → SwiGLU), ước lượng thứ tự độ lớn của FLOPs và bộ nhớ suy luận, đồng thời diễn giải ý tưởng tối ưu tính toán kiểu Chinchilla.&lt;/li&gt;
  &lt;li&gt;Phân biệt KD cổ điển, chưng cất dữ liệu tổng hợp và chưng cất đặc trưng/logit hộp trắng, cũng như ranh giới giữa sử dụng hợp lệ và sử dụng trái điều khoản.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;lộ-trình-bài-học&quot;&gt;Lộ trình bài học&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Bài học&lt;/th&gt;
      &lt;th&gt;Trọng tâm&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-01 Tiền huấn luyện và tokenization&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Hàm mất mát dự đoán token kế tiếp, toán softmax/CE, AdamW, BPE / SentencePiece, cửa sổ ngữ cảnh&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-02 Prompting và học trong ngữ cảnh&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Zero-shot, few-shot, tuân thủ chỉ dẫn so với tinh chỉnh cổ điển&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-03 Căn chỉnh: SFT đến tối ưu sở thích&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;SFT → mô hình phần thưởng / PPO → DPO kèm hàm mục tiêu mức cao; liên kết về Ch. 20–21&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-04 Phục vụ và hiệu năng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;KV-cache, gom batch, &lt;em&gt;speculative decoding&lt;/em&gt;, chiến lược lấy mẫu, tiêu chí chọn chưng cất&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-05 Chưng cất mô hình cho LLM&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Ôn tập KD cổ điển, ba họ chưng cất hiện đại và mã minh họa&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-07 Nội tại decoder và hạch toán chi phí&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;RMSNorm, SwiGLU, RoPE, FlashAttention, ước lượng FLOPs/bộ nhớ, scaling và song song hóa&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-06 Luyện phỏng vấn&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Bộ câu hỏi thảo luận tự luyện (tùy chọn)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;điều-kiện-tiên-quyết&quot;&gt;Điều kiện tiên quyết&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Chương 07–08 (&lt;em&gt;attention&lt;/em&gt;, tầng Transformer và mặt nạ nhân quả).&lt;/li&gt;
  &lt;li&gt;Phân bố categorical qua softmax và cross-entropy như log-likelihood âm (Chương 03).&lt;/li&gt;
  &lt;li&gt;Khái niệm nhúng từ (Chương 18).&lt;/li&gt;
  &lt;li&gt;Nên xem trước nhưng không bắt buộc: nén mô hình ở Chương 23 và bài &lt;strong&gt;21-99&lt;/strong&gt; về RLHF/DPO.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;mô-hình-tư-duy&quot;&gt;Mô hình tư duy&lt;/h2&gt;

&lt;p&gt;Có thể hình dung một LLM triển khai thực tế gồm &lt;strong&gt;bốn lớp thích nghi trên cùng một kiến trúc decoder&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tiền huấn luyện&lt;/strong&gt; — học phân bố \(p(x_t \mid x_{&amp;lt;t})\) trên kho văn bản rộng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thích nghi giao diện&lt;/strong&gt; — &lt;em&gt;prompt&lt;/em&gt;, ví dụ &lt;em&gt;few-shot&lt;/em&gt; và dữ liệu chỉ dẫn có giám sát (SFT).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thích nghi theo sở thích&lt;/strong&gt; — tối ưu theo phản hồi so sánh từ con người hoặc mô hình đánh giá, vượt ra ngoài xác suất văn bản web thông thường.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thích nghi chi phí&lt;/strong&gt; — tối ưu &lt;em&gt;cache&lt;/em&gt;, lượng tử hóa, gom batch hoặc &lt;strong&gt;chưng cất&lt;/strong&gt; sang mô hình học sinh nhỏ hơn để giảm chi phí phục vụ.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Khi xác định rõ một kỹ thuật thuộc lớp nào trong bốn lớp này, việc hệ thống hóa toàn bộ chương sẽ trở nên rõ ràng hơn nhiều.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (luyện phỏng vấn):&lt;/strong&gt; Sau khi học xong bài chưng cất và bài nội tại decoder, xem thêm bài &lt;strong&gt;26-06 Luyện phỏng vấn&lt;/strong&gt; để tự kiểm tra kiến thức. Lộ trình luyện phỏng vấn toàn khóa nằm ở bài &lt;strong&gt;01-98&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;tài-liệu-tham-khảo-thêm&quot;&gt;Tài liệu tham khảo thêm&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Alisa Liu, &lt;a href=&quot;https://alisawuffles.notion.site/alisa-s-book-of-llms&quot;&gt;Alisa’s Book of LLMs&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Alisa Liu, &lt;a href=&quot;https://alisawuffles.notion.site/math-notes&quot;&gt;Math notes&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Các bài báo nền tảng được dẫn trong chương: &lt;a href=&quot;https://arxiv.org/abs/2001.08361&quot;&gt;Kaplan et al., 2020&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Hoffmann et al., 2022&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Ouyang et al., 2022&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Rafailov et al., 2023&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;Dao et al., 2022&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Leviathan et al., 2023&lt;/a&gt;. Danh sách đầy đủ hơn nằm cuối các bài &lt;strong&gt;26-03&lt;/strong&gt;, &lt;strong&gt;26-04&lt;/strong&gt; và &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Giới thiệu tổng quan về mô hình ngôn ngữ lớn, bám sát bức tranh mở đầu của chương.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=LPZh9BOjkQs&quot;&gt;Large Language Models explained briefly&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Tóm tắt ngắn gọn cấu trúc và nguyên lý LLM trước khi đi vào bài chi tiết.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=7xTGNNLPyMI&quot;&gt;Deep Dive into LLMs like ChatGPT&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Trình bày đầy đủ toàn bộ quy trình từ tiền huấn luyện, căn chỉnh đến suy luận; phù hợp xem xuyên suốt cả chương.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>25-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter25/25_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter25/25_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Nếu thập kỷ trước là cuộc đua xây những mô hình ngày càng lớn hơn lúc &lt;em&gt;huấn luyện&lt;/em&gt;, thì giai đoạn 2024–2026 mở ra một trục mở rộng hoàn toàn mới: &lt;strong&gt;cho mô hình thêm thời gian suy nghĩ và công cụ lúc suy luận&lt;/strong&gt;! Từ các mô hình suy luận tự kiểm tra từng bước (Inference-Time Scaling), các tác tử lập trình/nghiên cứu gọi công cụ qua vòng lặp phản hồi (Tool-Using Agents), đến các mô hình đa phương thức nguyên bản hiểu liền mạch văn bản, ảnh, âm thanh và video — bài cập nhật này tổng kết những hướng nghiên cứu đã chính thức bước vào sản phẩm hàng ngày.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-đã-bước-vào-thực-tế-20242026&quot;&gt;Kiến thức cần nhớ: Ba trụ cột đã bước vào thực tế (2024–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mở rộng tính toán lúc suy luận (Inference-Time / Test-Time Scaling):&lt;/strong&gt; Dùng chuỗi tư duy dài (Long CoT), lấy mẫu song song Best-of-\(N\) kết hợp bộ chấm điểm (Verifier/PRM) để đổi thêm token suy nghĩ lấy bước nhảy vượt bậc về độ chính xác toán/code.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tác tử sử dụng công cụ (Tool-Using Agents — ReAct &amp;amp; Function Calling):&lt;/strong&gt; Đóng gói LLM trong vòng lặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Suy nghĩ → Gọi công cụ (tìm kiếm, chạy Python, đọc API) → Quan sát kết quả → Tự sửa lỗi&lt;/code&gt;, chuyển AI từ “trả lời một lượt” sang “giải quyết tác vụ đa bước”.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình đa phương thức nguyên bản (Native Multimodal Models):&lt;/strong&gt; Huấn luyện chung văn bản, ảnh, âm thanh và video ngay từ tiền huấn luyện trong cùng một không gian biểu diễn thay vì ghép nối rời rạc các bộ mã hóa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỹ thuật đánh giá và kiểm soát rủi ro tác tử:&lt;/strong&gt; Thiết kế hộp cát (sandbox), giới hạn quyền hành động, và theo dõi độ tin cậy tích lũy qua nhiều bước gọi công cụ liên tiếp.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-xác-suất-thành-công-của-best-of-n-test-time-scaling-và-tích-lũy-rủi-ro-của-tác-tử-đa-bước&quot;&gt;Giải thích: Tính xác suất thành công của Best-of-\(N\) (Test-Time Scaling) và tích lũy rủi ro của Tác tử đa bước&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Sức mạnh của Best-of-\(N\) với bộ kiểm chứng chính xác (ví dụ chạy bộ unit test lập trình):&lt;/strong&gt;
Giả sử trên một bài lập trình khó, mô hình chỉ giải đúng với xác suất \(p = 0{,}20\) ở lần thử đầu tiên (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pass@1 = 20%&lt;/code&gt;). Nếu ta sinh độc lập \(N = 8\) lời giải rồi dùng trình biên dịch + bộ test chọn lời giải chạy qua:
\(P(\text{ít nhất 1 lời giải đúng}) = 1 - (1 - 0{,}20)^8 = 1 - (0{,}80)^8 \approx 1 - 0{,}1678 = 0{,}8322\;(83{,}2\%!).\)
Chỉ bằng cách tăng tính toán lúc suy luận gấp 8 lần mà &lt;strong&gt;không cần huấn luyện lại mô hình&lt;/strong&gt;, tỷ lệ giải đúng đã vọt từ \(20\%\) lên \(83{,}2\%\)!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Rủi ro tích lũy của Tác tử đa bước:&lt;/strong&gt;
Ngược lại, nếu một tác tử cần thực hiện chuỗi \(10\) bước gọi công cụ phụ thuộc nhau, và xác suất thành công mỗi bước là \(95\%\) (\(0{,}95\)), thì xác suất hoàn thành trọn vẹn cả 10 bước mà không có cơ chế tự sửa lỗi chỉ còn:
\((0{,}95)^{10} \approx 0{,}5987\;(59{,}9\%).\)
Con số này cho thấy vì sao mọi tác tử thực chiến đều bắt buộc phải có &lt;strong&gt;vòng lặp quan sát phản hồi (feedback loop) và tự phục hồi lỗi&lt;/strong&gt;!&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-những-hướng-đã-đi-vào-thực-tế--tính-toán-lúc-suy-luận-tác-tử-và-đa-phương-thức&quot;&gt;Tùy chọn: Những hướng đã đi vào thực tế — Tính toán lúc suy luận, Tác tử và Đa phương thức&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; viết lại phần tổng quan về định luật mở rộng, đa phương thức hay an toàn AI của chương. Nội dung cập nhật &lt;strong&gt;các hệ thống cụ thể đã được triển khai trong giai đoạn 2024–2026&lt;/strong&gt;, giúp kết nối các xu hướng tương lai với những công cụ có thể sử dụng ngay.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Định luật lũy thừa trong bài cốt lõi&lt;/p&gt;

\[L \propto N^{-\alpha}\]

&lt;p&gt;vẫn mô tả quá trình tiền huấn luyện. Trục mở rộng mới trong thực tế công nghiệp là &lt;strong&gt;tính toán lúc suy luận&lt;/strong&gt; (&lt;em&gt;test-time compute&lt;/em&gt;): chi thêm tài nguyên tính toán cho &lt;em&gt;mỗi truy vấn&lt;/em&gt; thay vì chỉ mở rộng lúc huấn luyện.&lt;/p&gt;

&lt;h2 id=&quot;1-mở-rộng-tính-toán-lúc-suy-luận-inference-time-scaling&quot;&gt;1. Mở rộng tính toán lúc suy luận (Inference-Time Scaling)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://openai.com/index/learning-to-reason-with-llms/&quot;&gt;OpenAI o1&lt;/a&gt; (2024) và các mô hình suy luận tiếp theo (như dòng DeepSeek-R1 năm 2025) huấn luyện mô hình tạo chuỗi suy luận dài kết hợp tìm kiếm trước khi trả lời. Kết quả thực nghiệm cho thấy sai số có thể giảm theo lượng tính toán lúc suy luận:&lt;/p&gt;

\[\text{error} \approx c \cdot C_{\mathrm{test}}^{-\gamma}\]

&lt;p&gt;bổ sung cho hướng chỉ tăng số tham số \(N\) khi tiền huấn luyện (&lt;a href=&quot;https://arxiv.org/abs/2408.03314&quot;&gt;Snell et al., 2024&lt;/a&gt;, &lt;em&gt;Scaling LLM Test-Time Compute&lt;/em&gt;). Hướng này bổ trợ cho quy luật tối ưu lúc &lt;em&gt;huấn luyện&lt;/em&gt; của Chinchilla (xem bài tùy chọn Chương 00/01).&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-cụ-thể&quot;&gt;2. Ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;tác-tử-sử-dụng-công-cụ-tool-using-agents&quot;&gt;Tác tử sử dụng công cụ (Tool-Using Agents)&lt;/h3&gt;

&lt;p&gt;Các hệ thống “tác tử” (&lt;em&gt;agent&lt;/em&gt;) trong thực tế giai đoạn 2024–2026 vận hành theo vòng lặp: mô hình ngôn ngữ → gọi công cụ (SQL, trình duyệt, thực thi mã) → quan sát kết quả và lặp lại. Hệ sinh thái công cụ phổ biến gồm Agents / Responses API của OpenAI, &lt;a href=&quot;https://github.com/langchain-ai/langgraph&quot;&gt;LangGraph&lt;/a&gt; và &lt;a href=&quot;https://github.com/huggingface/smolagents&quot;&gt;smolagents&lt;/a&gt;. Thách thức nghiên cứu chính hiện nay nằm ở độ tin cậy và kiểm soát lỗi, hơn là thiết kế một loại nơ-ron hoàn toàn mới.&lt;/p&gt;

&lt;h3 id=&quot;mô-hình-đa-phương-thức-nguyên-bản&quot;&gt;Mô hình đa phương thức nguyên bản&lt;/h3&gt;

&lt;p&gt;Các hệ thống như GPT-4V, Gemini và các mô hình thị giác–ngôn ngữ mở (LLaVA, Qwen2-VL, PaliGemma) xử lý trực tiếp văn bản, hình ảnh và âm thanh trong cùng một kiến trúc. Nếu CLIP và Flamingo trong bài cốt lõi là nền tảng nghiên cứu ban đầu, thì đây là các sản phẩm và API hoàn chỉnh phát triển từ nền tảng đó.&lt;/p&gt;

&lt;h3 id=&quot;tính-bền-vững-trở-thành-ràng-buộc-kỹ-thuật&quot;&gt;Tính bền vững trở thành ràng buộc kỹ thuật&lt;/h3&gt;

&lt;p&gt;Việc dùng mô hình 70B cho mọi yêu cầu người dùng không còn là câu chuyện tương lai mà là bài toán chi phí và năng lượng trực tiếp. Lượng tử hóa (xem bài tùy chọn Chương 23), định tuyến truy vấn đơn giản sang mô hình nhỏ và kỹ thuật gom lô (&lt;em&gt;batching&lt;/em&gt;) là những giải pháp thực tế đang được triển khai để giải quyết bài toán năng lượng.&lt;/p&gt;

&lt;h2 id=&quot;3-phần-mềm-phổ-biến&quot;&gt;3. Phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt; và &lt;a href=&quot;https://github.com/sgl-project/sglang&quot;&gt;SGLang&lt;/a&gt; — phục vụ thông lượng cao, hỗ trợ giải mã suy luận và xuất định dạng có cấu trúc.&lt;/li&gt;
  &lt;li&gt;Các bản mô hình suy luận công khai trên Hugging Face (như các phiên bản chưng cất từ DeepSeek-R1).&lt;/li&gt;
  &lt;li&gt;Bộ khung đánh giá mở: &lt;a href=&quot;https://github.com/EleutherAI/lm-evaluation-harness&quot;&gt;lm-evaluation-harness&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2408.03314&quot;&gt;Scaling LLM Test-Time Compute (Snell et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2501.12948&quot;&gt;DeepSeek-R1 (DeepSeek-AI, 2025)&lt;/a&gt; — huấn luyện năng lực suy luận quy mô lớn bằng học tăng cường (xem thêm bài tùy chọn Chương 21).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.08485&quot;&gt;LLaVA (Liu et al., 2023)&lt;/a&gt; — công thức xây dựng mô hình thị giác–ngôn ngữ mở được áp dụng rộng rãi trong giai đoạn 2024–2026.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-bài-này-bổ-sung-gì-cho-ghi-chú-cốt-lõi&quot;&gt;5. Bài này bổ sung gì cho ghi chú cốt lõi&lt;/h2&gt;

&lt;p&gt;Phần thảo luận về định luật mở rộng, NAS, học liên tục và an toàn trong bài cốt lõi vẫn giữ vai trò định hướng. Bài này cập nhật ba mảng — &lt;strong&gt;tính toán lúc suy luận, tác tử dùng công cụ và mô hình đa phương thức mở&lt;/strong&gt; — đã chuyển từ hướng nghiên cứu sang hệ thống thực tế trong giai đoạn 2024–2026.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=7xTGNNLPyMI&quot;&gt;Deep Dive into LLMs like ChatGPT&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Bài giảng chuyên sâu năm 2025 của Karpathy, bao gồm phần mở rộng tính toán lúc suy luận bổ sung trên nền tiền huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PZXN7jm9IC0&quot;&gt;Chinchilla Explained: Compute-Optimal Massive Language Models&lt;/a&gt; — Edan Meyer, tiếng Anh. Ôn lại định luật Chinchilla lúc huấn luyện để đối chiếu với trục mở rộng lúc suy luận.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=N1fbskTpwZ0&quot;&gt;MIT 6.S191 (2024): Language Models and New Frontiers&lt;/a&gt; — Alexander Amini, tiếng Anh. Tổng quan về tác tử và hệ thống đa phương thức được đề cập trong bài.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>25-98 Luyện phỏng vấn (Bayesian và bất định)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter25/25_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter25/25_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Hãy tưởng tượng bạn đưa một bức ảnh chiếc giày thể thao vào một mạng phân loại ảnh chỉ từng học 2 lớp là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chó&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt;, rồi nhìn đầu ra Softmax báo: &lt;strong&gt;99,7% là chó&lt;/strong&gt;! Tại sao mạng nơ-ron chuẩn lại “tự tin một cách mù quáng” trên dữ liệu ngoài phân phối (OOD), và làm thế nào để định lượng xem sự không chắc chắn đến từ nhiễu dữ liệu hay do mô hình thiếu kiến thức? Bài luyện phỏng vấn này giúp bạn làm chủ hoàn toàn chủ đề Học sâu Bayes và độ bất định.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-phỏng-vấn-về-học-sâu-bayes-và-độ-bất-định&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột phỏng vấn về Học sâu Bayes và Độ bất định&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân tách Aleatoric vs. Epistemic Uncertainty:&lt;/strong&gt; Aleatoric (nhiễu nội tại dữ liệu, không giảm được dù thu thêm dữ liệu cùng loại) vs. Epistemic (sự thiếu hiểu biết của mô hình ở vùng thưa dữ liệu, giảm được khi bổ sung dữ liệu).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tương đương giữa Chính quy hóa L2 và Ước lượng MAP với tiên nghiệm Gauss:&lt;/strong&gt; Chứng minh toán học \(\arg\max_w [\ln p(D\mid w) + \ln \mathcal{N}(w\mid 0, \sigma_w^2 I)]\) chính xác là tối thiểu hóa NLL cộng phạt \(\frac{\lambda}{2}\|w\|_2^2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu chuẩn xác suất (Calibration — ECE &amp;amp; Temperature Scaling):&lt;/strong&gt; Nhận diện hiện tượng &lt;em&gt;overconfidence&lt;/em&gt; của Softmax (đặc biệt trên vùng OOD với mạng ReLU) và cách dùng một tham số nhiệt độ \(T\) duy nhất trên tập validation để hiệu chuẩn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xấp xỉ suy diễn Bayes thực dụng:&lt;/strong&gt; So sánh Monte Carlo Dropout (chạy \(M\) lượt xuôi bật dropout) và Deep Ensembles (huấn luyện \(M\) mạng độc lập — chuẩn vàng thực tế về đo độ bất định).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-độ-bất-định-epistemic-bằng-deep-ensemble-và-quy-đổi-tiên-nghiệm-gauss-sang-hệ-số-l2&quot;&gt;Giải thích: Tính tay độ bất định Epistemic bằng Deep Ensemble và quy đổi tiên nghiệm Gauss sang hệ số L2&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Đo bất định qua Deep Ensemble (\(M = 3\) mạng độc lập):&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Trên một mẫu &lt;strong&gt;trong phân phối (in-distribution)&lt;/strong&gt;, 3 mạng dự đoán xác suất lớp dương là \([0{,}88,\; 0{,}90,\; 0{,}92]\):
    &lt;ul&gt;
      &lt;li&gt;Trung bình \(\bar{p} = 0{,}90\), phương sai giữa các mạng (đại diện độ bất định Epistemic) \(\text{Var} = \frac{(-0{,}02)^2 + 0 + (0{,}02)^2}{3} \approx 0{,}00027\) → các mạng đồng thuận cao, đáng tin cậy.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Trên một mẫu &lt;strong&gt;ngoài phân phối (OOD)&lt;/strong&gt;, 3 mạng dự đoán \([0{,}95,\; 0{,}15,\; 0{,}70]\):
    &lt;ul&gt;
      &lt;li&gt;Trung bình \(\bar{p} = 0{,}60\), phương sai \(\text{Var} = \frac{(0{,}35)^2 + (-0{,}45)^2 + (0{,}10)^2}{3} = \frac{0{,}335}{3} \approx 0{,}1117\) — &lt;strong&gt;cao gấp hơn 400 lần&lt;/strong&gt;, phát ngay cảnh báo từ chối dự đoán tự động!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Quy đổi tiên nghiệm Gauss sang Weight Decay L2:&lt;/strong&gt;
Với nhiễu quan sát hồi quy \(\sigma_y = 0{,}5\) và tiên nghiệm trọng số \(w \sim \mathcal{N}(0, \sigma_w^2)\) có \(\sigma_w = 2{,}0\), cực đại hóa hậu nghiệm MAP cho hàm mất mát \(\frac{1}{2\sigma_y^2}\sum (y_i - \hat{y}_i)^2 + \frac{1}{2\sigma_w^2}\|w\|_2^2\). Nhân hai vế với \(2\sigma_y^2\), hệ số phạt L2 chính xác là \(\lambda = \frac{\sigma_y^2}{\sigma_w^2} = \frac{0{,}25}{4{,}0} = 0{,}0625\)!&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-luyện-phỏng-vấn--học-sâu-bayes-và-độ-bất-định&quot;&gt;Tùy chọn: Luyện phỏng vấn — Học sâu Bayes và độ bất định&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế phần tổng quan hướng phát triển tương lai của chương. Sau khi đọc bài tổng quan đó (và phần xác suất ở Chương 00), hãy luyện tập với các câu hỏi dưới đây rồi tham khảo thêm &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) để xem đầy đủ các câu hỏi có lời giải về lập trình xác suất và học sâu Bayes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Chủ đề đọc thêm trong tài liệu PDF:&lt;/strong&gt; suy luận Bayes, phân bố tiên nghiệm (&lt;em&gt;prior&lt;/em&gt;) và hậu nghiệm (&lt;em&gt;posterior&lt;/em&gt;) ở mức khái niệm, cùng cách định lượng độ bất định trong mạng sâu. Vì khóa học không tách riêng một chương về học sâu Bayes, nội dung này được đặt trong Chương 25.&lt;/p&gt;

&lt;p&gt;Trang tổng hợp lộ trình luyện tập: &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;câu-hỏi-tự-luyện&quot;&gt;Câu hỏi tự luyện&lt;/h2&gt;

&lt;h3 id=&quot;q1-hai-loại-độ-bất-định&quot;&gt;Q1. Hai loại độ bất định&lt;/h3&gt;

&lt;p&gt;Một mô hình y khoa trả về \(p(\text{bệnh}=1\mid\mathbf{x})=0.51\). Hãy nêu một tình huống trong đó giá trị này phản ánh độ bất định &lt;em&gt;aleatoric&lt;/em&gt; và một tình huống phản ánh độ bất định &lt;em&gt;epistemic&lt;/em&gt;. Thử nghiệm nào giúp phân biệt hai trường hợp?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; &lt;em&gt;Aleatoric&lt;/em&gt; là nhiễu nội tại không mất đi ngay cả khi có vô hạn dữ liệu; &lt;em&gt;epistemic&lt;/em&gt; là sự thiếu hiểu biết của mô hình và sẽ giảm khi bổ sung thêm dữ liệu có nhãn đúng miền.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Với &lt;em&gt;aleatoric&lt;/em&gt;, bản thân ảnh đầu vào vốn mơ hồ (ví dụ bị mờ do chuyển động hoặc hai dấu hiệu bệnh chồng lấn nhau), nên việc thu thập thêm dữ liệu cùng loại không đẩy xác suất về 0 hay 1. Với &lt;em&gt;epistemic&lt;/em&gt;, mẫu đến từ máy quét hoặc bệnh viện mới mà mô hình chưa từng thấy nên bộ trọng số chưa đủ thông tin; bổ sung dữ liệu có nhãn trong miền mới sẽ làm phân bố hậu nghiệm tập trung hơn. Khi chạy nhiều lượt suy luận bằng &lt;em&gt;MC dropout&lt;/em&gt; hoặc &lt;em&gt;deep ensemble&lt;/em&gt;, các dự đoán sẽ ít biến động trong trường hợp &lt;em&gt;aleatoric&lt;/em&gt; nhưng phân tán mạnh trong trường hợp &lt;em&gt;epistemic&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;q2-chính-quy-hóa-l2-dưới-góc-nhìn-tiên-nghiệm-gauss&quot;&gt;Q2. Chính quy hóa L2 dưới góc nhìn tiên nghiệm Gauss&lt;/h3&gt;

&lt;p&gt;Hãy chứng minh rằng việc cực đại hóa hậu nghiệm \(p(\mathbf{w}\mid\mathcal{D}) \propto p(\mathcal{D}\mid\mathbf{w})\,p(\mathbf{w})\) với phân bố tiên nghiệm \(p(\mathbf{w})=\mathcal{N}(\mathbf{0},\lambda^{-1}I)\) và mô hình quan sát Gauss (sai khác hằng số) tương đương với cực tiểu hóa MSE cộng số hạng phạt \(\frac{\lambda}{2}\|\mathbf{w}\|_2^2\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Lấy \(-\log\) hai vế của phân bố hậu nghiệm; phân bố tiên nghiệm Gauss sẽ cho ra một số hạng bậc hai theo \(\mathbf{w}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Ta có \(-\log p(\mathbf{w}) = \frac{\lambda}{2}\|\mathbf{w}\|_2^2 + \mathrm{const}\). Dưới giả định hợp lý (&lt;em&gt;likelihood&lt;/em&gt;) Gauss, \(-\log p(\mathcal{D}\mid\mathbf{w})\) chính là MSE (sai khác một hệ số tỉ lệ và hằng số). Do đó, ước lượng cực đại hậu nghiệm (MAP) với tiên nghiệm Gauss tương đương hoàn toàn với hồi quy có chính quy hóa L2. Đây là cầu nối trực tiếp từ Chương 00 và Chương 09 sang ngôn ngữ Bayes. Tuy nhiên, MAP chỉ trả về một ước lượng điểm nên tự nó &lt;strong&gt;không&lt;/strong&gt; cung cấp khoảng tin cậy.&lt;/p&gt;

&lt;h3 id=&quot;q3-vì-sao-mạng-ước-lượng-điểm-thường-quá-tự-tin&quot;&gt;Q3. Vì sao mạng ước lượng điểm thường quá tự tin?&lt;/h3&gt;

&lt;p&gt;Một mạng dùng hàm softmax được huấn luyện bằng cross-entropy trên tập dữ liệu sạch nhưng lại gán xác suất \(0.99\) cho một lớp sai trên đầu vào ngoài phân bố (OOD). Dưới góc nhìn Bayes, quy trình huấn luyện đã bỏ qua yếu tố nào?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Huấn luyện chuẩn chỉ tìm một bộ trọng số \(\mathbf{w}_{\mathrm{MAP}}\) (hoặc một điểm nghiệm SGD) rồi dùng \(p(y\mid\mathbf{x},\mathbf{w}_{\mathrm{MAP}})\) thay cho \(p(y\mid\mathbf{x},\mathcal{D})\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Phân bố dự đoán Bayes đầy đủ phải lấy tích phân \(p(y\mid\mathbf{x},\mathbf{w})\) theo phân bố hậu nghiệm \(p(\mathbf{w}\mid\mathcal{D})\). Việc chỉ giữ lại một điểm \(\mathbf{w}\) duy nhất bỏ qua sự bất đồng giữa nhiều bộ trọng số khác nhau cùng khớp tốt tập huấn luyện. Trên dữ liệu OOD, mức bất đồng này thường lớn, nên trung bình hỗn hợp sẽ phẳng hơn nhiều so với đầu ra softmax quá nhọn của một mạng đơn lẻ. Lưu ý rằng &lt;em&gt;temperature scaling&lt;/em&gt; có thể cải thiện hiệu chỉnh xác suất &lt;em&gt;trong miền&lt;/em&gt;, nhưng không khắc phục một cách hệ thống sự quá tự tin trên dữ liệu OOD.&lt;/p&gt;

&lt;h3 id=&quot;q4-mc-dropout-như-phép-xấp-xỉ-hậu-nghiệm-chi-phí-thấp&quot;&gt;Q4. MC Dropout như phép xấp xỉ hậu nghiệm chi phí thấp&lt;/h3&gt;

&lt;p&gt;Giả sử bạn giữ bật &lt;em&gt;dropout&lt;/em&gt; lúc kiểm thử, chạy cùng một mạng \(T=20\) lần và lấy trung bình các vectơ softmax. Cách làm này xấp xỉ không chính thức đối tượng Bayes nào, và có những hạn chế gì?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Mỗi mặt nạ &lt;em&gt;dropout&lt;/em&gt; tạo ra một hàm dự đoán khác nhau; trung bình của chúng tạo thành một phân bố hỗn hợp.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Về mặt trực giác, kết quả là phân bố dự đoán hỗn hợp \(\frac1T\sum_t p(y\mid\mathbf{x},\mathbf{w}\odot m_t)\), đôi khi được diễn giải như một phép suy luận biến phân trên mặt nạ &lt;em&gt;dropout&lt;/em&gt;. Tuy nhiên, phương pháp này &lt;strong&gt;không&lt;/strong&gt; đảm bảo khớp chính xác với phân bố hậu nghiệm thật và cũng không miễn phí vì tốn \(T\) lượt lan truyền xuôi khi suy luận. Một phương án cạnh tranh phổ biến khác là &lt;em&gt;deep ensemble&lt;/em&gt; (huấn luyện độc lập nhiều mạng khác nhau).&lt;/p&gt;

&lt;h3 id=&quot;q5-lựa-chọn-phân-bố-tiên-nghiệm-hợp-lý-cho-hệ-số-chặn&quot;&gt;Q5. Lựa chọn phân bố tiên nghiệm hợp lý cho hệ số chặn&lt;/h3&gt;

&lt;p&gt;Khi cần đặt phân bố tiên nghiệm cho tham số &lt;em&gt;bias&lt;/em&gt; trong một mô hình hồi quy logistic đã xác định đúng dạng (Chương 03), vì sao \(\mathcal{N}(0,10^2)\) thường hợp lý hơn một phân bố điểm tập trung tại \(0\), và khi nào thì phương sai quá lớn lại gây bất lợi?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Phân bố Dirac tại 0 hàm ý bạn khẳng định chắc chắn hệ số chặn phải bằng đúng 0.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Tiên nghiệm Gauss rộng thể hiện giả định “chưa biết chính xác hệ số chặn nhưng giá trị của nó nằm trong khoảng hợp lý”, thay vì ép cứng biên quyết định đi qua một giá trị log-odds cố định khi đặc trưng bằng 0. Tuy nhiên, phương sai quá lớn trở nên bất lợi khi các đặc trưng đầu vào chưa được chuẩn hóa đơn vị, khiến mức độ ảnh hưởng của tiên nghiệm phụ thuộc tùy ý vào thang đo. Các chủ đề sâu hơn về tiên nghiệm yếu thông tin (&lt;em&gt;weakly informative prior&lt;/em&gt;) và mô hình phân cấp được trình bày chi tiết trong sách tham khảo; bài học cốt lõi ở đây là ngay cả việc “dùng thiết lập mặc định” cũng ngầm tương ứng với một lựa chọn tiên nghiệm.&lt;/p&gt;

&lt;h2 id=&quot;ghi-công&quot;&gt;Ghi công&lt;/h2&gt;

&lt;p&gt;Kashani, S. và Ivry, A., &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Có thể tải bản PDF từ arXiv để xem đầy đủ bộ câu hỏi và lời giải; các câu hỏi trên là phần tự luyện biên soạn riêng cho khóa học, không sao chép nguyên văn từ sách.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=j4yxsEQqPMI&quot;&gt;MaDL - Bayesian Decision Theory&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Trình bày lý thuyết quyết định Bayes — nền tảng trực tiếp cho bộ câu hỏi luyện tập này.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Minh họa trực quan định lý Bayes, xuất phát điểm của các câu hỏi trên.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vPvnpC0PNVQ&quot;&gt;MaDL - Kullback-Leibler Divergence&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Giải thích phân kỳ KL, công cụ thường dùng khi so sánh các phân bố bất định.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>25-01 Hướng Phát triển Tương lai của Học sâu</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter25/25_01_Future_Directions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter25/25_01_Future_Directions</id>
   <content type="html">&lt;p&gt;Một trong những biểu đồ ấn tượng nhất của khoa học máy tính thế kỷ 21 là đường thẳng tắp trên trục log–log của &lt;strong&gt;Scaling Laws&lt;/strong&gt;: trải dài qua hơn 6 bậc độ lớn về sức mạnh tính toán, hàm mất mát của mô hình ngôn ngữ giảm đều đặn như một định luật vật lý! Bài học này đi sâu vào toán học của &lt;strong&gt;Scaling Laws&lt;/strong&gt;, &lt;strong&gt;Few-Shot / Meta-Learning (MAML)&lt;/strong&gt;, &lt;strong&gt;Học liên tục chống quên thảm họa&lt;/strong&gt; và các câu hỏi mở về hiệu quả mẫu, suy luận nhân quả và an toàn AI.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-khung-lý-thuyết-các-hướng-nghiên-cứu-biên-giới-của-học-sâu&quot;&gt;Kiến thức cần nhớ: Khung lý thuyết các hướng nghiên cứu biên giới của Học sâu&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Định luật mở rộng dạng hàm lũy thừa (Chinchilla):&lt;/strong&gt; \(L(N, D) = E + \frac{A}{N^\alpha} + \frac{B}{D^\beta}\), trong đó \(E\) là entropy bất khả giảm của ngôn ngữ tự nhiên còn hai số hạng sau phản ánh sai số do thiếu tham số và thiếu dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Meta-Learning và Few-Shot Learning (MAML, Prototypical Networks):&lt;/strong&gt; Học cách khởi tạo tham số \(\theta^*\) sao cho chỉ sau 1–5 bước hạ gradient trên vài mẫu mới, mô hình đã thích nghi ngay với tác vụ chưa từng thấy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chống quên thảm họa trong Học liên tục (Continual Learning — EWC):&lt;/strong&gt; Dùng ma trận thông tin Fisher \(F_i\) để phạt nặng việc làm lệch các trọng số quan trọng đối với tác vụ cũ khi học tác vụ mới.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;AI tin cậy, nhân quả và bền vững năng lượng:&lt;/strong&gt; Kết hợp suy luận nhân quả (do-calculus), tiết kiệm năng lượng phần cứng và căn chỉnh an toàn cho các hệ thống tự chủ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-vòng-trong-inner-loop-của-maml-và-phạt-fisher-trong-ewc&quot;&gt;Giải thích: Tính tay một bước vòng trong (Inner Loop) của MAML và phạt Fisher trong EWC&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Một bước thích nghi nhanh của MAML:&lt;/strong&gt; Giả sử siêu tham số khởi tạo là \(\theta = 1{,}0\), tốc độ học vòng trong \(\alpha = 0{,}1\), và trên 5 mẫu hỗ trợ của tác vụ mới \(\mathcal{T}_i\), đạo hàm hàm loss là \(\nabla_\theta \mathcal{L}_{\mathcal{T}_i}(1{,}0) = -3{,}0\).&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tham số thích nghi chỉ sau 1 bước: \(\theta_i&apos; = \theta - \alpha \nabla_\theta \mathcal{L}_{\mathcal{T}_i}(\theta) = 1{,}0 - 0{,}1(-3{,}0) = 1{,}3\).&lt;/li&gt;
  &lt;li&gt;Sau đó MAML tính loss trên tập truy vấn của \(\mathcal{T}_i\) tại \(\theta_i&apos; = 1{,}3\) và lấy đạo hàm &lt;em&gt;xuyên qua bước cập nhật đó&lt;/em&gt; về lại \(\theta\) để tối ưu hóa chính khả năng học nhanh!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Hàm phạt EWC (Elastic Weight Consolidation):&lt;/strong&gt; Với hai trọng số đã học xong tác vụ A tại \(\theta^* = (2{,}0,\; 0{,}5)\) có độ quan trọng Fisher \(F_1 = 10{,}0\) (rất quan trọng), \(F_2 = 0{,}2\) (ít quan trọng), hệ số \(\lambda = 1{,}0\). Nếu tác vụ B kéo cả hai lệch đi \(0{,}5\) đơn vị (tới \((2{,}5,\; 1{,}0)\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mức phạt cho trọng số 1: \(\frac{1}{2} \lambda F_1 (0{,}5)^2 = 0{,}5(10{,}0)(0{,}25) = 1{,}25\).&lt;/li&gt;
  &lt;li&gt;Mức phạt cho trọng số 2: \(\frac{1}{2} \lambda F_2 (0{,}5)^2 = 0{,}5(0{,}2)(0{,}25) = 0{,}025\) (nhỏ hơn &lt;strong&gt;50 lần&lt;/strong&gt;!). EWC tự động “khóa cứng” trọng số 1 để bảo vệ ký ức tác vụ A, đồng thời để trống trọng số 2 cho tác vụ B.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;tương-lai-của-học-sâu-xu-hướng-mới-nổi-và-thách-thức-còn-mở&quot;&gt;Tương lai của Học sâu: Xu hướng Mới nổi và Thách thức Còn mở&lt;/h1&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Học sâu đã đạt nhiều bước tiến lớn trong thập kỷ qua, nhưng nhiều câu hỏi nền tảng vẫn đang mở. Dù các hệ thống hiện nay hoạt động hiệu quả trên những tác vụ cụ thể khi có đủ dữ liệu và tài nguyên tính toán, giới nghiên cứu vẫn tiếp tục giải quyết các giới hạn về hiệu quả mẫu, khả năng suy luận, độ tin cậy và chi phí vận hành. Nắm được các hướng đi mới và thách thức còn tồn tại giúp người thực hành đánh giá thực tế hơn quỹ đạo phát triển của lĩnh vực.&lt;/p&gt;

&lt;p&gt;Giả thuyết mở rộng quy mô (&lt;em&gt;scaling hypothesis&lt;/em&gt;) là động lực chính của nhiều tiến bộ gần đây: tăng đồng thời kích thước mô hình, lượng dữ liệu và tài nguyên tính toán giúp cải thiện hiệu năng một cách đều đặn. Quy mô 175 tỷ tham số của GPT-3 lớn hơn 100 lần so với 1.5 tỷ của GPT-2, kéo theo các năng lực mới như học từ vài ví dụ (&lt;em&gt;few-shot learning&lt;/em&gt;). Tuy nhiên, hướng mở rộng này đặt ra nhiều câu hỏi quan trọng về giới hạn nguồn dữ liệu, chi phí năng lượng cũng như hạ tầng huấn luyện và phục vụ.&lt;/p&gt;

&lt;p&gt;Học đa phương thức (&lt;em&gt;multimodal learning&lt;/em&gt;) — xử lý đồng thời nhiều dạng dữ liệu như văn bản, hình ảnh và âm thanh — là một hướng trọng tâm vì tri giác con người vốn đa phương thức. Các mô hình như CLIP (học từ cặp ảnh–văn bản) và GPT-4 (xử lý cả văn bản và ảnh) cho thấy tiền huấn luyện đa phương thức hỗ trợ hiệu quả nhiều tác vụ liên phương thức như mô tả ảnh, hỏi đáp thị giác và sinh ảnh từ văn bản.&lt;/p&gt;

&lt;p&gt;Hiệu quả và tính bền vững trở thành ưu tiên lớn khi quy mô mô hình tăng mạnh. Chi phí tính toán và tiêu thụ năng lượng để huấn luyện các mô hình lớn như GPT-3 rất cao, thúc đẩy nghiên cứu về kiến trúc gọn nhẹ, thuật toán tiết kiệm dữ liệu, chưng cất tri thức và phần cứng chuyên dụng để mở rộng khả năng tiếp cận ra ngoài các tổ chức có nguồn lực tính toán khổng lồ.&lt;/p&gt;

&lt;p&gt;An toàn, độ vững chắc và căn chỉnh (&lt;em&gt;alignment&lt;/em&gt;) là những thách thức đặc biệt quan trọng. Các mô hình hiện tại vẫn có thể thất bại khó lường trước dữ liệu ngoài phân bố, khuếch đại thiên kiến xã hội từ dữ liệu huấn luyện hoặc tối ưu mục tiêu chưa khớp hoàn toàn với ý định của con người. Khi AI được triển khai rộng rãi hơn trong các lĩnh vực trọng yếu, nghiên cứu về độ vững chắc đối kháng, công bằng, khả năng diễn giải và căn chỉnh giá trị trở thành yêu cầu bắt buộc.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;h3 id=&quot;định-luật-mở-rộng-scaling-laws&quot;&gt;Định luật mở rộng (Scaling Laws)&lt;/h3&gt;

&lt;p&gt;Các quan sát thực nghiệm cho thấy mối quan hệ dạng hàm lũy thừa giữa hàm mất mát và quy mô:&lt;/p&gt;

\[L \propto N^{-\alpha}\]

&lt;p&gt;trong đó \(L\) là mất mát, \(N\) là số tham số (hoặc lượng dữ liệu, hoặc ngân sách tính toán) và \(\alpha\) là hằng số (thường trong khoảng 0.05–0.1). Quan hệ này thể hiện lợi tức giảm dần: để giảm mất mát theo cấp số cộng, cần tăng quy mô theo cấp số nhân. Dù vậy, tính ổn định của quy luật trên nhiều kiến trúc và miền dữ liệu cho thấy quy luật nhất quán trong quá trình học của mạng nơ-ron.&lt;/p&gt;

&lt;p&gt;Đường biên tối ưu theo tính toán (&lt;em&gt;compute-optimal frontier&lt;/em&gt;) cân bằng giữa kích thước mô hình và lượng dữ liệu huấn luyện:&lt;/p&gt;

\[N_{\text{optimal}} \propto C^{0.5}, \quad D_{\text{optimal}} \propto C^{0.5}\]

&lt;p&gt;trong đó \(C\) là ngân sách tính toán, \(N\) là số tham số và \(D\) là số token huấn luyện. Kết quả này chỉ ra rằng khi tăng ngân sách tính toán, cần tăng cân đối cả kích thước mô hình lẫn lượng dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;học-từ-vài-ví-dụ-few-shot-learning&quot;&gt;Học từ vài ví dụ (Few-Shot Learning)&lt;/h3&gt;

&lt;p&gt;Học meta (&lt;em&gt;meta-learning&lt;/em&gt;) hình thức hóa bài toán học từ rất ít ví dụ. Với một phân bố tác vụ \(p(\mathcal{T})\), thuật toán học tham số khởi tạo \(\theta_0\) sao cho có thể thích nghi nhanh với tác vụ mới:&lt;/p&gt;

\[\theta_0 = \arg\min_\theta \mathbb{E}_{\mathcal{T} \sim p(\mathcal{T})}\left[\mathcal{L}_\mathcal{T}(\theta - \alpha \nabla_\theta \mathcal{L}_\mathcal{T}(\theta))\right]\]

&lt;p&gt;MAML tối ưu \(\theta_0\) để chỉ cần một vài bước hạ gradient trên tập dữ liệu nhỏ của tác vụ mới đã đạt hiệu năng tốt.&lt;/p&gt;

&lt;h3 id=&quot;học-liên-tục-continual-learning&quot;&gt;Học liên tục (Continual Learning)&lt;/h3&gt;

&lt;p&gt;Học thêm tác vụ mới mà không quên tác vụ cũ đòi hỏi cân bằng giữa tính dẻo (&lt;em&gt;plasticity&lt;/em&gt; — tiếp thu kiến thức mới) và tính ổn định (&lt;em&gt;stability&lt;/em&gt; — giữ kiến thức cũ). Phương pháp &lt;em&gt;Elastic Weight Consolidation&lt;/em&gt; (EWC) phạt sự thay đổi của các tham số quan trọng đối với tác vụ trước đó:&lt;/p&gt;

\[\mathcal{L}_{\text{EWC}} = \mathcal{L}_{\text{new}} + \sum_i \frac{\lambda}{2} F_i (\theta_i - \theta_i^*)^2\]

&lt;p&gt;trong đó \(F_i\) là đường chéo ma trận thông tin Fisher (phản ánh độ nhạy của hàm mất mát tác vụ cũ theo tham số \(i\)) và \(\theta_i^*\) là giá trị tham số sau khi học tác vụ cũ.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và trực giác&lt;/h2&gt;

&lt;p&gt;Xét bước chuyển qua các thế hệ GPT-2 (1.5 tỷ tham số), GPT-3 (175 tỷ tham số) và GPT-4 (quy mô không công bố chính thức, thường được ước đoán khoảng 1.7 nghìn tỷ tham số):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;GPT-2&lt;/strong&gt;: sinh văn bản mạch lạc, hoàn thành đoạn văn cơ bản.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GPT-3&lt;/strong&gt;: học &lt;em&gt;few-shot&lt;/em&gt;, suy luận đơn giản và hỗ trợ lập trình cơ bản.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GPT-4&lt;/strong&gt;: suy luận phức tạp hơn, xử lý đa phương thức và lập trình nâng cao.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sự thay đổi không chỉ dừng ở cải thiện định lượng mà còn xuất hiện các năng lực mới theo ngưỡng quy mô (&lt;em&gt;emergent abilities&lt;/em&gt;), chẳng hạn khả năng làm theo chỉ dẫn mới mà không cần huấn luyện lại riêng cho từng tác vụ.&lt;/p&gt;

&lt;p&gt;Tương tự, các mô hình đa phương thức như DALL-E có thể sinh ảnh từ mô tả văn bản như “một phi hành gia cưỡi ngựa theo phong cách chân thực” nhờ kết hợp hiểu ngôn ngữ tự nhiên với biểu diễn đặc trưng thị giác.&lt;/p&gt;

&lt;h3 id=&quot;hệ-thống-gợi-ý-tối-ưu-đa-mục-tiêu-và-trách-nhiệm&quot;&gt;Hệ thống gợi ý: Tối ưu đa mục tiêu và trách nhiệm&lt;/h3&gt;

&lt;p&gt;Các nền tảng video ngắn cho thấy bài toán “căn chỉnh” không chỉ giới hạn ở chatbot: mỗi lần làm mới bảng tin là một bài toán &lt;strong&gt;tối ưu đa mục tiêu&lt;/strong&gt; (&lt;em&gt;multi-objective optimization&lt;/em&gt;) phải cân bằng đồng thời nhiều chỉ số như thời gian xem, mức độ tương tác, đa dạng chủ đề, an toàn nội dung và doanh thu quảng cáo — không tồn tại một hàm mất mát đơn lẻ nào phản ánh đủ mọi tiêu chí.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter25/recsys_multi_objective.jpg&quot; alt=&quot;Cân bằng đa mục tiêu&quot; /&gt;
&lt;em&gt;Hình: Hệ thống xếp hạng bảng tin cần cân bằng đồng thời nhiều mục tiêu thay vì chỉ tối ưu một chỉ số duy nhất. (Minh họa từ video giải thích recommendation system)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Các thách thức thực tế đi kèm gồm:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bong bóng lọc / buồng vang (&lt;em&gt;filter bubble / echo chamber&lt;/em&gt;)&lt;/strong&gt;: tối ưu hóa thuần túy theo mức độ tương tác dễ thu hẹp phạm vi nội dung người dùng tiếp cận.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vòng lặp phản hồi (&lt;em&gt;feedback loop&lt;/em&gt;)&lt;/strong&gt;: mô hình khuếch đại hành vi cũ, khiến dữ liệu thu thập về sau ngày càng thiên lệch.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xung đột giá trị&lt;/strong&gt;: mục tiêu kéo dài thời gian sử dụng có thể mâu thuẫn với sự đa dạng thông tin và trải nghiệm lành mạnh của người dùng.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Do đó, các hướng nghiên cứu như công bằng (&lt;em&gt;fairness&lt;/em&gt;), ràng buộc đa dạng, hệ gợi ý nhân quả (&lt;em&gt;causal recsys&lt;/em&gt;) và con người trong vòng lặp (&lt;em&gt;human-in-the-loop&lt;/em&gt;) nằm tại giao điểm giữa mở rộng quy mô, căn chỉnh và kỹ thuật hệ thống học máy thực tế.&lt;/p&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Few-shot learning example
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;FewShotLearner&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Meta-learning for few-shot classification.
    
    Learns from episodes: each episode has support set (few examples)
    and query set (test examples). Model learns to adapt quickly
    to new classes from few examples.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Feature extractor
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Classifier (dynamically created for each episode)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Placeholder
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;adapt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;support_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;support_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_steps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Adapt to new task from support set.
        
        Creates and trains task-specific classifier on few examples.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Extract features from support set
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;support_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;support_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Create and train task-specific classifier
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;support_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;task_classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;support_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;task_classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Quick adaptation
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_steps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;task_classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;support_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;support_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;task_classifier&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Few-Shot Learning: Rapid Adaptation to New Tasks&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Meta-learning enables learning from few examples (5-10 per class)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;by learning how to learn quickly across many related tasks.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This is crucial for data-scarce domains!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Tính toán mô phỏng thần kinh (&lt;em&gt;neuromorphic computing&lt;/em&gt;) và mạng nơ-ron xung (&lt;em&gt;spiking neural networks&lt;/em&gt;) xử lý các xung sự kiện rời rạc thay vì giá trị liên tục, hướng tới mức tiêu thụ năng lượng thấp hơn và gần với cơ chế sinh học hơn. Song song đó, đồng thiết kế giữa thuật toán và phần cứng chuyên dụng (TPU, chip neuromorphic) tiếp tục là hướng tối ưu hóa quan trọng.&lt;/p&gt;

&lt;p&gt;Học máy lượng tử (&lt;em&gt;quantum machine learning&lt;/em&gt;) nghiên cứu khả năng tận dụng máy tính lượng tử để tăng tốc một số phép toán tuyến tính và tối ưu hóa; hiện chủ yếu ở giai đoạn lý thuyết và thử nghiệm quy mô nhỏ.&lt;/p&gt;

&lt;p&gt;Tìm kiếm kiến trúc nơ-ron (NAS) tự động hóa quá trình thiết kế mạng, góp phần tạo ra các họ kiến trúc hiệu quả như EfficientNet.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;“Attention is All You Need” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Kiến trúc Transformer trở thành nền tảng cho BERT, GPT và hầu hết mô hình ngôn ngữ lớn hiện đại.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2103.00020&quot;&gt;“CLIP: Learning Transferable Visual Models From Natural Language Supervision” (2021)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Alec Radford, Jong Wook Kim, et al. (OpenAI)&lt;br /&gt;
CLIP học biểu diễn liên phương thức ảnh–văn bản từ 400 triệu cặp dữ liệu, cho phép phân loại ảnh &lt;em&gt;zero-shot&lt;/em&gt; thông qua câu lệnh văn bản.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;“An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale” (2021)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Vision Transformer (ViT) chứng minh kiến trúc dựa trên &lt;em&gt;attention&lt;/em&gt; có thể đạt hiệu năng ngang bằng hoặc vượt CNN trong thị giác máy tính ở quy mô lớn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;“Training Compute-Optimal Large Language Models” (2022)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Jordan Hoffmann, Sebastian Borgeaud, et al. (DeepMind)&lt;br /&gt;
Bài báo Chinchilla chỉ ra rằng nhiều LLM trước đó bị thiếu dữ liệu huấn luyện so với số tham số, đồng thời đề xuất tỷ lệ mở rộng cân bằng giữa kích thước mô hình và lượng dữ liệu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.12712&quot;&gt;“Sparks of Artificial General Intelligence: Early experiments with GPT-4” (2023)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Microsoft Research&lt;br /&gt;
Khảo sát năng lực của GPT-4 trên nhiều nhóm bài toán đa dạng, ghi nhận sự mở rộng rõ rệt về khả năng tổng quát hóa cũng như những hạn chế còn tồn tại.&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;Bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;p&gt;Một sai lệch nhận thức phổ biến là đánh giá quá cao tiến độ ngắn hạn nhưng lại đánh giá thấp tác động dài hạn. Các hệ thống hiện nay vẫn còn những hạn chế rõ rệt về lẽ thường, suy luận vững chắc và hiệu quả dữ liệu — những vấn đề khó giải quyết triệt để trong thời gian ngắn; trong khi đó, tiến bộ tích lũy qua giai đoạn 10–20 năm có thể tạo ra thay đổi lớn hơn nhiều so với dự đoán tuyến tính.&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;p&gt;Các hướng phát triển chính của học sâu bao gồm mở rộng quy mô hợp lý theo định luật &lt;em&gt;scaling&lt;/em&gt;, xây dựng hệ thống đa phương thức tích hợp văn bản–thị giác–âm thanh, nâng cao hiệu quả tính toán và năng lượng, cải thiện khả năng học từ ít dữ liệu (&lt;em&gt;few-shot / meta-learning&lt;/em&gt;), học liên tục không quên, và tăng cường độ vững chắc, công bằng cùng căn chỉnh giá trị. Những bài toán mở cốt lõi vẫn xoay quanh hiệu quả mẫu, suy luận đáng tin cậy, khả năng diễn giải và độ bền trước dịch chuyển phân bố dữ liệu.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1444915507374636&quot;&gt;Thuật toán gợi ý (TikTok-style recommendation)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PZXN7jm9IC0&quot;&gt;Chinchilla Explained: Compute-Optimal Massive Language Models&lt;/a&gt; — Edan Meyer, tiếng Anh. Giải thích định luật mở rộng tối ưu theo tính toán tương ứng với phần hàm lũy thừa trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=N1fbskTpwZ0&quot;&gt;MIT 6.S191 (2024): Language Models and New Frontiers&lt;/a&gt; — Alexander Amini, tiếng Anh. Trình bày mô hình đa phương thức và các bài toán nghiên cứu mở.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=LPZh9BOjkQs&quot;&gt;Large Language Models explained briefly&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Minh họa trực quan ngắn gọn về các mô hình ngôn ngữ lớn được nhắc tới trong phần &lt;em&gt;scaling&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>25 Chủ đề Nâng cao và Hướng Phát triển Tương lai</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter25/25_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter25/25_00_Introduction</id>
   <content type="html">&lt;p&gt;Nếu quay ngược về năm 2018, ít ai tin rằng việc đơn giản tăng kích thước mô hình, dữ liệu và tính toán theo quy luật lũy thừa lại có thể mở khóa năng lực viết mã, giải toán và suy luận đa bước. Chương &lt;strong&gt;Chủ đề Nâng cao và Hướng Phát triển Tương lai&lt;/strong&gt; đưa bạn đứng lên “đài quan sát” của ngành AI: nhìn rõ các &lt;strong&gt;Định luật Mở rộng (Scaling Laws)&lt;/strong&gt;, &lt;strong&gt;Học sâu Bayes &amp;amp; độ bất định&lt;/strong&gt;, &lt;strong&gt;tính toán lúc suy luận (Inference-Time Scaling)&lt;/strong&gt;, &lt;strong&gt;Tác tử (Agents)&lt;/strong&gt; và &lt;strong&gt;mô hình đa phương thức nguyên bản&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-định-hình-biên-giới-của-học-sâu-hiện-đại&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột định hình biên giới của Học sâu hiện đại&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Định luật mở rộng (Kaplan &amp;amp; Chinchilla Scaling Laws):&lt;/strong&gt; Mô hình hóa hàm mất mát theo quy luật lũy thừa của tham số \(N\), dữ liệu \(D\) và ngân sách tính toán \(C\), biến việc thiết kế mô hình lớn thành khoa học dự báo định lượng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học sâu Bayes và định lượng độ bất định:&lt;/strong&gt; Phân tách độ bất định dữ liệu (&lt;em&gt;aleatoric&lt;/em&gt;) và độ bất định mô hình (&lt;em&gt;epistemic&lt;/em&gt;) để hệ thống biết lúc nào cần nói “tôi không chắc chắn”.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mở rộng tính toán lúc suy luận (Test-Time / Inference-Time Scaling):&lt;/strong&gt; Thay vì chỉ đổ ngân sách vào tiền huấn luyện, cấp thêm thời gian “suy nghĩ” (chuỗi tư duy, tìm kiếm cây, tự kiểm chứng) để giải các bài toán khó.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tác tử sử dụng công cụ và Đa phương thức nguyên bản:&lt;/strong&gt; Kết hợp mô hình nền với trình biên dịch, trình duyệt, bộ nhớ ngoài và khả năng xử lý đồng nhất văn bản–ảnh–âm thanh–video trong cùng một kiến trúc.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-ước-lượng-ngân-sách-tính-toán-tiền-huấn-luyện-c-approx-6-n-d-theo-quy-tắc-chinchilla&quot;&gt;Giải thích: Ước lượng ngân sách tính toán tiền huấn luyện \(C \approx 6 N D\) theo quy tắc Chinchilla&lt;/h3&gt;

&lt;p&gt;Với một Transformer dày đặc (dense) có \(N\) tham số huấn luyện trên \(D\) token, tổng số phép toán dấu phẩy động (FLOPs) xấp xỉ \(C \approx 6 N D\) (2 FLOPs/tham số/token cho lượt xuôi + 4 FLOPs cho lượt ngược).&lt;/p&gt;

&lt;p&gt;Theo quy luật tối ưu tính toán &lt;strong&gt;Chinchilla&lt;/strong&gt;, tỷ lệ vàng là \(D \approx 20 N\) (20 token cho mỗi tham số):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình \(N = 10\text{ tỷ}\) (\(10^{10}\)) tham số:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Số token tối ưu Chinchilla: \(D = 20 \times 10^{10} = 200\text{ tỷ token}\).&lt;/li&gt;
      &lt;li&gt;Tổng ngân sách tính toán: \(C = 6 \times 10^{10} \times 2 \times 10^{11} = 1{,}2 \times 10^{22}\text{ FLOPs}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuyển dịch thực tế 2024–2026 (Over-training cho suy luận rẻ):&lt;/strong&gt; Các mô hình nhỏ như Llama-3 8B được huấn luyện trên tới \(15{,}000\text{ tỷ}\) token (\(D \approx 1{,}875 N\) — gấp gần &lt;strong&gt;94 lần&lt;/strong&gt; tỷ lệ Chinchilla!) để đổi lấy chi phí phục vụ suy luận cực rẻ về sau.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chương này tổng quan các hướng nghiên cứu mới và những bài toán mở của học sâu: mô hình đa phương thức (&lt;em&gt;multimodal&lt;/em&gt; — CLIP, Flamingo), tìm kiếm kiến trúc nơ-ron (&lt;em&gt;neural architecture search&lt;/em&gt;), học meta (&lt;em&gt;meta-learning&lt;/em&gt; — học cách học), học liên tục (&lt;em&gt;continual learning&lt;/em&gt;), học liên bang (&lt;em&gt;federated learning&lt;/em&gt;), tính toán mô phỏng thần kinh (&lt;em&gt;neuromorphic computing&lt;/em&gt;), học máy lượng tử, cùng các vấn đề về an toàn AI, công bằng và tính bền vững.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần tổng quan hướng phát triển tương lai, xem thêm bài &lt;strong&gt;25-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về tính toán lúc suy luận (&lt;em&gt;test-time compute&lt;/em&gt;), tác tử (&lt;em&gt;agent&lt;/em&gt;) và các mô hình thị giác–ngôn ngữ mở đã triển khai thực tế.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (luyện phỏng vấn):&lt;/strong&gt; Xem thêm bài &lt;strong&gt;25-98 Luyện phỏng vấn&lt;/strong&gt; với các câu hỏi tự soạn về học sâu Bayes và độ bất định; tham khảo thêm tài liệu &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) để xem ngân hàng câu hỏi có lời giải.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Liên kết sang chương LLM chuyên biệt:&lt;/strong&gt; Tiền huấn luyện, &lt;em&gt;prompting&lt;/em&gt;, căn chỉnh, phục vụ và chưng cất mô hình ngôn ngữ lớn được trình bày riêng tại &lt;strong&gt;Chương 26&lt;/strong&gt;. Phân tích tối ưu tài nguyên tính toán kiểu Chinchilla (Kaplan / Hoffmann) nằm ở bài &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=N1fbskTpwZ0&quot;&gt;MIT 6.S191 (2024): Language Models and New Frontiers&lt;/a&gt; — Alexander Amini, tiếng Anh. Bài giảng năm 2024 của MIT tổng quan các hướng biên giới của học sâu tương ứng với chương này.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PZXN7jm9IC0&quot;&gt;Chinchilla Explained: Compute-Optimal Massive Language Models&lt;/a&gt; — Edan Meyer, tiếng Anh. Giải thích định luật mở rộng tối ưu theo tính toán Chinchilla được trình bày trong bài sau.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Bức tranh cụ thể về các hệ thống mô hình ngôn ngữ lớn phát triển từ những hướng nghiên cứu trên.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>24-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter24/24_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter24/24_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Khi cố nhìn trực tiếp vào một nơ-ron đơn lẻ bên trong một Mô hình Ngôn ngữ Lớn, các nhà nghiên cứu phát hiện một điều gây choáng: &lt;em&gt;cùng một nơ-ron&lt;/em&gt; vừa sáng lên khi thấy mã nguồn Python, vừa sáng lên khi thấy trích dẫn Kinh Thánh, lại vừa sáng lên khi thấy công thức hóa học! Hiện tượng &lt;strong&gt;Chồng chập (Superposition)&lt;/strong&gt; này khiến việc đọc từng nơ-ron thất bại — và thúc đẩy cuộc cách mạng &lt;strong&gt;Diễn giải Cơ chế (Mechanistic Interpretability)&lt;/strong&gt; giai đoạn 2023–2026 với &lt;strong&gt;Sparse Autoencoder (SAE)&lt;/strong&gt; và &lt;strong&gt;Circuit Analysis&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-đột-phá-của-diễn-giải-mô-hình-hiện-đại-20222026&quot;&gt;Kiến thức cần nhớ: Ba đột phá của Diễn giải Mô hình hiện đại (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Giả thuyết chồng chập (Superposition) và nơ-ron đa nghĩa (Polysemanticity):&lt;/strong&gt; Mạng nơ-ron nhồi nhét \(M \gg d\) khái niệm thưa vào một không gian kích hoạt \(d\) chiều dưới dạng các hướng gần trực giao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sparse Autoencoder (SAE) tách đặc trưng đơn nghĩa:&lt;/strong&gt; Mở rộng vector kích hoạt \(\mathbf{h} \in \mathbb{R}^d\) sang không gian từ điển rộng hơn nhiều \(\mathbf{f} \in \mathbb{R}^M\) (\(M = 8d\text{–}64d\)) với phạt thưa \(L_1\) hoặc TopK để tách riêng từng khái niệm sạch (ví dụ đặc trưng “Cầu Cổng Vàng”, “lỗi bảo mật SQL”).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân tích mạch (Circuit Analysis) và Vá kích hoạt (Activation Patching):&lt;/strong&gt; Thay thế kích hoạt ở từng đầu chú ý/tầng MLP giữa câu sạch và câu nhiễu để chứng minh &lt;em&gt;quan hệ nhân quả&lt;/em&gt; của các mạch như Induction Heads.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ứng dụng điều hướng hành vi (Feature Steering):&lt;/strong&gt; Tăng hoặc khóa trực tiếp cường độ của một đặc trưng SAE đã phát hiện để kiểm soát phong cách hoặc giảm hành vi không an toàn của LLM ngay lúc suy luận.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-hiểu-định-lượng-về-chồng-chập-superposition-và-không-gian-từ-điển-của-sparse-autoencoder&quot;&gt;Giải thích: Hiểu định lượng về Chồng chập (Superposition) và không gian từ điển của Sparse Autoencoder&lt;/h3&gt;

&lt;p&gt;Trong một tầng Transformer có chiều ẩn \(d = 4{,}096\), giả sử mô hình cần biểu diễn \(M = 65{,}536\) khái niệm thực tế (gấp \(16\times\) số chiều sẵn có!), nhưng tại mỗi token trung bình chỉ có \(k = 32\) khái niệm thực sự xuất hiện cùng lúc.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tỷ lệ mở rộng (Expansion Factor) của SAE:&lt;/strong&gt; \(M / d = 65{,}536 / 4{,}096 = 16\times\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mật độ kích hoạt (Sparsity \(L_0\)):&lt;/strong&gt; Chỉ \(32 / 65{,}536 \approx 0{,}049\%\) số đặc trưng SAE khác 0 trên mỗi token.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mục tiêu của SAE trên một vector kích hoạt \(\mathbf{h}\):&lt;/strong&gt;
\(\mathcal{L}_{\text{SAE}} = \|\mathbf{h} - \hat{\mathbf{h}}\|_2^2 + \lambda \|\mathbf{f}\|_1.\)
Ví dụ nếu \(\|\mathbf{h} - \hat{\mathbf{h}}\|_2^2 = 0{,}08\), tổng độ lớn đặc trưng \(\|\mathbf{f}\|_1 = 24{,}0\) và \(\lambda = 0{,}005\), thì \(\mathcal{L}_{\text{SAE}} = 0{,}08 + 0{,}12 = 0{,}20\). Chính sự giằng co giữa sai số tái tạo và phạt \(L_1\) buộc SAE chọn ra bộ từ điển các khái niệm &lt;strong&gt;đơn nghĩa&lt;/strong&gt; nhất thay vì tái tạo bằng các tổ hợp pha trộn!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-diễn-giải-sau-limeshap--mạch-transformer-và-autoencoder-thưa&quot;&gt;Tùy chọn: Diễn giải sau LIME/SHAP — Mạch Transformer và Autoencoder thưa&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế các phần lý thuyết và cài đặt về &lt;em&gt;saliency&lt;/em&gt;, LIME hay SHAP. Nội dung giới thiệu nhánh &lt;strong&gt;diễn giải cơ chế&lt;/strong&gt; (&lt;em&gt;mechanistic interpretability&lt;/em&gt;) cho Transformer — hướng nghiên cứu phát triển mạnh cho LLM trong giai đoạn 2022–2026.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;SHAP vẫn trả lời tốt câu hỏi “đặc trưng đầu vào nào làm thay đổi điểm dự đoán?”. Tuy nhiên, với các mô hình ngôn ngữ lớn cỡ 70B tham số, câu hỏi trọng tâm thường chuyển sang: “&lt;strong&gt;đặc trưng nội tại&lt;/strong&gt; nào bên trong mạng đảm nhiệm hành vi từ chối, cú pháp mã nguồn hay một sự kiện tri thức cụ thể?”.&lt;/p&gt;

&lt;h2 id=&quot;1-autoencoder-thưa-sparse-autoencoder-trên-giá-trị-kích-hoạt&quot;&gt;1. Autoencoder thưa (Sparse Autoencoder) trên giá trị kích hoạt&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2309.08600&quot;&gt;Cunningham et al., 2023&lt;/a&gt; và &lt;a href=&quot;https://transformer-circuits.pub/2024/scaling-monosemanticity/index.html&quot;&gt;Templeton et al., 2024&lt;/a&gt; (Anthropic, &lt;em&gt;Scaling Monosemanticity&lt;/em&gt;) huấn luyện &lt;em&gt;autoencoder&lt;/em&gt; thưa (SAE) trên các vector kích hoạt của luồng phần dư (&lt;em&gt;residual stream&lt;/em&gt;) \(x\):&lt;/p&gt;

\[\hat{x} = W_{\mathrm{dec}}\,\mathrm{ReLU}(W_{\mathrm{enc}}x + b) + b&apos;, \quad \mathcal{L}=\|x-\hat{x}\|_2^2 + \lambda\|f\|_1.\]

&lt;p&gt;Mã thưa \(f\) giúp phân tách chồng chập thành các &lt;strong&gt;đặc trưng đơn nghĩa&lt;/strong&gt; (&lt;em&gt;monosemantic features&lt;/em&gt;) dễ diễn giải hơn. Từ đó, nhà nghiên cứu có thể thử điều hướng (&lt;em&gt;steering&lt;/em&gt;) hoặc triệt tiêu từng đặc trưng riêng lẻ, dù tiêu chuẩn đánh giá định lượng vẫn đang hoàn thiện. Ở đây, &lt;em&gt;autoencoder&lt;/em&gt; (Chương 12) đóng vai trò công cụ giải phẫu mô hình thay vì mô hình sinh dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-cụ-thể&quot;&gt;2. Ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;các-công-cụ-quy-kết-vẫn-giữ-vai-trò-trong-triển-khai-thực-tế&quot;&gt;Các công cụ quy kết vẫn giữ vai trò trong triển khai thực tế&lt;/h3&gt;

&lt;p&gt;Integrated Gradients trong &lt;a href=&quot;https://captum.ai/&quot;&gt;Captum&lt;/a&gt; và &lt;em&gt;attention rollout&lt;/em&gt; vẫn được dùng rộng rãi trong các ngành chịu sự quản lý để lập hồ sơ mô hình (&lt;em&gt;model card&lt;/em&gt;). Với dữ liệu dạng bảng (như chấm điểm tín dụng), SHAP và LIME trong bài lý thuyết vẫn là lựa chọn phù hợp hơn là áp dụng SAE.&lt;/p&gt;

&lt;h3 id=&quot;phân-tích-mạch-circuit-analysis&quot;&gt;Phân tích mạch (Circuit Analysis)&lt;/h3&gt;

&lt;p&gt;Loạt nghiên cứu &lt;a href=&quot;https://transformer-circuits.pub/&quot;&gt;Transformer Circuits (Elhage et al.)&lt;/a&gt; (2022–2024) phân tích ngược các cấu trúc như &lt;em&gt;induction head&lt;/em&gt; và những mạch tính toán con bên trong Transformer. Đây là tài liệu mở rộng, không thay thế bài tập thực hành Grad-CAM cơ bản.&lt;/p&gt;

&lt;h3 id=&quot;đánh-giá-an-toàn-mô-hình&quot;&gt;Đánh giá an toàn mô hình&lt;/h3&gt;

&lt;p&gt;Diễn giải cơ chế ngày càng được dùng làm đầu vào cho &lt;strong&gt;quản trị và an toàn AI&lt;/strong&gt;, chẳng hạn tìm hiểu liệu có thể nhận diện các đặc trưng liên quan đến hành vi sai lệch hay không. Các kết quả hiện vẫn mang tính nghiên cứu ban đầu; mục tiêu của bài là giới thiệu bộ công cụ chứ chưa khẳng định mô hình lớn đã được giải thích hoàn toàn.&lt;/p&gt;

&lt;h2 id=&quot;3-phần-mềm-phổ-biến&quot;&gt;3. Phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/pytorch/captum&quot;&gt;captum&lt;/a&gt; — thư viện quy kết cho PyTorch trong sản xuất.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/openai/sparse_autoencoder&quot;&gt;openai/sparse_autoencoder&lt;/a&gt; và &lt;a href=&quot;https://github.com/decoderesearch/SAELens&quot;&gt;SAELens&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/TransformerLensOrg/TransformerLens&quot;&gt;TransformerLens&lt;/a&gt; — công cụ phân tích mạch Transformer thông qua cơ chế &lt;em&gt;hook&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2309.08600&quot;&gt;Sparse Autoencoders Find Highly Interpretable Features (Cunningham et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://transformer-circuits.pub/2024/scaling-monosemanticity/index.html&quot;&gt;Scaling Monosemanticity (Templeton et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://transformer-circuits.pub/2021/framework/index.html&quot;&gt;A Mathematical Framework for Transformer Circuits (Elhage et al.)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-bài-này-bổ-sung-gì-cho-ghi-chú-cốt-lõi&quot;&gt;5. Bài này bổ sung gì cho ghi chú cốt lõi&lt;/h2&gt;

&lt;p&gt;Trước hết cần thực hành thành thạo LIME, SHAP và bản đồ &lt;em&gt;saliency&lt;/em&gt; trong các bài cốt lõi. Bài này bổ sung nhóm &lt;strong&gt;công cụ diễn giải cơ chế cho LLM&lt;/strong&gt; (SAE và phân tích mạch) xuất hiện sau hệ thống phương pháp XAI cổ điển.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [A Window  Into LLMs&lt;/td&gt;
          &lt;td&gt;Sparse Autoencoders Explained](https://www.youtube.com/watch?v=TKozVZoXAYs) — Papers Are Wonderful, tiếng Anh. Giải thích cách &lt;em&gt;autoencoder&lt;/em&gt; thưa trích xuất đặc trưng diễn giải được từ giá trị kích hoạt của LLM.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=UGO_Ehywuxc&quot;&gt;The Dark Matter of AI [Mechanistic Interpretability]&lt;/a&gt; — Welch Labs, tiếng Anh. Tổng quan về chương trình nghiên cứu diễn giải cơ chế, nơi các &lt;em&gt;autoencoder&lt;/em&gt; thưa được ứng dụng.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, tiếng Anh. Nền tảng trực quan hóa mạng nơ-ron trước đó mà hướng diễn giải cơ chế tiếp nối.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>24-01 Diễn giải và Giải thích Mạng Neuron</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter24/24_01_Model_Interpretability/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter24/24_01_Model_Interpretability</id>
   <content type="html">&lt;p&gt;Đặt niềm tin mù quáng vào một con số độ chính xác 98% giống như lái máy bay mà không có bảng đồng hồ đo bên trong buồng lái: mọi thứ có thể êm đẹp trong điều kiện chuẩn, nhưng ngay khi gặp nhiễu lạ ngoài thực tế, bạn sẽ không biết mô hình hỏng ở đâu. Mục tổng quan nền tảng này kết nối chặt chẽ phần lý thuyết quy kết (&lt;strong&gt;24-01-01&lt;/strong&gt;) với bài cài đặt thực chiến (&lt;strong&gt;24-01-02&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hệ-quy-chiếu-phân-loại-các-phương-pháp-diễn-giải-mô-hình&quot;&gt;Kiến thức cần nhớ: Hệ quy chiếu phân loại các phương pháp Diễn giải Mô hình&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Giải thích nội tại (Intrinsic) vs. Hậu kiểm (Post-hoc):&lt;/strong&gt; Phân biệt mô hình tự dễ hiểu (cây quyết định nông, hồi quy tuyến tính) với việc giải thích mạng sâu sau khi huấn luyện (Grad-CAM, SHAP).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cục bộ (Local) vs. Toàn cục (Global):&lt;/strong&gt; Trả lời “vì sao ảnh này bị gán nhãn mèo?” (local) khác với “mô hình học quy luật tổng quát nào trên toàn tập dữ liệu?” (global).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phụ thuộc mô hình (Model-Specific) vs. Độc lập mô hình (Model-Agnostic):&lt;/strong&gt; Các phương pháp gradient tận dụng cấu trúc khả vi của mạng nơ-ron cực nhanh, còn LIME/KernelSHAP chạy được với mọi hộp đen nhưng tốn nhiều lượt truy vấn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tiêu chuẩn chọn công cụ theo miền dữ liệu:&lt;/strong&gt; Grad-CAM/IG cho ảnh, SHAP cho dữ liệu bảng tài chính/y tế, và phân tích mạch/SAE cho mô hình ngôn ngữ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-chi-phí-tính-toán-grad-cam-vs-kernelshap-trên-một-bức-ảnh-224-times-224&quot;&gt;Giải thích: So sánh chi phí tính toán: Grad-CAM vs. KernelSHAP trên một bức ảnh \(224 \times 224\)&lt;/h3&gt;

&lt;p&gt;Giả sử một lượt suy luận (forward) qua ResNet-50 mất \(5\text{ ms}\) và một lượt lan truyền ngược (backward) mất \(10\text{ ms}\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Grad-CAM:&lt;/strong&gt; Chỉ cần đúng &lt;strong&gt;1 lượt forward + 1 lượt backward&lt;/strong&gt; → tổng thời gian \(= 5 + 10 = 15\text{ ms}\) (chạy được theo thời gian thực trên luồng video 60 fps!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Integrated Gradients (50 bước tích phân):&lt;/strong&gt; Cần \(50\) cặp forward/backward → \(50 \times 15 = 750\text{ ms}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LIME / KernelSHAP (chia ảnh thành 100 siêu điểm ảnh và lấy \(1{,}000\) mẫu nhiễu):&lt;/strong&gt; Cần \(1{,}000\) lượt forward → \(1{,}000 \times 5 = 5{,}000\text{ ms} = 5{,}0\text{ giây/ảnh}\).
Con số này giải thích trực quan vì sao kỹ sư thường dùng Grad-CAM cho chẩn đoán nhanh ảnh/video, và dành SHAP/LIME cho kiểm toán chuyên sâu dữ liệu bảng hoặc các ca quan trọng.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chủ đề diễn giải mô hình (&lt;em&gt;model interpretability&lt;/em&gt;) được chia thành hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết&lt;/strong&gt; — bản đồ nổi bật (&lt;em&gt;saliency&lt;/em&gt;), SHAP, LRP và trực giác hoạt động.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt&lt;/strong&gt; — mã minh họa Grad-CAM và SHAP, các bài báo nền tảng và những lưu ý thường gặp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, tiếng Anh. Phân biệt giữa việc quan sát bên trong mạng và việc giải thích một dự đoán cụ thể.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[SHAP values for beginners&lt;/td&gt;
          &lt;td&gt;What they mean and their applications](https://www.youtube.com/watch?v=MQ6fFDwjuco) — A Data Odyssey, tiếng Anh. Minh họa cách dùng giá trị SHAP để giải thích từng dự đoán riêng lẻ.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Explainable AI explained!&lt;/td&gt;
          &lt;td&gt;#3 LIME](https://www.youtube.com/watch?v=d6j6bofhj2M) — DeepFindr, tiếng Anh. Giới thiệu LIME như một cách tiếp cận giải thích cục bộ bổ sung cho SHAP.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>24-01-02 Cài đặt Diễn giải</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter24/24_01_02_Interpretability_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter24/24_01_02_Interpretability_Implementation</id>
   <content type="html">&lt;p&gt;Muốn nhìn thấy mạng ResNet-50 đang tập trung vào đâu trên bức ảnh mà không phải viết lại hay sửa đổi kiến trúc mạng, vũ khí bí mật của PyTorch chính là cơ chế &lt;strong&gt;Hooks&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;register_forward_hook&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;register_full_backward_hook&lt;/code&gt;). Trong bài thực hành này, bạn sẽ tự tay cài đặt lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;GradCAM&lt;/code&gt;, cài đặt bản đồ Saliency, Integrated Gradients và kết hợp với thư viện giải thích để soi sáng từng dự đoán của mạng CNN.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-kỹ-thuật-lập-trình-grad-cam-và-integrated-gradients-trong-pytorch&quot;&gt;Kiến thức cần nhớ: Kỹ thuật lập trình Grad-CAM và Integrated Gradients trong PyTorch&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế Forward &amp;amp; Backward Hooks:&lt;/strong&gt; Bắt giữ trọn vẹn bản đồ đặc trưng \(A^k\) (lượt xuôi) và gradient \(\partial y^c / \partial A^k\) (lượt ngược) tại tầng tích chập cuối (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;layer4[-1]&lt;/code&gt;) mà không sửa mã nguồn mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính trọng số kênh và phóng to bản đồ nhiệt:&lt;/strong&gt; Lấy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean(dim=(2, 3))&lt;/code&gt; trên gradient, nhân tổ hợp tuyến tính với feature map, áp dụng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;F.relu(...)&lt;/code&gt; và nội suy song tuyến (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bilinear&lt;/code&gt;) về đúng kích thước ảnh gốc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Riemann Sum cho Integrated Gradients:&lt;/strong&gt; Chia đoạn thẳng từ ảnh đen \(\mathbf{x}&apos;\) tới ảnh gốc \(\mathbf{x}\) thành \(m = 50\) bước rời rạc để xấp xỉ tích phân mượt và kiểm tra sai số hội tụ (completeness delta).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quản lý vòng đời Hook &amp;amp; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;zero_grad()&lt;/code&gt;:&lt;/strong&gt; Luôn gỡ hook (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;handle.remove()&lt;/code&gt;) sau khi dùng xong để tránh rò rỉ bộ nhớ GPU và nhớ xóa gradient trước mỗi lớp mục tiêu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bản-đồ-nhiệt-grad-cam-kích-thước-2-times-2-từ-2-kênh-đặc-trưng&quot;&gt;Giải thích: Tính tay một bản đồ nhiệt Grad-CAM kích thước \(2 \times 2\) từ 2 kênh đặc trưng&lt;/h3&gt;

&lt;p&gt;Giả sử tầng tích chập cuối có 2 kênh đặc trưng kích thước \(2 \times 2\):
\(A^1 = \begin{pmatrix} 2 &amp;amp; 0 \\ 1 &amp;amp; 3 \end{pmatrix}, \quad A^2 = \begin{pmatrix} 1 &amp;amp; 4 \\ 0 &amp;amp; 1 \end{pmatrix}\)
và gradient của điểm lớp mục tiêu \(y^c\) theo hai kênh này là:
\(\frac{\partial y^c}{\partial A^1} = \begin{pmatrix} 0{,}6 &amp;amp; 0{,}2 \\ 0{,}4 &amp;amp; 0{,}8 \end{pmatrix}, \quad \frac{\partial y^c}{\partial A^2} = \begin{pmatrix} -0{,}2 &amp;amp; -0{,}6 \\ -0{,}4 &amp;amp; 0{,}0 \end{pmatrix}.\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính trọng số tầm quan trọng từng kênh (Global Average Pooling trên gradient):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(\alpha_1 = \frac{0{,}6 + 0{,}2 + 0{,}4 + 0{,}8}{4} = +0{,}50\).&lt;/li&gt;
      &lt;li&gt;\(\alpha_2 = \frac{-0{,}2 - 0{,}6 - 0{,}4 + 0{,}0}{4} = -0{,}30\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổ hợp tuyến tính \(L = \alpha_1 A^1 + \alpha_2 A^2\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Góc trên-trái: \(0{,}5(2) - 0{,}3(1) = +0{,}70\)&lt;/li&gt;
      &lt;li&gt;Góc trên-phải: \(0{,}5(0) - 0{,}3(4) = -1{,}20\)&lt;/li&gt;
      &lt;li&gt;Góc dưới-trái: \(0{,}5(1) - 0{,}3(0) = +0{,}50\)&lt;/li&gt;
      &lt;li&gt;Góc dưới-phải: \(0{,}5(3) - 0{,}3(1) = +1{,}20\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng ReLU&lt;/strong&gt; (loại bỏ bằng chứng chống lại lớp \(c\)) và chuẩn hóa về \([0, 1]\):
\(\text{Grad-CAM} = \begin{pmatrix} 0{,}70 &amp;amp; 0 \\ 0{,}50 &amp;amp; 1{,}20 \end{pmatrix} \xrightarrow{\div 1{,}20} \begin{pmatrix} 0{,}58 &amp;amp; 0{,}00 \\ 0{,}42 &amp;amp; 1{,}00 \end{pmatrix}.\)
Vùng nóng nhất nằm ở góc dưới-phải (\(1{,}00\)), còn góc trên-phải bị cắt về \(0\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;

&lt;p&gt;Ví dụ cài đặt Grad-CAM và xấp xỉ SHAP đơn giản bằng PyTorch:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GradCAM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Gradient-weighted Class Activation Mapping.
    
    Visualizes which regions of image are important for prediction
    by computing gradients of class score with respect to final
    convolutional layer activations.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        model: CNN model
        target_layer: name of convolutional layer to visualize
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_layer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_layer&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Storage for forward activations and backward gradients
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Register hooks
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_register_hooks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_register_hooks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Register forward and backward hooks on target layer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Find target layer
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;named_modules&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;register_forward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;forward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;register_full_backward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;backward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_class&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Generate CAM for target class.
        
        input_image: (1, 3, H, W)
        target_class: index of class to explain
        
        Returns: (H, W) heatmap
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass for target class
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;class_score&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_class&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;class_score&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Get activations and gradients
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, C, H, W)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, C, H, W)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Global average pool gradients to get weights
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, C, 1, 1)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Weighted combination of activation maps
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, 1, H, W)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# ReLU (only positive contributions)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Normalize to [0, 1]
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example usage
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Grad-CAM: Visualizing CNN Decisions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Load pre-trained model
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;PIL&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Image&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;resnet50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DEFAULT&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create Grad-CAM
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradcam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GradCAM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_layer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;layer4&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Load and preprocess image (simulated here)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generating Grad-CAM for sample image...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;input_tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;224&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;224&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Get prediction
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;predicted_class&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;confidence&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted_class&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted class: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predicted_class&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; with confidence &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;confidence&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate CAM for predicted class
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradcam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;generate_cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted_class&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CAM shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CAM range: [&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CAM highlights image regions important for prediction!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;High values = important regions, low values = irrelevant&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# SHAP approximation
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSHAP&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Simplified SHAP for neural networks&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;background_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        model: neural network
        background_data: reference dataset for baselines
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;background&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;background_data&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;explain&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Approximate SHAP values for input x.
        
        Uses sampling to approximate Shapley values:
        repeatedly mask random subsets of features,
        measure prediction changes.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Get baseline prediction (average over background)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;baseline_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Generate random feature masks
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;masks&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute predictions with different feature subsets
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;masks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Mask some features (use background average)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;x_masked&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clone&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;bg_avg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;x_masked&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bg_avg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;x_masked&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_masked&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Compute prediction
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_masked&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Marginal contribution of each feature
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;pred_diff&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;baseline_output&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred_diff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SHAP: Feature Attribution&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simple example with a linear model (for verification)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;simple_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;background&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reference data
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;shap&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSHAP&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;simple_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Explain a prediction
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;explain&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature attributions (SHAP values):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Positive = feature increased prediction&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Negative = feature decreased prediction&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Magnitude = importance&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Ví dụ tạo mẫu đối kháng bằng FGSM để kiểm tra độ vững chắc của mô hình:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fgsm_attack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Fast Gradient Sign Method: minimal perturbation to fool model.
    
    Reveals model&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s decision boundaries and vulnerabilities.
    Shows what patterns strongly influence predictions.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Backward to get gradients
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Create adversarial example
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Move in direction that increases loss (fools model)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;perturbation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sign&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;adversarial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;perturbation&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adversarial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adversarial Examples: Probing Model Robustness&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simple classifier
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyClassifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;toy_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyClassifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;toy_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Original image (random for demo)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;original&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;true_label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Get original prediction
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;orig_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;toy_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;original&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;orig_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;orig_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;orig_conf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orig_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;orig_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Original prediction: class &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orig_pred&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orig_conf&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; confidence)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate adversarial example
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adversarial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fgsm_attack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;toy_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;original&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clone&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test adversarial
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;adv_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;toy_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adversarial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;adv_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adv_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;adv_conf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adv_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adv_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adversarial prediction: class &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adv_pred&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adv_conf&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; confidence)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Measure perturbation
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perturbation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adversarial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;original&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Average perturbation: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perturbation&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adv_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;orig_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✗ Model fooled by imperceptible perturbation!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This reveals model&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s decision boundary is fragile&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✓ Model robust to this perturbation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Diễn giải mô hình liên hệ gần gũi với suy luận nhân quả (&lt;em&gt;causal inference&lt;/em&gt;). Các phương pháp quy kết thông thường chỉ phản ánh mối tương quan giữa đầu vào và đầu ra, chưa chứng minh quan hệ nhân quả. Diễn giải nhân quả đặt câu hỏi sâu hơn: “nếu can thiệp thay đổi đặc trưng này thì dự đoán có thực sự thay đổi không?”, đòi hỏi can thiệp và phân tích phản thực.&lt;/p&gt;

&lt;p&gt;Diễn giải và định lượng độ bất định (&lt;em&gt;uncertainty quantification&lt;/em&gt;) bổ trợ trực tiếp cho nhau: diễn giải cho biết &lt;em&gt;vì sao&lt;/em&gt; mô hình dự đoán như vậy, còn định lượng bất định cho biết mô hình &lt;em&gt;chắc chắn đến mức nào&lt;/em&gt;. Kết hợp cả hai (qua học sâu Bayes, &lt;em&gt;MC dropout&lt;/em&gt; hoặc &lt;em&gt;ensemble&lt;/em&gt;) mang lại câu trả lời đầy đủ hơn cho người sử dụng.&lt;/p&gt;

&lt;p&gt;Diễn giải cũng là công cụ hỗ trợ kiểm toán tính công bằng và phát hiện thiên kiến. Nếu một mô hình tuyển dụng phụ thuộc trực tiếp hoặc gián tiếp (qua biến đại diện) vào giới tính hay chủng tộc, các phương pháp quy kết sẽ giúp bộc lộ điều đó. Tuy nhiên, diễn giải chỉ là bước phát hiện; việc đánh giá đặc trưng nào hợp lệ hay gây thiên kiến vẫn cần tiêu chuẩn miền và quy định cụ thể.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.6034&quot;&gt;“Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Karen Simonyan, Andrea Vedaldi, Andrew Zisserman&lt;br /&gt;
Giới thiệu bản đồ &lt;em&gt;saliency&lt;/em&gt; dựa trên gradient cho CNN, đặt nền móng cho nhóm kỹ thuật trực quan hóa tầm quan trọng của từng pixel.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1311.2901&quot;&gt;“Visualizing and Understanding Convolutional Networks” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Matthew Zeiler, Rob Fergus&lt;br /&gt;
Sử dụng mạng &lt;em&gt;deconvolution&lt;/em&gt; để trực quan hóa đặc trưng qua các tầng CNN, chỉ ra cấu trúc phân cấp từ cạnh/màu ở tầng đầu, kết cấu ở tầng giữa đến bộ phận đối tượng ở tầng sâu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1610.02391&quot;&gt;“Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ramprasaath Selvaraju, Michael Cogswell, Abhishek Das, Ramakrishna Vedantam, Devi Parikh, Dhruv Batra&lt;br /&gt;
Grad-CAM dùng gradient để gán trọng số cho các bản đồ đặc trưng, tạo bản đồ định vị theo lớp mà không cần sửa đổi kiến trúc CNN, trở thành công cụ phổ biến cho diễn giải ảnh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1705.07874&quot;&gt;“A Unified Approach to Interpreting Model Predictions” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Scott Lundberg, Su-In Lee&lt;br /&gt;
SHAP thống nhất nhiều phương pháp quy kết dưới khung giá trị Shapley của lý thuyết trò chơi, được dùng rộng rãi cho dữ liệu dạng bảng và các mô hình tổng quát.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1703.01365&quot;&gt;“Axiomatic Attribution for Deep Networks” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Mukund Sundararajan, Ankur Taly, Qiqi Yan&lt;br /&gt;
Đề xuất Integrated Gradients đáp ứng hai tiên đề quan trọng là tính nhạy và bất biến cài đặt mà gradient thuần túy vi phạm.&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;Bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;p&gt;Bản đồ &lt;em&gt;saliency&lt;/em&gt; đôi khi gây hiểu nhầm: gradient lớn không phải lúc nào cũng phản ánh đặc trưng quan trọng về mặt ngữ nghĩa mà có thể do đặc thù kiến trúc (như ReLU hay chuẩn hóa batch). Cần kiểm chứng lại bằng thử nghiệm loại bỏ đặc trưng (&lt;em&gt;ablation&lt;/em&gt;) và đối chiếu với kiến thức chuyên ngành.&lt;/p&gt;

&lt;p&gt;Sự tồn tại của ví dụ đối kháng không đồng nghĩa mô hình hoàn toàn kém; hầu hết mô hình học sâu trong không gian nhiều chiều đều nhạy cảm với nhiễu đối kháng thiết kế riêng. Trừ các bài toán bảo mật đặc thù, cần ưu tiên đánh giá độ vững chắc trước các dạng nhiễu tự nhiên (như mờ ảnh, nhiễu cảm biến).&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;p&gt;Diễn giải mô hình giúp hiểu cơ chế ra quyết định thông qua quy kết đặc trưng (đầu vào nào quan trọng), trực quan hóa kích hoạt (đặc trưng nào được học) và phân tích độ vững chắc. &lt;em&gt;Gradient saliency&lt;/em&gt; và Grad-CAM làm nổi bật vùng không gian quan trọng trong CNN, SHAP cung cấp phương pháp quy kết có nền tảng lý thuyết trò chơi, còn ví dụ đối kháng thăm dò độ bền của biên quyết định. Vì mỗi kỹ thuật chỉ phản ánh một khía cạnh, việc kết hợp nhiều phương pháp giúp gỡ lỗi tương quan giả, kiểm toán thiên kiến và tăng độ tin cậy khi triển khai học sâu trong các lĩnh vực rủi ro cao.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Explainable AI explained!&lt;/td&gt;
          &lt;td&gt;#3 LIME](https://www.youtube.com/watch?v=d6j6bofhj2M) — DeepFindr, tiếng Anh. Minh họa cách cài đặt một phương pháp giải thích cục bộ bằng mô hình có trọng số.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[SHAP values for beginners&lt;/td&gt;
          &lt;td&gt;What they mean and their applications](https://www.youtube.com/watch?v=MQ6fFDwjuco) — A Data Odyssey, tiếng Anh. Giúp hiểu rõ đại lượng mà thư viện SHAP tính toán phía sau giao diện gọi hàm.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, tiếng Anh. Phân tích các bẫy phổ biến khi trực quan hóa (những hình ảnh trông hợp lý nhưng chưa chắc phản ánh đúng cơ chế của mô hình).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>24-01-01 Lý thuyết Diễn giải</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter24/24_01_01_Interpretability_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter24/24_01_01_Interpretability_Theory</id>
   <content type="html">&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Nếu ta chỉ lấy đạo hàm $$\left&lt;/td&gt;
      &lt;td&gt;\frac{\partial f(x)}{\partial x_i}\right&lt;/td&gt;
      &lt;td&gt;\(để đánh giá tầm quan trọng của đặc trưng\)x_i$$, một bẫy toán học tinh vi lập tức xuất hiện: tại vùng bão hòa của ReLU hay Sigmoid, đạo hàm có thể bằng &lt;strong&gt;đúng 0&lt;/strong&gt; ngay cả khi đặc trưng đó đã đóng góp toàn bộ tín hiệu làm thay đổi dự đoán! Bài lý thuyết này trình bày cách &lt;strong&gt;Integrated Gradients&lt;/strong&gt;, &lt;strong&gt;Grad-CAM&lt;/strong&gt; và &lt;strong&gt;SHAP (giá trị Shapley)&lt;/strong&gt; khắc phục bẫy bão hòa và thiết lập những tiên đề công bằng chặt chẽ cho việc quy kết đặc trưng.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-nền-tảng-toán-học-của-saliency-integrated-gradients-grad-cam-và-shap&quot;&gt;Kiến thức cần nhớ: Nền tảng toán học của Saliency, Integrated Gradients, Grad-CAM và SHAP&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Saliency Map &amp;amp; Integrated Gradients (IG):&lt;/strong&gt; Khắc phục bão hòa gradient bằng cách tích phân đạo hàm dọc đoạn thẳng từ điểm cơ sở \(\mathbf{x}&apos;\) tới \(\mathbf{x}\): \(\text{IG}_i(\mathbf{x}) = (x_i - x&apos;_i) \int_0^1 \frac{\partial f(\mathbf{x}&apos; + \alpha(\mathbf{x} - \mathbf{x}&apos;))}{\partial x_i} d\alpha\), đảm bảo tiên đề &lt;em&gt;đầy đủ&lt;/em&gt; (tổng đóng góp bằng \(f(\mathbf{x}) - f(\mathbf{x}&apos;)\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Grad-CAM trên tầng tích chập cuối:&lt;/strong&gt; Tính trọng số tầm quan trọng từng kênh bằng trung bình không gian của gradient \(\alpha_k^c = \frac{1}{Z}\sum_{i,j} \frac{\partial y^c}{\partial A^k_{ij}}\), rồi lấy tổ hợp tuyến tính qua ReLU để giữ các vùng đóng góp dương cho lớp \(c\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giá trị Shapley trong lý thuyết trò chơi (SHAP):&lt;/strong&gt; Phương pháp quy kết &lt;em&gt;duy nhất&lt;/em&gt; thỏa mãn đồng thời ba tiên đề: độ chính xác cục bộ, tính khuyết (missingness) và tính nhất quán (consistency).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LIME (Local Interpretable Model-Agnostic Explanations):&lt;/strong&gt; Lấy mẫu nhiễu quanh điểm \(\mathbf{x}\), gán trọng số gần xa theo nhân khoảng cách, rồi khớp mô hình tuyến tính thưa giải thích hành vi cục bộ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-giá-trị-shapley-shap-cho-một-mô-hình-dự-đoán-có-2-đặc-trưng&quot;&gt;Giải thích: Tính tay giá trị Shapley (SHAP) cho một mô hình dự đoán có 2 đặc trưng&lt;/h3&gt;

&lt;p&gt;Giả sử một mô hình chấm điểm rủi ro tín dụng dùng 2 đặc trưng: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Thu nhập&lt;/code&gt; (\(x_1\)) và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Lịch sử trễ hạn&lt;/code&gt; (\(x_2\)). Giá trị dự đoán kỳ vọng của mô hình trên 4 tập con đặc trưng đã biết là:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Không biết đặc trưng nào: \(v(\varnothing) = 50\) (điểm cơ sở).&lt;/li&gt;
  &lt;li&gt;Chỉ biết \(x_1\): \(v(\{x_1\}) = 62\).&lt;/li&gt;
  &lt;li&gt;Chỉ biết \(x_2\): \(v(\{x_2\}) = 70\).&lt;/li&gt;
  &lt;li&gt;Biết cả hai: \(v(\{x_1, x_2\}) = 90\) (tổng mức tăng cần phân bổ là \(90 - 50 = +40\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Với 2 đặc trưng có \(2! = 2\) thứ tự thêm vào (\(x_1 \to x_2\) và \(x_2 \to x_1\)):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đóng góp biên của \(x_1\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Khi thêm trước: \(v(\{x_1\}) - v(\varnothing) = 62 - 50 = +12\).&lt;/li&gt;
      &lt;li&gt;Khi thêm sau \(x_2\): \(v(\{x_1, x_2\}) - v(\{x_2\}) = 90 - 70 = +20\).&lt;/li&gt;
      &lt;li&gt;Giá trị Shapley của \(x_1\): \(\phi_1 = \frac{12 + 20}{2} = +16\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đóng góp biên của \(x_2\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Khi thêm trước: \(70 - 50 = +20\); khi thêm sau \(x_1\): \(90 - 62 = +28\).&lt;/li&gt;
      &lt;li&gt;Giá trị Shapley của \(x_2\): \(\phi_2 = \frac{20 + 28}{2} = +24\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng tiên đề đầy đủ (Efficiency):&lt;/strong&gt; \(\phi_1 + \phi_2 = 16 + 24 = +40 = v(\{x_1, x_2\}) - v(\varnothing)\) — chính xác tuyệt đối!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;diễn-giải-mô-hình-hiểu-cơ-chế-hộp-đen&quot;&gt;Diễn giải Mô hình: Hiểu Cơ chế “Hộp đen”&lt;/h1&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Diễn giải mạng nơ-ron (&lt;em&gt;neural network interpretability&lt;/em&gt;) giải quyết câu hỏi cốt lõi trong học sâu: vì sao mô hình lại đưa ra một dự đoán cụ thể? Dù mạng nơ-ron đạt độ chính xác cao trên nhiều tác vụ, quá trình suy luận bên trong thường khó quan sát vì hàng triệu tham số tương tác qua nhiều tầng biến đổi phi tuyến. Tính chất “hộp đen” này trở thành rào cản trong các lĩnh vực có mức độ rủi ro cao như y khoa (vì sao mô hình chẩn đoán bệnh này?), pháp lý (vì sao đánh giá rủi ro cao?) hay xe tự lái (vì sao xe phanh gấp?), nơi hệ thống cần không chỉ dự đoán đúng mà còn có căn cứ để kiểm toán, tin cậy và gỡ lỗi.&lt;/p&gt;

&lt;p&gt;Cần phân biệt rõ giữa &lt;em&gt;khả năng diễn giải&lt;/em&gt; (&lt;em&gt;interpretability&lt;/em&gt;) và &lt;em&gt;khả năng giải thích&lt;/em&gt; (&lt;em&gt;explainability&lt;/em&gt;). Một mô hình có khả năng diễn giải khi cơ chế tính toán nội tại của nó minh bạch — chẳng hạn hồi quy tuyến tính hoặc cây quyết định nông, nơi ta nhìn trực tiếp cách các đặc trưng kết hợp thành đầu ra. Khả năng giải thích là việc cung cấp lời giải thích hậu kỳ (&lt;em&gt;post-hoc&lt;/em&gt;) cho một dự đoán cụ thể, ngay cả khi bản thân mô hình không minh bạch. Mạng nơ-ron sâu hiếm khi diễn giải trực tiếp được toàn bộ tham số, nhưng có thể được giải thích thông qua các kỹ thuật làm nổi bật vùng đầu vào quan trọng, trực quan hóa đặc trưng đã học hoặc xấp xỉ quyết định cục bộ bằng một mô hình thay thế đơn giản hơn.&lt;/p&gt;

&lt;p&gt;Nhu cầu diễn giải xuất phát từ nhiều mục đích thực tế: trong nghiên cứu khoa học và y học, quan sát đặc trưng mô hình dựa vào có thể gợi mở dấu hiệu mới; trong gỡ lỗi, diễn giải giúp phát hiện tương quan giả (như nhận diện chó husky dựa trên nền tuyết thay vì đặc điểm con chó); trong các hệ thống an toàn trọng yếu, nó hỗ trợ kiểm chứng hành vi trên nhiều kịch bản; và trong các ngành chịu sự quản lý chặt chẽ, giải thích quyết định có thể là yêu cầu pháp lý.&lt;/p&gt;

&lt;p&gt;Các nhóm phương pháp diễn giải tiếp cận bài toán từ nhiều góc độ khác nhau: phương pháp &lt;em&gt;saliency&lt;/em&gt; làm nổi bật vùng đầu vào tác động mạnh nhất đến dự đoán (“mô hình nhìn vào đâu?”); trực quan hóa kích hoạt cho thấy mẫu đầu vào nào làm một nơ-ron kích hoạt mạnh (“mạng học được đặc trưng gì?”); phương pháp quy kết (&lt;em&gt;attribution&lt;/em&gt;) phân bổ giá trị dự đoán thành đóng góp của từng đặc trưng (“mỗi đặc trưng quan trọng đến mức nào?”); và giải thích theo khái niệm tìm kiếm các khái niệm bậc cao thay vì dừng ở từng pixel hay từ đơn lẻ. Trong thực tế, việc đánh giá toàn diện thường cần phối hợp nhiều kỹ thuật bổ trợ nhau.&lt;/p&gt;

&lt;p&gt;Diễn giải mô hình cũng luôn đi kèm các sự đánh đổi: mô hình dễ diễn giải trực tiếp thường kém chính xác hơn mạng sâu; lời giải thích trung thực hoàn toàn với cơ chế nội tại có thể quá phức tạp để con người hiểu, trong khi lời giải thích đơn giản lại dễ lược bỏ chi tiết quan trọng. Vì vậy, nghiên cứu diễn giải tập trung cân bằng giữa độ trung thực, tính dễ hiểu và giá trị sử dụng cho từng bối cảnh cụ thể.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Các phương pháp quy kết hình thức hóa câu hỏi “đặc trưng đầu vào nào ảnh hưởng nhiều nhất đến dự đoán?” bằng một vectơ quy kết \(\mathbf{a}\) cho đầu vào \(\mathbf{x}\) và mô hình \(f\), trong đó \(a_i\) biểu thị mức độ quan trọng của thành phần đầu vào thứ \(i\) đối với \(f(\mathbf{x})\).&lt;/p&gt;

&lt;h3 id=&quot;bản-đồ-nổi-bật-dựa-trên-gradient-gradient-based-saliency&quot;&gt;Bản đồ nổi bật dựa trên Gradient (Gradient-based Saliency)&lt;/h3&gt;

&lt;p&gt;Cách quy kết đơn giản nhất sử dụng độ lớn đạo hàm theo đầu vào:&lt;/p&gt;

\[\mathbf{a} = \left|\frac{\partial f(\mathbf{x})}{\partial \mathbf{x}}\right|\]

&lt;p&gt;Đại lượng này đo mức độ nhạy của đầu ra trước thay đổi nhỏ của từng chiều đầu vào. Trên dữ liệu ảnh, kết quả tạo thành bản đồ &lt;em&gt;saliency&lt;/em&gt; làm nổi bật các pixel có ảnh hưởng lớn.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, gradient thuần túy có thể bị bão hòa (đạo hàm tiến về 0 ở vùng phẳng dù đặc trưng vẫn quan trọng) và không đối chiếu với một mốc tham chiếu (&lt;em&gt;baseline&lt;/em&gt;). &lt;strong&gt;Integrated Gradients&lt;/strong&gt; khắc phục điều này bằng cách tích phân gradient dọc theo đoạn thẳng nối từ mốc tham chiếu \(\mathbf{x}&apos;\) đến đầu vào \(\mathbf{x}\):&lt;/p&gt;

\[\mathbf{a}_i = (x_i - x_i&apos;) \int_{\alpha=0}^1 \frac{\partial f(\mathbf{x}&apos; + \alpha(\mathbf{x} - \mathbf{x}&apos;))}{\partial x_i} d\alpha\]

&lt;p&gt;Phương pháp này thỏa mãn các tiên đề quan trọng như tính nhạy (&lt;em&gt;sensitivity&lt;/em&gt; — đặc trưng không ảnh hưởng đầu ra có điểm quy kết bằng 0) và bất biến cài đặt (&lt;em&gt;implementation invariance&lt;/em&gt; — hai mạng tương đương về hàm số cho cùng kết quả quy kết).&lt;/p&gt;

&lt;h3 id=&quot;shap-shapley-additive-explanations&quot;&gt;SHAP (Shapley Additive Explanations)&lt;/h3&gt;

&lt;p&gt;SHAP dựa trên giá trị Shapley trong lý thuyết trò chơi hợp tác. Đóng góp của đặc trưng \(i\) được định nghĩa là:&lt;/p&gt;

\[\phi_i = \sum_{S \subseteq \mathcal{F} \backslash \{i\}} \frac{|S|!(|\mathcal{F}|-|S|-1)!}{|\mathcal{F}|!} [f(S \cup \{i\}) - f(S)]\]

&lt;p&gt;trong đó \(\mathcal{F}\) là tập toàn bộ đặc trưng, \(S\) là tập con đặc trưng và \(f(S)\) là dự đoán của mô hình khi chỉ giữ các đặc trưng trong \(S\) (các đặc trưng còn lại đặt về giá trị tham chiếu). Công thức tính trung bình có trọng số đóng góp biên của đặc trưng \(i\) trên mọi tổ hợp con khả dĩ.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Vì tính chính xác giá trị Shapley đòi hỏi $$2^{&lt;/td&gt;
      &lt;td&gt;\mathcal{F}&lt;/td&gt;
      &lt;td&gt;}$$ lần đánh giá mô hình, thực tế thường dùng các thuật toán xấp xỉ như Kernel SHAP (hồi quy tuyến tính có trọng số) hoặc thuật toán chính xác trong thời gian đa thức như TreeSHAP dành cho mô hình cây.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;lan-truyền-độ-liên-quan-theo-tầng-layer-wise-relevance-propagation-lrp&quot;&gt;Lan truyền độ liên quan theo tầng (Layer-wise Relevance Propagation, LRP)&lt;/h3&gt;

&lt;p&gt;LRP phân bổ ngược độ liên quan từ đầu ra về đầu vào qua từng tầng:&lt;/p&gt;

\[R_i^{(l)} = \sum_j \frac{z_{ij}}{\sum_k z_{kj}} R_j^{(l+1)}\]

&lt;p&gt;trong đó \(z_{ij} = a_i^{(l)} w_{ij}\) là đóng góp của nơ-ron \(i\) ở tầng \(l\) vào nơ-ron \(j\) ở tầng \(l+1\). Xuất phát từ \(R_{\text{out}} = f(\mathbf{x})\), phép lan truyền ngược bảo toàn tổng độ liên quan qua các tầng sao cho \(\sum_i R_i^{(0)} = f(\mathbf{x})\).&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và trực giác&lt;/h2&gt;

&lt;p&gt;Xét một mạng CNN phân loại một bức ảnh là “chó” với độ tin cậy 95%. Nếu không có công cụ diễn giải, ta không biết mô hình dựa vào khuôn mặt chó, dáng thân hay một yếu tố nền mang tính tương quan giả như bãi cỏ.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Gradient saliency&lt;/strong&gt; tính \(\partial p_{\text{dog}}/\partial \text{pixels}\) để xác định các pixel mà thay đổi nhỏ tạo biến động lớn nhất cho xác suất lớp “chó”. Nếu bản đồ nhiệt tập trung vào mặt và tai chó, mô hình đang dùng đặc trưng hợp lý; nếu tập trung vào nền, mô hình có nguy cơ dựa vào tương quan giả.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Class Activation Mapping (CAM)&lt;/strong&gt; đối với CNN có tầng &lt;em&gt;global average pooling&lt;/em&gt; tính tổ hợp tuyến tính của các bản đồ đặc trưng ở tầng tích chập cuối bằng trọng số của lớp “chó”:&lt;/li&gt;
&lt;/ul&gt;

\[\text{CAM} = \sum_k w_k^{\text{dog}} \cdot \text{FeatureMap}_k\]

&lt;p&gt;Phóng to bản đồ nhiệt này lên kích thước ảnh gốc và chồng lên ảnh giúp thấy trực quan vùng không gian nào đóng góp vào dự đoán.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Giá trị SHAP&lt;/strong&gt; cho cùng dự đoán có thể cho kết quả minh họa như sau:
    &lt;ul&gt;
      &lt;li&gt;Vùng mặt chó: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+0.35&lt;/code&gt; (đóng góp dương mạnh).&lt;/li&gt;
      &lt;li&gt;Vùng thân chó: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+0.28&lt;/code&gt;.&lt;/li&gt;
      &lt;li&gt;Nền cỏ: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+0.08&lt;/code&gt; (đóng góp nhỏ; nếu lớn sẽ là dấu hiệu tương quan giả).&lt;/li&gt;
      &lt;li&gt;Vùng bầu trời: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-0.02&lt;/code&gt; (âm nhẹ, phù hợp với vùng không liên quan).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nếu vùng nền cỏ có giá trị SHAP lớn, ta phát hiện được thiên lệch dữ liệu (chó thường xuất hiện trên cỏ) để bổ sung dữ liệu đa dạng hơn hoặc tăng cường dữ liệu.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ví dụ đối kháng&lt;/strong&gt; (&lt;em&gt;adversarial example&lt;/em&gt;) cung cấp một góc nhìn khác về độ vững chắc: tìm nhiễu đầu vào nhỏ nhất làm thay đổi dự đoán. Nếu một nhiễu rất nhỏ không thể nhận ra bằng mắt thường khiến ảnh “chó” bị phân loại thành “mèo”, biên quyết định của mô hình còn mong manh và có thể đang dựa vào các mẫu tín hiệu thiếu bền vững.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [SHAP values for beginners&lt;/td&gt;
          &lt;td&gt;What they mean and their applications](https://www.youtube.com/watch?v=MQ6fFDwjuco) — A Data Odyssey, tiếng Anh. Giải thích giá trị SHAP như cách phân bổ đóng góp công bằng cho từng đặc trưng, tương ứng với định nghĩa trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, tiếng Anh. Trình bày nhánh trực quan hóa đặc trưng (xem một nơ-ron phản ứng với mẫu ảnh nào).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Explainable AI explained!&lt;/td&gt;
          &lt;td&gt;#3 LIME](https://www.youtube.com/watch?v=d6j6bofhj2M) — DeepFindr, tiếng Anh. Giới thiệu LIME — phương pháp xấp xỉ tuyến tính cục bộ bổ sung cạnh SHAP.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>24 Khả năng Diễn giải và Giải thích</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter24/24_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter24/24_00_Introduction</id>
   <content type="html">&lt;p&gt;Có một câu chuyện kinh điển trong lịch sử học sâu: một mô hình phân loại ảnh y tế đạt độ chính xác 99% khi chẩn đoán ung thư da trên tập kiểm tra — cho đến khi các nhà nghiên cứu dùng bản đồ giải thích soi vào và bàng hoàng phát hiện… mô hình chẳng hề nhìn vào khối u, mà chỉ chăm chăm tìm &lt;strong&gt;chiếc thước kẻ bác sĩ thường đặt cạnh các khối u ác tính&lt;/strong&gt; lúc chụp ảnh! Đó là lý do &lt;strong&gt;Khả năng Diễn giải và Giải thích (Interpretability &amp;amp; Explainability)&lt;/strong&gt; không phải món trang sức học thuật, mà là tuyến phòng thủ quan trọng để kiểm chứng niềm tin, phát hiện đường tắt (&lt;em&gt;shortcut learning&lt;/em&gt;) và đảm bảo an toàn AI.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-diễn-giải-mô-hình-học-sâu&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Diễn giải Mô hình Học sâu&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Quy kết dựa trên Gradient (Saliency Maps, Integrated Gradients, Grad-CAM):&lt;/strong&gt; Đo độ nhạy của điểm dự đoán lớp theo từng điểm ảnh hoặc bản đồ đặc trưng tích chập để tô sáng vùng quyết định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giải thích độc lập mô hình (LIME &amp;amp; SHAP):&lt;/strong&gt; Xấp xỉ tuyến tính cục bộ (LIME) hoặc chia công bằng đóng góp từng đặc trưng dựa trên lý thuyết trò chơi hợp tác (giá trị Shapley trong SHAP).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá tính trung thực (Faithfulness vs. Plausibility):&lt;/strong&gt; Phân biệt giải thích “trông hợp lý với mắt người” với giải thích “thực sự phản ánh cơ chế tính toán của mạng” bằng các bài kiểm tra ngẫu nhiên hóa trọng số (&lt;em&gt;sanity checks&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diễn giải cơ chế hiện đại (Mechanistic Interpretability — 2022–2026):&lt;/strong&gt; Mổ xẻ mạch tính toán bên trong Transformer (Induction Heads, Circuit Analysis) và dùng Sparse Autoencoder tách các khái niệm bị chồng chập.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-thử-nghiệm-xóa-vùng-nổi-bật-deletion-test-để-kiểm-chứng-tính-trung-thực-của-giải-thích&quot;&gt;Giải thích: Thử nghiệm xóa vùng nổi bật (Deletion Test) để kiểm chứng tính trung thực của giải thích&lt;/h3&gt;

&lt;p&gt;Làm sao biết một bản đồ giải thích (ví dụ Grad-CAM) thực sự tìm đúng vùng ảnh quan trọng chứ không chỉ vẽ lại viền ảnh? Ta chạy bài kiểm tra &lt;strong&gt;Deletion Faithfulness&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Giả sử ảnh gốc có xác suất dự đoán lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chó Golden&lt;/code&gt; là \(p_0 = 0{,}94\). Ta lần lượt che mờ (thay bằng màu trung bình) \(10\%\), \(20\%\), \(30\%\) số pixel có điểm quy kết cao nhất:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phương pháp A (trung thực cao):&lt;/strong&gt; Xác suất tụt mạnh: \(0{,}94 \to 0{,}42 \to 0{,}15 \to 0{,}06\) (diện tích dưới đường cong Deletion AUC thấp \(\approx 0{,}36\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương pháp B (kém trung thực, chỉ tô viền nền):&lt;/strong&gt; Xác suất hầu như không đổi: \(0{,}94 \to 0{,}91 \to 0{,}88 \to 0{,}82\) (Deletion AUC cao \(\approx 0{,}89\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chỉ số Deletion AUC thấp hơn hẳn của Phương pháp A chứng minh bằng thực nghiệm định lượng rằng các vùng nó tô sáng thực sự là nhân tố điều khiển quyết định của mạng!&lt;/p&gt;

&lt;p&gt;Hiểu lý do mô hình học sâu đưa ra một dự đoán cụ thể là yêu cầu quan trọng để xây dựng niềm tin, gỡ lỗi và đáp ứng quy định pháp lý. Chương này trình bày các phương pháp trực quan hóa (bản đồ nổi bật / &lt;em&gt;saliency map&lt;/em&gt;, trực quan hóa kích hoạt), phân tích &lt;em&gt;attention&lt;/em&gt;, đánh giá tầm quan trọng của đặc trưng, LIME, SHAP, giải thích phản thực (&lt;em&gt;counterfactual explanation&lt;/em&gt;) và ví dụ đối kháng (&lt;em&gt;adversarial example&lt;/em&gt;), giúp làm rõ cơ chế ra quyết định bên trong các mô hình “hộp đen”.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau LIME và SHAP, xem thêm bài &lt;strong&gt;24-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về &lt;em&gt;autoencoder&lt;/em&gt; thưa và diễn giải cơ chế cho LLM.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, tiếng Anh. Bài giảng CS231n về trực quan hóa và hiểu hoạt động bên trong mạng nơ-ron — điểm khởi đầu của chương.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[SHAP values for beginners&lt;/td&gt;
          &lt;td&gt;What they mean and their applications](https://www.youtube.com/watch?v=MQ6fFDwjuco) — A Data Odyssey, tiếng Anh. Giới thiệu trực quan phương pháp quy kết giá trị SHAP được trình bày ở các bài sau.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Explainable AI explained!&lt;/td&gt;
          &lt;td&gt;#3 LIME](https://www.youtube.com/watch?v=d6j6bofhj2M) — DeepFindr, tiếng Anh. Giải thích LIME — phương pháp xây dựng mô hình thay thế cục bộ đặt cạnh SHAP.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>23-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter23/23_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter23/23_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Khi bạn chạy một mô hình 8B hay 32B ngay trên chiếc máy tính cá nhân bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;llama.cpp&lt;/code&gt; với định dạng GGUF, hay nhìn máy chủ vLLM phục vụ tốc độ hơn 100 token/giây nhờ &lt;strong&gt;AWQ&lt;/strong&gt; và &lt;strong&gt;Speculative Decoding&lt;/strong&gt;, bạn đang tận hưởng thành quả của làn sóng nén LLM bùng nổ giai đoạn 2022–2026. Bài cập nhật này giải mã cơ chế giúp lượng tử hóa 4-bit không đánh mất trí thông minh và cách giải mã suy đoán tăng tốc sinh văn bản mà &lt;strong&gt;giữ nguyên 100% phân phối xác suất đầu ra&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-công-nghệ-tối-ưu-suy-luận-llm-thực-chiến-20222026&quot;&gt;Kiến thức cần nhớ: Bốn công nghệ tối ưu suy luận LLM thực chiến (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;GPTQ (Post-Training Quantization bậc hai):&lt;/strong&gt; Dùng xấp xỉ ma trận Hessian nghịch đảo của sai số tái tạo tầng \(\|W X - \hat{W} X\|_2^2\) để lượng tử hóa từng cột trọng số rồi bù trừ sai số sang các cột còn lại.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;AWQ (Activation-Aware Weight Quantization):&lt;/strong&gt; Phát hiện chỉ khoảng \(1\%\) kênh trọng số tương ứng với &lt;em&gt;kích hoạt đầu vào lớn&lt;/em&gt; mới thực sự quyết định độ chính xác; nhân hệ số bảo vệ cho \(1\%\) kênh nổi bật đó trước khi lượng tử hóa 4-bit.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định dạng GGUF (K-Quants) và QLoRA:&lt;/strong&gt; Phân bổ bit không đồng đều theo khối (group-wise quantization) để chạy tối ưu trên CPU/Apple Silicon (GGUF) hoặc kết hợp tinh chỉnh LoRA trên mô hình 4-bit (QLoRA).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Speculative Decoding (Giải mã suy đoán):&lt;/strong&gt; Dùng mô hình nháp (draft model) siêu nhỏ sinh nhanh \(K\) token, rồi cho mô hình lớn kiểm định song song cả \(K\) token trong &lt;strong&gt;1 lượt xuôi duy nhất&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-hệ-số-tăng-tốc-thực-tế-của-speculative-decoding-với-k--4-token-nháp&quot;&gt;Giải thích: Tính hệ số tăng tốc thực tế của Speculative Decoding với \(K = 4\) token nháp&lt;/h3&gt;

&lt;p&gt;Giả sử mô hình lớn (target) mất \(T_L = 40\text{ ms}\) cho một lượt suy luận (dù xử lý 1 token hay kiểm định song song 5 token vì đang nghẽn băng thông đọc trọng số), còn mô hình nháp (draft) mất \(T_D = 4\text{ ms/token}\). Trong mỗi vòng, mô hình nháp sinh \(K = 4\) token và trung bình mô hình lớn chấp nhận \(\bar{a} = 3{,}0\) token (cộng thêm \(1\) token mới sinh từ mô hình lớn tại vị trí cuối = tổng cộng \(4{,}0\) token hợp lệ mỗi vòng).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Thời gian mỗi vòng Speculative Decoding:&lt;/strong&gt;
\(T_{\text{vòng}} = K \cdot T_D + T_L = 4(4\text{ ms}) + 40\text{ ms} = 56\text{ ms}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thời gian trung bình mỗi token:&lt;/strong&gt;
\(\frac{56\text{ ms}}{4{,}0\text{ token}} = 14\text{ ms/token}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hệ số tăng tốc so với giải mã thường (\(40\text{ ms/token}\)):&lt;/strong&gt;
\(\frac{40}{14} \approx 2{,}86\times\text{ nhanh hơn!}\)
Điểm kỳ diệu nhất: nhờ quy tắc chấp nhận–từ chối chuẩn xác (rejection sampling), phân phối xác suất đầu ra &lt;strong&gt;khớp toán học 100%&lt;/strong&gt; với việc chạy nguyên mô hình lớn!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-llm-hiệu-quả--gptq-awq-gguf-và-speculative-decoding&quot;&gt;Tùy chọn: LLM hiệu quả — GPTQ, AWQ, GGUF và Speculative Decoding&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế lý thuyết về cắt tỉa, lượng tử hóa, chưng cất hay kiến trúc MobileNet/EfficientNet trong bài cốt lõi (vốn vẫn quan trọng với CNN và thị giác biên). Nội dung cập nhật hệ thống &lt;strong&gt;tối ưu phục vụ LLM&lt;/strong&gt; giai đoạn 2022–2026.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Công thức lượng tử hóa INT8 cơ bản&lt;/p&gt;

\[w_q = \mathrm{round}\big((w-z)/s\big)\]

&lt;p&gt;vẫn giữ nguyên nguyên lý. Điểm mới nằm ở &lt;strong&gt;lượng tử hóa 4-bit chỉ cho trọng số&lt;/strong&gt; trên mô hình Transformer và các &lt;strong&gt;thuật toán giải mã&lt;/strong&gt; giúp giảm số bước sinh tuần tự.&lt;/p&gt;

&lt;h2 id=&quot;1-lượng-tử-hóa-sau-huấn-luyện-ptq-cho-mô-hình-ngôn-ngữ&quot;&gt;1. Lượng tử hóa sau huấn luyện (PTQ) cho mô hình ngôn ngữ&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.17323&quot;&gt;GPTQ (Frantar et al., 2023)&lt;/a&gt; — phương pháp PTQ dùng thông tin đạo hàm bậc hai theo từng lớp, là nền tảng của nhiều trọng số định dạng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gptq&lt;/code&gt; trên Hugging Face Hub.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2306.00978&quot;&gt;AWQ (Lin et al., 2024)&lt;/a&gt; — lượng tử hóa nhận biết kích hoạt (&lt;em&gt;activation-aware&lt;/em&gt;), bảo vệ các kênh trọng số quan trọng trước khi làm tròn xuống 4-bit.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;GGUF / llama.cpp&lt;/a&gt; — định dạng nén nhiều mức bit (&lt;em&gt;k-quant&lt;/em&gt; như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Q4_K_M&lt;/code&gt;) tối ưu cho suy luận trên CPU và Apple Silicon.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Các phương pháp này bổ sung cho lý thuyết lượng tử hóa tổng quát của chương bằng những công thức và nhân tính toán (&lt;em&gt;kernel&lt;/em&gt;) chuyên biệt cho khối &lt;em&gt;attention&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-cụ-thể&quot;&gt;2. Ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;lora-kết-hợp-lượng-tử-hóa-qlora&quot;&gt;LoRA kết hợp lượng tử hóa (QLoRA)&lt;/h3&gt;

&lt;p&gt;Như đã giới thiệu ở bài tùy chọn Chương 15, QLoRA giữ mô hình gốc ở 4-bit và chỉ huấn luyện các bộ thích ứng (&lt;em&gt;adapter&lt;/em&gt;) 16-bit. Khi triển khai phục vụ, có thể gộp trực tiếp &lt;em&gt;adapter&lt;/em&gt; vào trọng số hoặc hoán đổi nhanh giữa nhiều &lt;em&gt;adapter&lt;/em&gt;, kết hợp lợi ích của cả nén mô hình và học chuyển giao.&lt;/p&gt;

&lt;h3 id=&quot;speculative-decoding&quot;&gt;Speculative Decoding&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Leviathan et al., 2023&lt;/a&gt; sử dụng một mô hình nháp nhỏ để đề xuất nhanh \(K\) token liên tiếp, sau đó mô hình lớn kiểm định song song trong một lượt lan truyền xuôi và chấp nhận tiền tố phù hợp. Kỹ thuật này giảm thời gian suy luận thực tế mà vẫn bảo toàn chính xác phân bố đầu ra \(\pi\) của mô hình lớn, và đã được tích hợp trong vLLM cùng nhiều dịch vụ API.&lt;/p&gt;

&lt;h3 id=&quot;định-tuyến-hỗn-hợp-chuyên-gia-moe&quot;&gt;Định tuyến hỗn hợp chuyên gia (MoE)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2401.04088&quot;&gt;Mixtral (Jiang et al., 2024)&lt;/a&gt; chỉ kích hoạt một tập con các mạng chuyên gia (&lt;em&gt;expert&lt;/em&gt;) cho mỗi token: tổng số tham số lưu trữ lớn hơn nhưng lượng FLOP trên mỗi token tương đương một mô hình dày đặc nhỏ hơn. MoE bổ sung cho nén mô hình theo hướng tận dụng &lt;em&gt;tính thưa khi tính toán&lt;/em&gt; thay vì chỉ giảm số lượng trọng số lưu trữ.&lt;/p&gt;

&lt;h2 id=&quot;3-phần-mềm-phổ-biến&quot;&gt;3. Phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/AutoGPTQ/AutoGPTQ&quot;&gt;AutoGPTQ&lt;/a&gt;, &lt;a href=&quot;https://github.com/mit-han-lab/llm-awq&quot;&gt;mit-han-lab/llm-awq&lt;/a&gt;, &lt;a href=&quot;https://github.com/TimDettmers/bitsandbytes&quot;&gt;bitsandbytes&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;ggerganov/llama.cpp&lt;/a&gt; và &lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vllm-project/vllm&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.17323&quot;&gt;GPTQ (Frantar et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2306.00978&quot;&gt;AWQ (Lin et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Speculative Decoding (Leviathan et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2401.04088&quot;&gt;Mixtral of Experts (Jiang et al., 2024)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-bài-này-bổ-sung-gì-cho-ghi-chú-cốt-lõi&quot;&gt;5. Bài này bổ sung gì cho ghi chú cốt lõi&lt;/h2&gt;

&lt;p&gt;Phần lý thuyết cắt tỉa, chưng cất và MobileNet trong bài cốt lõi vẫn là nền tảng chung. Bài này bổ sung &lt;strong&gt;PTQ chuyên biệt cho LLM, GGUF, speculative decoding và MoE&lt;/strong&gt; — những công cụ cần thiết khi đối tượng triển khai là các mô hình Transformer cỡ 7B–70B tham số.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, tiếng Anh. Giải thích lượng tử hóa sau huấn luyện cho mô hình ngôn ngữ lớn, bám sát trọng tâm của bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[QLoRA: Efficient Finetuning of Quantized LLMs&lt;/td&gt;
          &lt;td&gt;Tim Dettmers](https://www.youtube.com/watch?v=fQirE9N5q_Y) — AMLD Intelligence Summit, tiếng Anh. Tim Dettmers trình bày QLoRA — kỹ thuật tinh chỉnh trực tiếp trên mô hình nền 4-bit.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jrJKRYAdh7I&quot;&gt;Knowledge Distillation: How LLMs train each other&lt;/a&gt; — Julia Turc, tiếng Anh. Giới thiệu chưng cất tri thức như một hướng khác để tạo mô hình triển khai nhỏ gọn hơn.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>23-01 Nén Mô hình và Hiệu quả</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter23/23_01_Model_Compression/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter23/23_01_Model_Compression</id>
   <content type="html">&lt;p&gt;Một phát hiện gây chấn động từ bài báo &lt;em&gt;The Lottery Ticket Hypothesis&lt;/em&gt; cho thấy bên trong một mạng nơ-ron dày đặc hàng triệu tham số thường ẩn giấu một “mạng con trúng số” chỉ chiếm &lt;strong&gt;10–20% số trọng số&lt;/strong&gt; nhưng đạt độ chính xác ngang ngửa mạng đầy đủ! Bài học này đi sâu vào cơ sở toán học của ba trụ cột nén mô hình kinh điển: &lt;strong&gt;Cắt tỉa (Pruning)&lt;/strong&gt;, &lt;strong&gt;Lượng tử hóa đồng đều (Affine/Symmetric Quantization)&lt;/strong&gt; và &lt;strong&gt;Chưng cất tri thức với nhiệt độ \(T\)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cơ-sở-toán-học-của-ba-kỹ-thuật-nén-mô-hình-cốt-lõi&quot;&gt;Kiến thức cần nhớ: Cơ sở toán học của ba kỹ thuật nén mô hình cốt lõi&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Cắt tỉa theo độ lớn và cấu trúc (Magnitude &amp;amp; Structured Pruning):&lt;/strong&gt; Xếp hạng trọng số theo $$&lt;/td&gt;
          &lt;td&gt;w&lt;/td&gt;
          &lt;td&gt;\(hoặc chuẩn\)L_1/L_2\(của bộ lọc, cắt bỏ tỷ lệ\)p$$ rồi tinh chỉnh lại; hiểu sự đánh đổi giữa độ thưa và hiệu suất thực trên nhân CUDA.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lượng tử hóa tuyến tính (Symmetric &amp;amp; Asymmetric Quantization):&lt;/strong&gt; Ánh xạ số thực \(r \in [r_{\min}, r_{\max}]\) sang số nguyên \(q = \text{clip}(\text{round}(r/s) + z,\; q_{\min}, q_{\max})\) cùng quá trình giải lượng tử hóa \(\hat{r} = s(q - z)\), phân biệt PTQ và QAT (dùng Straight-Through Estimator).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chưng cất tri thức (Hinton Knowledge Distillation):&lt;/strong&gt; Làm mềm phân phối Softmax bằng nhiệt độ \(T &amp;gt; 1\) để lộ ra “tri thức ẩn” (&lt;em&gt;dark knowledge&lt;/em&gt;) về độ tương đồng giữa các lớp sai, kết hợp mất mát KL (nhân \(T^2\)) với Cross-Entropy nhãn cứng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập tách biệt chiều sâu (Depthwise Separable Convolution):&lt;/strong&gt; Phân rã phép tích chập \(K \times K \times C_{\text{in}} \times C_{\text{out}}\) thành bước lọc từng kênh rồi trộn \(1 \times 1\) để giảm \(8\text{–}9\times\) số phép tính FLOPs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-lượng-tử-hóa-đối-xứng-int8-và-sai-số-lượng-tử-hóa&quot;&gt;Giải thích: Tính tay một bước lượng tử hóa đối xứng INT8 và sai số lượng tử hóa&lt;/h3&gt;

&lt;p&gt;Xét một vector trọng số thực \(\mathbf{w} = [-0{,}82,\; 0{,}15,\; 1{,}27,\; -0{,}04]\) cần lượng tử hóa đối xứng sang số nguyên có dấu INT8 trong đoạn \([-127, 127]\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính hệ số tỷ lệ (Scale Factor \(s\)):&lt;/strong&gt;
\(s = \frac{\max_i |w_i|}{127} = \frac{1{,}27}{127} = 0{,}01.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lượng tử hóa sang số nguyên (\(q_i = \text{round}(w_i / s)\)):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(-0{,}82 / 0{,}01 = -82\) → \(q_1 = -82\)&lt;/li&gt;
      &lt;li&gt;\(0{,}15 / 0{,}01 = 15\) → \(q_2 = 15\)&lt;/li&gt;
      &lt;li&gt;\(1{,}27 / 0{,}01 = 127\) → \(q_3 = 127\)&lt;/li&gt;
      &lt;li&gt;\(-0{,}04 / 0{,}01 = -4\) → \(q_4 = -4\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giải lượng tử hóa và đo sai số:&lt;/strong&gt; Nếu phần tử thứ nhất là \(-0{,}824\) thì \(\text{round}(-82{,}4) = -82\), giải lượng tử hóa ra \(-82 \times 0{,}01 = -0{,}820\) — sai số tối đa luôn bị chặn bởi \(s/2 = 0{,}005\)! Tuy nhiên, nếu xuất hiện một &lt;strong&gt;giá trị ngoại lai (outlier)&lt;/strong&gt; bằng \(12{,}7\) trong cùng nhóm, \(s\) nhảy vọt lên \(0{,}10\) làm toàn bộ trọng số nhỏ bị làm tròn thô gấp 10 lần — đó chính là lý do các thuật toán lượng tử hóa LLM hiện đại phải xử lý riêng các kênh ngoại lai!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;học-sâu-hiệu-quả-nén-và-tăng-tốc-mô-hình&quot;&gt;Học sâu Hiệu quả: Nén và Tăng tốc Mô hình&lt;/h1&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Khi các mô hình học sâu mở rộng đến hàng tỷ tham số, việc triển khai chúng trên thiết bị hạn chế tài nguyên (điện thoại di động, hệ thống nhúng, thiết bị biên) hoặc phục vụ hàng triệu truy vấn cùng lúc trở nên khó khăn về chi phí và độ trễ. Các kỹ thuật nén mô hình (&lt;em&gt;model compression&lt;/em&gt;) giúp giảm kích thước lưu trữ, mức tiêu thụ bộ nhớ và khối lượng tính toán mà vẫn giữ độ chính xác ở mức chấp nhận được. Bốn nhóm kỹ thuật chính gồm: cắt tỉa (&lt;em&gt;pruning&lt;/em&gt;), lượng tử hóa (&lt;em&gt;quantization&lt;/em&gt;), chưng cất tri thức (&lt;em&gt;knowledge distillation&lt;/em&gt;) và thiết kế kiến trúc hiệu quả.&lt;/p&gt;

&lt;p&gt;Cắt tỉa loại bỏ các tham số hoặc kết nối ít đóng góp, dựa trên nhận xét rằng mạng nơ-ron thường có mức độ dư thừa lớn và vẫn hoạt động tốt sau khi lược bỏ 50–90% trọng số. Cắt tỉa có cấu trúc (&lt;em&gt;structured pruning&lt;/em&gt;) loại bỏ nguyên cả bộ lọc hoặc tầng, dễ mang lại tốc độ thực thi nhanh hơn trên phần cứng thông thường. Cắt tỉa không cấu trúc (&lt;em&gt;unstructured pruning&lt;/em&gt;) xóa từng trọng số riêng lẻ, đạt tỷ lệ nén cao hơn nhưng thường cần thư viện hoặc phần cứng hỗ trợ ma trận thưa để tăng tốc thực tế.&lt;/p&gt;

&lt;p&gt;Lượng tử hóa giảm độ chính xác biểu diễn số học của trọng số và giá trị kích hoạt (chẳng hạn từ số thực 32-bit sang số nguyên 8-bit), giúp giảm 4 lần dung lượng bộ nhớ và tận dụng phép tính số nguyên nhanh hơn trên nhiều bộ xử lý. Lượng tử hóa sau huấn luyện (&lt;em&gt;post-training quantization&lt;/em&gt;, PTQ) áp dụng trực tiếp lên mô hình đã huấn luyện mà không cần huấn luyện lại. Huấn luyện nhận biết lượng tử hóa (&lt;em&gt;quantization-aware training&lt;/em&gt;, QAT) mô phỏng quá trình lượng tử hóa ngay trong vòng lặp huấn luyện để mô hình thích nghi với sai số làm tròn.&lt;/p&gt;

&lt;p&gt;Chưng cất tri thức chuyển giao năng lực từ một mạng “giáo viên” lớn sang một mạng “học sinh” nhỏ hơn bằng cách huấn luyện học sinh khớp với phân bố dự đoán mềm (&lt;em&gt;soft targets&lt;/em&gt;) của giáo viên bên cạnh nhãn gốc. Nhờ học thêm thông tin về độ bất định và sự tương đồng giữa các lớp từ giáo viên, mạng học sinh thường đạt kết quả tốt hơn so với khi chỉ huấn luyện trực tiếp trên nhãn cứng. Với &lt;strong&gt;chưng cất trong kỷ nguyên LLM&lt;/strong&gt; (hạn chế khi khớp logit toàn từ vựng, chưng cất qua dữ liệu tổng hợp và phạm vi sử dụng hợp lệ), xem &lt;strong&gt;Chương 26&lt;/strong&gt;, bài &lt;strong&gt;26-05&lt;/strong&gt;; bài này tập trung vào thiết lập cổ điển với không gian đầu ra cố định.&lt;/p&gt;

&lt;p&gt;Song song với việc nén mô hình có sẵn, các kiến trúc hiệu quả như MobileNet và EfficientNet được thiết kế tối ưu ngay từ đầu nhờ tích chập tách theo chiều sâu (&lt;em&gt;depthwise separable convolution&lt;/em&gt;), tìm kiếm kiến trúc nơ-ron (NAS) và quy tắc mở rộng kích thước cân bằng, đạt độ chính xác cạnh tranh với chi phí tính toán thấp hơn nhiều so với mạng chuẩn.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;h3 id=&quot;cắt-tỉa-pruning&quot;&gt;Cắt tỉa (Pruning)&lt;/h3&gt;

&lt;p&gt;Mức độ quan trọng của tham số \(w\) thường được ước lượng theo một trong hai cách:&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;$$I(w) =&lt;/td&gt;
      &lt;td&gt;w&lt;/td&gt;
      &lt;td&gt;$$ (cắt tỉa theo độ lớn trọng số)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;hoặc&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;$$I(w) = \left&lt;/td&gt;
      &lt;td&gt;w \cdot \frac{\partial \mathcal{L}}{\partial w}\right&lt;/td&gt;
      &lt;td&gt;$$ (xấp xỉ khai triển Taylor bậc nhất)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Các trọng số có \(I(w) &amp;lt; \tau\) (với \(\tau\) là ngưỡng chọn trước) bị loại bỏ, sau đó mô hình được tinh chỉnh lại trên các trọng số còn giữ.&lt;/p&gt;

&lt;h3 id=&quot;lượng-tử-hóa-quantization&quot;&gt;Lượng tử hóa (Quantization)&lt;/h3&gt;

&lt;p&gt;Lượng tử hóa ánh xạ giá trị liên tục sang tập mức rời rạc. Với lượng tử hóa tuyến tính 8-bit không dấu:&lt;/p&gt;

\[w_{\text{quant}} = \text{round}\left(\frac{w - w_{\min}}{w_{\max} - w_{\min}} \cdot 255\right)\]

&lt;p&gt;Khi cần khôi phục giá trị xấp xỉ (giải lượng tử hóa) để tính toán:&lt;/p&gt;

\[w \approx w_{\min} + w_{\text{quant}} \cdot \frac{w_{\max} - w_{\min}}{255}\]

&lt;h3 id=&quot;chưng-cất-tri-thức-knowledge-distillation&quot;&gt;Chưng cất tri thức (Knowledge Distillation)&lt;/h3&gt;

&lt;p&gt;Mạng học sinh tối ưu tổng có trọng số giữa hàm mất mát trên nhãn cứng và hàm mất mát trên phân bố mềm từ giáo viên:&lt;/p&gt;

\[\mathcal{L} = \alpha \mathcal{L}_{\text{hard}}(y, \hat{y}_{\text{student}}) + (1-\alpha) \mathcal{L}_{\text{soft}}(\hat{y}_{\text{teacher}}, \hat{y}_{\text{student}})\]

&lt;p&gt;Phân bố mềm sử dụng tham số nhiệt độ \(T\):&lt;/p&gt;

\[p_i = \frac{\exp(z_i/T)}{\sum_j \exp(z_j/T)}\]

&lt;p&gt;Giá trị \(T\) lớn hơn làm phẳng phân bố xác suất, giúp bộc lộ rõ hơn quan hệ tương đồng giữa các lớp mà giáo viên học được.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và trực giác&lt;/h2&gt;

&lt;p&gt;Xét ví dụ nén mô hình ResNet-50 (khoảng 25 triệu tham số, tương đương khoảng 100 MB ở định dạng FP32 — 4 byte mỗi tham số). Giả sử bước cắt tỉa loại bỏ 60% trọng số có độ lớn nhỏ hơn 0.001 do đóng góp không đáng kể, đưa mô hình xuống còn 10 triệu tham số (40 MB ở FP32) với mức suy giảm độ chính xác rất nhỏ.&lt;/p&gt;

&lt;p&gt;Tiếp theo, lượng tử hóa từ FP32 sang INT8 (1 byte mỗi tham số) giảm bộ nhớ thêm 4 lần: 10 triệu tham số chỉ còn khoảng 10 MB thay vì 40 MB. Kết hợp cắt tỉa và lượng tử hóa giúp giảm dung lượng lưu trữ trọng số từ 100 MB xuống 10 MB — tỷ lệ nén tổng cộng 10 lần.&lt;/p&gt;

&lt;p&gt;Cuối cùng, chưng cất tri thức sang một kiến trúc gọn hơn như MobileNet (4 triệu tham số) giúp mạng học sinh học từ dự đoán mềm của ResNet, đạt 75% độ chính xác thay vì 70% khi chỉ huấn luyện trên nhãn cứng — phần chênh lệch 5% đến từ thông tin phân bố của giáo viên trên các mẫu khó.&lt;/p&gt;

&lt;p&gt;Tổng kết lại, mô hình học sinh 4 triệu tham số ở định dạng INT8 chỉ chiếm khoảng 4 MB (nhỏ hơn 25 lần so với 100 MB FP32 ban đầu), suy luận nhanh hơn nhiều lần và chỉ giảm 3% độ chính xác so với mức 78% của ResNet-50 gốc, đủ gọn để triển khai trực tiếp trên thiết bị di động.&lt;/p&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Pruning example
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;magnitude_prune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sparsity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Remove smallest magnitude weights&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;modules&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;isinstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;or&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;isinstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quantile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sparsity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Quantization
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;quantize_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_bits&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Quantize tensor to num_bits&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;qmin&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;qmax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_bits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;min_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;qmax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;qmin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clamp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;qmin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;qmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_val&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Knowledge distillation
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;distillation_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;teacher_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Combine hard and soft targets&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;hard_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;soft_student&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;soft_teacher&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;teacher_logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;soft_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;kl_div&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;soft_student&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;soft_teacher&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reduction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;batchmean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hard_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;soft_loss&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Nén mô hình gắn liền với tìm kiếm kiến trúc nơ-ron (&lt;em&gt;neural architecture search&lt;/em&gt;, NAS), phương pháp tự động tìm kiếm kiến trúc cân bằng tốt giữa độ chính xác và chi phí tính toán.&lt;/p&gt;

&lt;p&gt;Ngoài ra, cắt tỉa còn liên hệ với &lt;em&gt;giả thuyết vé số&lt;/em&gt; (&lt;em&gt;lottery ticket hypothesis&lt;/em&gt;): một mạng khởi tạo ngẫu nhiên thường chứa sẵn những mạng con mà nếu được huấn luyện lại từ đúng trọng số khởi tạo ban đầu sẽ đạt hiệu năng tương đương mạng đầy đủ.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1506.02626&quot;&gt;“Learning both Weights and Connections for Efficient Neural Networks” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Song Han, Jeff Pool, John Tran, William Dally&lt;br /&gt;
Chứng minh cắt tỉa theo độ lớn trọng số có thể nén AlexNet và VGGNet từ 9 đến 13 lần mà hầu như không giảm độ chính xác.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1503.02531&quot;&gt;“Distilling the Knowledge in a Neural Network” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Geoffrey Hinton, Oriol Vinyals, Jeff Dean&lt;br /&gt;
Đặt nền tảng cho chưng cất tri thức, cho thấy mạng học sinh học hiệu quả hơn khi dùng phân bố mềm của giáo viên thay vì chỉ dùng nhãn cứng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1704.04861&quot;&gt;“MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Andrew Howard et al.&lt;br /&gt;
Sử dụng tích chập tách theo chiều sâu để giảm khối lượng tính toán 8–9 lần so với tích chập tiêu chuẩn trong khi vẫn duy trì độ chính xác tốt cho các ứng dụng thị giác trên thiết bị di động.&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;p&gt;Nén mô hình giúp triển khai học sâu hiệu quả trên thiết bị hạn chế tài nguyên thông qua bốn hướng chính: cắt tỉa (loại bỏ trọng số dư thừa), lượng tử hóa (giảm số bit biểu diễn), chưng cất tri thức (chuyển giao năng lực từ mô hình lớn sang mô hình nhỏ) và thiết kế kiến trúc gọn nhẹ ngay từ đầu. Kết hợp hợp lý các kỹ thuật này có thể giảm mạnh dung lượng bộ nhớ và chi phí suy luận với mức suy giảm độ chính xác nhỏ, hỗ trợ suy luận thời gian thực trên thiết bị biên và tiết kiệm năng lượng tính toán.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Lecture 15&lt;/td&gt;
          &lt;td&gt;Efficient Methods and Hardware for Deep Learning](https://www.youtube.com/watch?v=eZdOkDtYMoo) — Stanford University School of Engineering, tiếng Anh. Trình bày tổng hợp cắt tỉa, lượng tử hóa và các ràng buộc phần cứng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, tiếng Anh. Giải thích cơ chế biểu diễn trọng số ở độ chính xác thấp, bổ sung trực quan cho phần lượng tử hóa.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[2.3 Knowledge Distillation&lt;/td&gt;
          &lt;td&gt;Geoffery Hinton&lt;/td&gt;
          &lt;td&gt;Soft Labels&lt;/td&gt;
          &lt;td&gt;Softmax with Temperature](https://www.youtube.com/watch?v=g1r4Esohw-g) — AI_Snippets, tiếng Anh. Minh họa nhãn mềm và tham số nhiệt độ của Hinton — nội dung chưng cất cổ điển trước khi chuyển sang Chương 26.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>23 Học sâu Hiệu quả</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter23/23_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter23/23_00_Introduction</id>
   <content type="html">&lt;p&gt;Một mô hình 70 tỷ tham số ở độ chính xác FP16 ngốn tới &lt;strong&gt;140 GB VRAM&lt;/strong&gt; — vượt xa cả một chiếc GPU trung tâm dữ liệu cao cấp, huống chi là điện thoại di động hay máy tính xách tay của bạn. Làm thế nào để nén gọn một “gã khổng lồ” như vậy xuống nhỏ hơn 4 lần, chạy nhanh hơn 3 lần mà trí thông minh gần như không suy suyển? Chương &lt;strong&gt;Học sâu Hiệu quả (Efficient Deep Learning)&lt;/strong&gt; mở ra bốn nghệ thuật kỹ thuật biến những mô hình khổng lồ trong phòng thí nghiệm thành sản phẩm chạy mượt ngoài đời thực.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-học-sâu-hiệu-quả-và-nén-mô-hình&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Học sâu Hiệu quả và Nén Mô hình&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cắt tỉa (Pruning):&lt;/strong&gt; Loại bỏ các trọng số hoặc kênh dư thừa gần 0 (giả thuyết &lt;em&gt;Lottery Ticket&lt;/em&gt;), phân biệt rõ cắt tỉa phi cấu trúc (nén tốt nhưng khó tăng tốc GPU) với cắt tỉa có cấu trúc (bỏ hẳn kênh/đầu chú ý).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lượng tử hóa (Quantization):&lt;/strong&gt; Giảm độ rộng bit biểu diễn từ FP32 (32 bit) xuống FP16/BF16, INT8 hay INT4 — cắt giảm trực tiếp băng thông bộ nhớ và tăng tốc nhân ma trận phần cứng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chưng cất tri thức (Knowledge Distillation):&lt;/strong&gt; Huấn luyện mô hình học sinh nhỏ gọn bắt chước phân phối xác suất mềm (soft targets) giàu thông tin từ mô hình thầy khổng lồ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc gọn nhẹ &amp;amp; tăng tốc suy luận (MobileNet, GPTQ/AWQ, Speculative Decoding):&lt;/strong&gt; Tối ưu ngay từ phép tích chập tách biệt chiều sâu (depthwise separable conv) đến giải mã suy đoán cho LLM.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-ước-lượng-nhanh-vram-và-băng-thông-bộ-nhớ-khi-nén-mô-hình-7-tỷ-tham-số-từ-fp32-xuống-int4&quot;&gt;Giải thích: Ước lượng nhanh VRAM và băng thông bộ nhớ khi nén mô hình 7 tỷ tham số từ FP32 xuống INT4&lt;/h3&gt;

&lt;p&gt;Xét một mô hình ngôn ngữ \(7\text{ tỷ}\) tham số chạy trên GPU có băng thông bộ nhớ \(500\text{ GB/giây}\) (trong pha sinh từng token, tốc độ bị giới hạn bởi băng thông đọc trọng số — &lt;em&gt;memory-bandwidth bound&lt;/em&gt;):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;FP32 (4 byte/tham số):&lt;/strong&gt; Dung lượng \(= 7 \times 4 = 28\text{ GB}\) → Thời gian tối thiểu đọc hết trọng số cho 1 token \(= 28 / 500 = 56\text{ ms}\) (tối đa \(\sim 17{,}9\text{ token/giây}\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FP16 / BF16 (2 byte/tham số):&lt;/strong&gt; Dung lượng \(= 14\text{ GB}\) → Thời gian đọc \(= 28\text{ ms}\) (tối đa \(\sim 35{,}7\text{ token/giây}\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;INT4 (0,5 byte/tham số, cộng khoảng 10% hệ số thang đo):&lt;/strong&gt; Dung lượng \(\approx 3{,}85\text{ GB}\) → Thời gian đọc \(\approx 7{,}7\text{ ms}\) (tối đa \(\sim 130\text{ token/giây}\) — &lt;strong&gt;nhanh hơn 7,3 lần&lt;/strong&gt; và chạy gọn trên một chiếc laptop phổ thông!).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Học sâu hiệu quả (&lt;em&gt;efficient deep learning&lt;/em&gt;) tập trung làm cho mô hình nhỏ gọn hơn, chạy nhanh hơn và dễ triển khai hơn. Chương này trình bày các kỹ thuật nén mô hình (&lt;em&gt;model compression&lt;/em&gt; gồm cắt tỉa / &lt;em&gt;pruning&lt;/em&gt;, lượng tử hóa / &lt;em&gt;quantization&lt;/em&gt;, chưng cất tri thức / &lt;em&gt;knowledge distillation&lt;/em&gt;), thiết kế kiến trúc hiệu quả (MobileNet, EfficientNet), tăng tốc phần cứng (GPU, TPU), huấn luyện độ chính xác hỗn hợp (&lt;em&gt;mixed-precision training&lt;/em&gt;) và các chiến lược triển khai trên thiết bị biên lẫn hệ thống sản xuất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần cắt tỉa, lượng tử hóa và chưng cất cổ điển, xem thêm bài &lt;strong&gt;23-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về GPTQ, AWQ, GGUF và &lt;em&gt;speculative decoding&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Liên kết sang chủ đề chưng cất LLM:&lt;/strong&gt; Bài &lt;strong&gt;23-01&lt;/strong&gt; trình bày công thức chưng cất tri thức cổ điển trên tập lớp cố định. Với chưng cất LLM hiện đại (dữ liệu tổng hợp, khớp đặc trưng/logit hộp trắng và bài toán cân nhắc giữa tối ưu phục vụ hay chưng cất), xem &lt;strong&gt;Chương 26&lt;/strong&gt;. &lt;em&gt;Speculative decoding&lt;/em&gt; dưới góc nhìn tối ưu phục vụ nằm ở bài &lt;strong&gt;26-04&lt;/strong&gt;, còn hạch toán FLOP và bộ nhớ KV nằm ở bài &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Lecture 15&lt;/td&gt;
          &lt;td&gt;Efficient Methods and Hardware for Deep Learning](https://www.youtube.com/watch?v=eZdOkDtYMoo) — Stanford University School of Engineering, tiếng Anh. Bài giảng CS231n bao quát các chủ đề chính của chương gồm cắt tỉa, lượng tử hóa và chưng cất.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, tiếng Anh. Giải thích nền tảng lượng tử hóa — kỹ thuật trọng tâm trong bài cập nhật hiện đại của chương.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jrJKRYAdh7I&quot;&gt;Knowledge Distillation: How LLMs train each other&lt;/a&gt; — Julia Turc, tiếng Anh. Trình bày phương pháp chưng cất tri thức thầy–trò và cách áp dụng cho mô hình ngôn ngữ lớn.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>22-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter22/22_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter22/22_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Năm 2024, giải Nobel Hóa học gọi tên đột phá dự đoán cấu trúc protein — và ở trái tim của cuộc cách mạng khoa học đó (từ AlphaFold 2 đến &lt;strong&gt;AlphaFold 3&lt;/strong&gt;) là sự giao thoa giữa &lt;strong&gt;học sâu hình học trên đồ thị&lt;/strong&gt;, &lt;strong&gt;Graph Transformer&lt;/strong&gt; và &lt;strong&gt;mô hình khuếch tán 3D&lt;/strong&gt;. Bài cập nhật này cho thấy GNN hiện đại đã vượt xa khung truyền thông điệp cục bộ để chinh phục từ thiết kế dược phẩm đến đồ thị tri thức (GraphRAG) và hệ thống gợi ý hàng tỷ nút.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-mặt-trận-hiện-đại-của-học-sâu-trên-đồ-thị-20222026&quot;&gt;Kiến thức cần nhớ: Ba mặt trận hiện đại của Học sâu trên Đồ thị (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Graph Transformer (Graphormer, GPS):&lt;/strong&gt; Cho phép mọi cặp đỉnh chú ý trực tiếp tới nhau (giải quyết tắc nghẽn &lt;em&gt;oversquashing&lt;/em&gt; tầm xa) bằng cách nhúng khoảng cách đường đi ngắn nhất và vector riêng Laplacian vào điểm chú ý.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;AlphaFold 3 và học sâu sinh học phân tử:&lt;/strong&gt; Kết hợp khối &lt;em&gt;Pairformer&lt;/em&gt; (cập nhật biểu diễn cặp nguyên tử/axit amin thỏa mãn bất đẳng thức tam giác) với bộ khuếch tán sinh trực tiếp tọa độ 3D của phức hợp protein–DNA–thuốc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GNN quy mô web trong hệ thống gợi ý (PinSage, LightGCN):&lt;/strong&gt; Mô hình hóa tương tác người dùng–sản phẩm thành đồ thị hai phía để lan truyền sở thích bậc cao mà lọc cộng tác cổ điển bỏ sót.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đồ thị tri thức &amp;amp; GraphRAG:&lt;/strong&gt; Kết hợp truy hồi đa bước trên đồ thị thực thể–quan hệ với LLM để trả lời các câu hỏi tổng hợp xuyên suốt hàng nghìn tài liệu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-thiên-lệch-khoảng-cách-đồ-thị-spatial-encoding-trong-graph-transformer&quot;&gt;Giải thích: Tính tay thiên lệch khoảng cách đồ thị (Spatial Encoding) trong Graph Transformer&lt;/h3&gt;

&lt;p&gt;Trong Graphormer (Graph Transformer), điểm chú ý giữa đỉnh \(i\) và đỉnh \(j\) được bổ sung một số hạng thiên lệch học được \(b_{\phi(i, j)}\) phụ thuộc vào &lt;strong&gt;độ dài đường đi ngắn nhất&lt;/strong&gt; \(\phi(i, j)\) giữa hai đỉnh:
\(A_{ij} = \frac{(Q_i \cdot K_j)}{\sqrt{d_k}} + b_{\phi(i, j)}.\)&lt;/p&gt;

&lt;p&gt;Giả sử trên một phân tử mạch thẳng 4 nguyên tử \(1 - 2 - 3 - 4\), tích vô hướng \(\frac{Q_1 \cdot K_j}{\sqrt{d_k}}\) của đỉnh 1 với các đỉnh \(2, 3, 4\) đều bằng \(1{,}0\), còn bảng thiên lệch khoảng cách đã học là \(b_1 = +1{,}2\) (kề trực tiếp), \(b_2 = +0{,}3\) (cách 2 bước), \(b_3 = -0{,}5\) (cách 3 bước).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Điểm chú ý sau khi cộng cấu trúc đồ thị:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Đỉnh 2 (cách 1): \(1{,}0 + 1{,}2 = 2{,}2\)&lt;/li&gt;
      &lt;li&gt;Đỉnh 3 (cách 2): \(1{,}0 + 0{,}3 = 1{,}3\)&lt;/li&gt;
      &lt;li&gt;Đỉnh 4 (cách 3): \(1{,}0 - 0{,}5 = 0{,}5\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất Softmax:&lt;/strong&gt; \(e^{2{,}2} \approx 9{,}03\), \(e^{1{,}3} \approx 3{,}67\), \(e^{0{,}5} \approx 1{,}65\) (tổng \(14{,}35\)) → trọng số lần lượt là \(62{,}9\%\), \(25{,}6\%\) và \(11{,}5\%\).
Nhờ cơ chế này, đỉnh 1 vừa ưu tiên láng giềng gần, vừa &lt;strong&gt;vẫn trực tiếp nhận \(11{,}5\%\) thông tin từ đỉnh 4 chỉ trong 1 tầng duy nhất&lt;/strong&gt; mà không bị nghẽn cổ chai qua đỉnh 2 và 3!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-gnn-sau-truyền-thông-điệp--graph-transformer-và-alphafold-3&quot;&gt;Tùy chọn: GNN sau truyền thông điệp — Graph Transformer và AlphaFold 3&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế lý thuyết về truyền thông điệp, tính bất biến hoán vị hay phép cập nhật GCN. Nội dung bổ sung các mô hình giai đoạn 2022–2025 kết hợp &lt;strong&gt;attention trên đồ thị&lt;/strong&gt; với lớp truyền thông điệp cổ điển, cùng ứng dụng dự đoán cấu trúc sinh học nổi bật ngoài hệ thống gợi ý.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Công thức truyền thông điệp (MPNN):&lt;/p&gt;

\[\mathbf{h}_i^{(t+1)} = \mathrm{UPD}\Big(\mathbf{h}_i^{(t)},\; \mathrm{AGG}_{j\in\mathcal{N}(i)} \mathrm{MSG}(\mathbf{h}_i^{(t)},\mathbf{h}_j^{(t)},e_{ij})\Big)\]

&lt;p&gt;vẫn là nền tảng cốt lõi. Tuy nhiên, nhiều mô hình hiện đại cho phép &lt;strong&gt;mọi nút chú ý trực tiếp đến nhiều nút khác&lt;/strong&gt; (như Graphormer, GraphGPS) khi kích thước đồ thị đủ nhỏ (ví dụ phân tử hoặc protein).&lt;/p&gt;

&lt;h2 id=&quot;1-graph-transformer&quot;&gt;1. Graph Transformer&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2106.05234&quot;&gt;Ying et al., 2021&lt;/a&gt; (Graphormer) và &lt;a href=&quot;https://arxiv.org/abs/2205.12454&quot;&gt;Rampášek et al., 2022&lt;/a&gt; (GraphGPS) bổ sung mã hóa vị trí Laplacian hoặc mã hóa khoảng cách đồ thị để Transformer tôn trọng cấu trúc liên kết. Hướng này hiệu quả trên các đồ thị kích thước nhỏ đến trung bình (như phân tử có vài chục đến vài trăm nút), nhưng không phù hợp với đồ thị mạng xã hội hàng chục triệu nút — nơi kỹ thuật lấy mẫu láng giềng kiểu GraphSAGE trong bài lý thuyết vẫn cần thiết.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-cụ-thể&quot;&gt;2. Ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;alphafold-3&quot;&gt;AlphaFold 3&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://www.nature.com/articles/s41586-024-07487-w&quot;&gt;Abramson et al., 2024&lt;/a&gt; (AlphaFold 3) dự đoán cấu trúc phức hợp sinh học bằng mô-đun &lt;strong&gt;khuếch tán&lt;/strong&gt; trên tọa độ nguyên tử kết hợp với nhánh biểu diễn cặp (&lt;em&gt;pairformer&lt;/em&gt;) kế thừa ý tưởng &lt;em&gt;attention&lt;/em&gt; trên đồ thị từ AlphaFold 2. Đây là ứng dụng tiêu biểu trong khám phá thuốc và sinh học cấu trúc, phát triển từ cùng nền tảng biểu diễn quan hệ cặp.&lt;/p&gt;

&lt;h3 id=&quot;hệ-thống-gợi-ý-và-đồ-thị-tri-thức&quot;&gt;Hệ thống gợi ý và đồ thị tri thức&lt;/h3&gt;

&lt;p&gt;Các hệ thống gợi ý thực tế vẫn sử dụng phổ biến &lt;strong&gt;GNN trên đồ thị hai phía&lt;/strong&gt; hoặc mô hình nhúng &lt;em&gt;two-tower&lt;/em&gt; (như họ PinSage). Các nghiên cứu giai đoạn 2023–2025 thường bổ sung đặc trưng trích xuất từ LLM cho từng nút, trong khi tầng tổng hợp cấu trúc vẫn dựa trên GNN.&lt;/p&gt;

&lt;h3 id=&quot;phần-mềm-phổ-biến&quot;&gt;Phần mềm phổ biến&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/pyg-team/pytorch_geometric&quot;&gt;pyg-team/pytorch_geometric&lt;/a&gt; 2.x — hỗ trợ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransformerConv&lt;/code&gt; và ví dụ GraphGPS.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/dmlc/dgl&quot;&gt;dmlc/dgl&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google-deepmind/alphafold3&quot;&gt;google-deepmind/alphafold3&lt;/a&gt; (mã suy luận phát hành từ 2024).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;3-trích-dẫn-20222026&quot;&gt;3. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.12454&quot;&gt;GraphGPS (Rampášek et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2106.05234&quot;&gt;Graphormer (Ying et al., 2021)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.nature.com/articles/s41586-024-07487-w&quot;&gt;AlphaFold 3 (Abramson et al., 2024)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-bài-này-bổ-sung-gì-cho-ghi-chú-cốt-lõi&quot;&gt;4. Bài này bổ sung gì cho ghi chú cốt lõi&lt;/h2&gt;

&lt;p&gt;Trước hết nên tự cài đặt một lớp truyền thông điệp cơ bản từ bài cốt lõi. Bài này bổ sung &lt;strong&gt;Graph Transformer&lt;/strong&gt; và &lt;strong&gt;AlphaFold 3&lt;/strong&gt; như những ví dụ tiêu biểu ứng dụng ý tưởng của chương trong giai đoạn 2024–2026.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=eGoszzMkGfU&quot;&gt;Graph Neural Networks Explained: A Clear Guide to GNN Basics &amp;amp; Models&lt;/a&gt; — IBM Technology, tiếng Anh. Ôn lại cơ chế truyền thông điệp mà Graph Transformer mở rộng bằng trọng số &lt;em&gt;attention&lt;/em&gt; học được.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=1DmNdMUbDkg&quot;&gt;Message Passing: How Graph Neural Networks Actually Work&lt;/a&gt; — The Synthetic Mind, tiếng Anh. Làm rõ một vòng truyền thông điệp cục bộ để đối chiếu với khối Graph Transformer.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, tiếng Anh. Giải thích cơ chế &lt;em&gt;self-attention&lt;/em&gt; toàn cục khi nút có thể trao đổi thông tin vượt ra ngoài tập láng giềng trực tiếp.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>22-01 Mạng Neuron Đồ thị</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter22/22_01_GNN_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter22/22_01_GNN_Fundamentals</id>
   <content type="html">&lt;p&gt;Điều gì xảy ra nếu trong một mạng xã hội, ta chỉ đơn giản lấy &lt;em&gt;tổng&lt;/em&gt; đặc trưng của mọi bạn bè để cập nhật biểu diễn của một người dùng? Một ngôi sao có 10 triệu người theo dõi sẽ có vector lớn gấp triệu lần người bình thường, khiến kích hoạt bùng nổ! Bài học nền tảng này giải phẫu cách &lt;strong&gt;GCN&lt;/strong&gt; giải quyết bài toán đó bằng chuẩn hóa đối xứng \(\tilde{D}^{-1/2}\tilde{A}\tilde{D}^{-1/2}\), cách &lt;strong&gt;GAT&lt;/strong&gt; dùng cơ chế chú ý học trọng số cạnh, và hiện tượng &lt;strong&gt;Oversmoothing&lt;/strong&gt; khi xếp quá nhiều tầng GNN.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cơ-sở-toán-học-của-gcn-gat-và-các-hiện-tượng-đặc-thù-trên-đồ-thị&quot;&gt;Kiến thức cần nhớ: Cơ sở toán học của GCN, GAT và các hiện tượng đặc thù trên đồ thị&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập đồ thị chuẩn hóa (GCN — Kipf &amp;amp; Welling):&lt;/strong&gt; Bổ sung vòng khuyên tự nối \(\tilde{A} = A + I\) để đỉnh giữ lại đặc trưng chính nó, rồi chuẩn hóa hai đầu theo căn bậc hai bậc đỉnh \(\tilde{D}^{-1/2}\tilde{A}\tilde{D}^{-1/2} H W\) giúp ổn định thang độ lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Graph Attention Networks (GAT):&lt;/strong&gt; Tính trọng số chú ý \(\alpha_{ij} = \text{softmax}_j(\text{LeakyReLU}(\mathbf{a}^\top[W\mathbf{h}_i \| W\mathbf{h}_j]))\) cho phép đỉnh chủ động ưu tiên các láng giềng liên quan nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ba cấp độ tác vụ trên đồ thị:&lt;/strong&gt; Phân loại đỉnh (node classification), dự đoán cạnh (link prediction), và phân loại toàn đồ thị (graph classification qua phép gộp readout toàn cục).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiện tượng quá mịn (Oversmoothing):&lt;/strong&gt; Khi xếp quá nhiều tầng (thường \(&amp;gt; 4\text{–}6\) tầng GCN thuần), việc lấy trung bình lặp đi lặp lại làm mọi vector đỉnh hội tụ về cùng một giá trị, xóa nhòa sự khác biệt giữa các lớp.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-truyền-thông-điệp-gcn-chuẩn-hóa-đối-xứng-cho-đỉnh-trung-tâm&quot;&gt;Giải thích: Tính tay một bước truyền thông điệp GCN chuẩn hóa đối xứng cho đỉnh trung tâm&lt;/h3&gt;

&lt;p&gt;Xét đồ thị đường thẳng \(1 - 2 - 3\) với đặc trưng vô hướng ban đầu \(h_1 = 2{,}0\), \(h_2 = 4{,}0\), \(h_3 = 6{,}0\) và trọng số tuyến tính \(W = 1\) (bỏ qua ReLU vì các số đều dương).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Thêm vòng khuyên tự nối (\(\tilde{A} = A + I\)):&lt;/strong&gt; Bậc mới của từng đỉnh là \(\tilde{d}_1 = 2\), \(\tilde{d}_2 = 3\), \(\tilde{d}_3 = 2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính giá trị cập nhật cho đỉnh 2&lt;/strong&gt; theo công thức \(h_2&apos; = \sum_{j \in \{1,2,3\}} \frac{1}{\sqrt{\tilde{d}_2 \tilde{d}_j}} h_j\):
    &lt;ul&gt;
      &lt;li&gt;Đóng góp từ đỉnh 1: \(\frac{1}{\sqrt{3 \times 2}} \cdot 2{,}0 = \frac{2{,}0}{2{,}4495} \approx 0{,}8165\).&lt;/li&gt;
      &lt;li&gt;Đóng góp từ chính đỉnh 2: \(\frac{1}{\sqrt{3 \times 3}} \cdot 4{,}0 = \frac{4{,}0}{3} \approx 1{,}3333\).&lt;/li&gt;
      &lt;li&gt;Đóng góp từ đỉnh 3: \(\frac{1}{\sqrt{3 \times 2}} \cdot 6{,}0 = \frac{6{,}0}{2{,}4495} \approx 2{,}4495\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng hợp:&lt;/strong&gt; \(h_2&apos; \approx 0{,}8165 + 1{,}3333 + 2{,}4495 = 4{,}5993\).
Nhận xét: Trọng số chia đều theo bậc của &lt;em&gt;cả đỉnh gửi lẫn đỉnh nhận&lt;/em&gt; (\(\sqrt{\tilde{d}_i \tilde{d}_j}\)) giúp một đỉnh bậc cao không thống trị phép cập nhật của các đỉnh lân cận bậc thấp!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;mạng-nơ-ron-đồ-thị-học-sâu-trên-dữ-liệu-đồ-thị&quot;&gt;Mạng Nơ-ron Đồ thị: Học sâu trên Dữ liệu Đồ thị&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://distill.pub/2021/gnn-intro/graph_neural_network.png&quot; alt=&quot;Graph Neural Network&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc mạng nơ-ron đồ thị với cơ chế truyền thông điệp. Nguồn: Distill.pub&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Mạng nơ-ron đồ thị (&lt;em&gt;graph neural network&lt;/em&gt;, GNN) mở rộng học sâu sang dữ liệu có cấu trúc đồ thị, giúp mô hình hóa các hệ thống thực thể và quan hệ phổ biến trong thực tế: mạng xã hội kết nối người dùng, đồ thị phân tử kết nối các nguyên tử, đồ thị tri thức liên kết khái niệm, mạng trích dẫn giữa các bài báo, hay hệ thống gợi ý kết nối người dùng với sản phẩm. Khác với ảnh (lưới 2D đều đặn) hoặc chuỗi (dãy 1D có thứ tự), đồ thị có cấu trúc tùy ý — số lượng láng giềng thay đổi theo từng nút, không có thứ tự không gian cố định và sơ đồ kết nối phức tạp — đòi hỏi các kiến trúc chuyên biệt vừa tận dụng được cấu trúc đồ thị vừa khả vi để huấn luyện bằng lan truyền ngược.&lt;/p&gt;

&lt;p&gt;Yêu cầu cơ bản nhất đối với mô hình học trên đồ thị là tính bất biến hoán vị (&lt;em&gt;permutation invariance&lt;/em&gt;): biểu diễn của đồ thị không được thay đổi khi ta đổi thứ tự đánh số các nút. Dù đánh số nút là 1, 2, 3 hay 3, 2, 1, đồ thị vẫn không đổi nên kết quả biểu diễn phải nhất quán. Điều này khiến việc đưa thẳng ma trận kề vào một mạng nơ-ron truyền thống trở nên không phù hợp, vì mạng sẽ xem các hoán vị khác nhau là các đầu vào khác nhau. GNN giải quyết vấn đề này bằng cơ chế truyền thông điệp (&lt;em&gt;message passing&lt;/em&gt;): qua từng tầng, mỗi nút tổng hợp thông tin từ các láng giềng bằng những phép toán bất biến hoán vị (như tổng, trung bình hoặc cực đại) kết hợp biến đổi học được. Sau \(k\) vòng lặp, biểu diễn của mỗi nút sẽ tích hợp thông tin từ vùng lân cận trong phạm vi \(k\) bước (&lt;em&gt;k-hop neighborhood&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Các bài toán học trên đồ thị thường chia thành ba nhóm chính theo mức độ đầu ra: phân loại nút (&lt;em&gt;node classification&lt;/em&gt;) dự đoán nhãn cho từng nút (như phân loại người dùng trên mạng xã hội); dự đoán cạnh (&lt;em&gt;link prediction&lt;/em&gt;) ước lượng khả năng tồn tại của các liên kết còn thiếu hoặc phát sinh trong tương lai (như gợi ý kết bạn hay sản phẩm); và phân loại đồ thị (&lt;em&gt;graph classification&lt;/em&gt;) gán nhãn cho cả đồ thị (như dự đoán hoạt tính sinh học của một phân tử thuốc). Cả ba tác vụ đều dùng chung khung truyền thông điệp nhưng khác nhau ở bước tổng hợp và đầu ra dự đoán.&lt;/p&gt;

&lt;p&gt;GNN được ứng dụng trong nhiều lĩnh vực: trong hóa học để dự đoán độ tan hoặc độc tính của phân tử; trong mạng xã hội để phát hiện cộng đồng và tìm người dùng có ảnh hưởng; trong hệ thống gợi ý trên đồ thị hai phía (người dùng – sản phẩm); trong sinh học cấu trúc để mô hình hóa tương tác giữa các axit amin; và trong giao thông để dự báo lưu lượng dựa trên mạng lưới đường bộ.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Một đồ thị \(\mathcal{G} = (\mathcal{V}, \mathcal{E})\) gồm tập nút \(\mathcal{V} = \{v_1, \ldots, v_n\}\) và tập cạnh \(\mathcal{E} \subseteq \mathcal{V} \times \mathcal{V}\). Mỗi nút có vectơ đặc trưng \(\mathbf{x}_i \in \mathbb{R}^d\), và mỗi cạnh có thể kèm đặc trưng \(\mathbf{e}_{ij}\). Ma trận kề \(\mathbf{A} \in \{0,1\}^{n \times n}\) mã hóa cấu trúc kết nối: \(A_{ij} = 1\) nếu \((v_i, v_j) \in \mathcal{E}\) và bằng 0 trong trường hợp ngược lại.&lt;/p&gt;

&lt;h3 id=&quot;khung-truyền-thông-điệp-message-passing&quot;&gt;Khung truyền thông điệp (Message Passing)&lt;/h3&gt;

&lt;p&gt;GNN cập nhật biểu diễn của các nút qua nhiều tầng truyền thông điệp. Tại tầng \(k\), biểu diễn \(\mathbf{h}_i^{(k)}\) của nút \(i\) được cập nhật từ trạng thái trước đó của chính nó và của các láng giềng:&lt;/p&gt;

\[\mathbf{h}_i^{(k)} = \text{UPDATE}^{(k)}\left(\mathbf{h}_i^{(k-1)}, \text{AGGREGATE}^{(k)}\left(\{\mathbf{h}_j^{(k-1)} : j \in \mathcal{N}(i)\}\right)\right)\]

&lt;p&gt;trong đó \(\mathcal{N}(i)\) là tập các nút láng giềng của \(i\). Hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AGGREGATE&lt;/code&gt; gom thông tin từ láng giềng (phải bất biến hoán vị), còn hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UPDATE&lt;/code&gt; kết hợp đặc trưng hiện tại của nút \(i\) với thông tin đã gom được.&lt;/p&gt;

&lt;h3 id=&quot;graph-convolutional-networks-gcn&quot;&gt;Graph Convolutional Networks (GCN)&lt;/h3&gt;

&lt;p&gt;GCN xuất phát từ lý thuyết đồ thị phổ, định nghĩa phép tích chập thông qua ma trận Laplacian của đồ thị. Dạng cập nhật thực hành theo từng tầng là:&lt;/p&gt;

\[\mathbf{H}^{(k+1)} = \sigma(\tilde{\mathbf{D}}^{-1/2}\tilde{\mathbf{A}}\tilde{\mathbf{D}}^{-1/2}\mathbf{H}^{(k)}\mathbf{W}^{(k)})\]

&lt;p&gt;trong đó \(\tilde{\mathbf{A}} = \mathbf{A} + \mathbf{I}\) là ma trận kề có bổ sung vòng tự nối (&lt;em&gt;self-loop&lt;/em&gt;), \(\tilde{\mathbf{D}}\) là ma trận bậc tương ứng, \(\mathbf{H}^{(k)}\) là ma trận biểu diễn nút ở tầng \(k\), và \(\mathbf{W}^{(k)}\) là ma trận trọng số cần học. Phép toán này tính trung bình có trọng số các láng giềng (nút có bậc càng cao thì đóng góp trên mỗi cạnh càng giảm nhờ hệ số chuẩn hóa) rồi áp dụng phép biến đổi tuyến tính và hàm kích hoạt phi tuyến.&lt;/p&gt;

&lt;h3 id=&quot;graphsage&quot;&gt;GraphSAGE&lt;/h3&gt;

&lt;p&gt;GraphSAGE lấy mẫu một tập láng giềng có kích thước cố định và áp dụng hàm tổng hợp học được:&lt;/p&gt;

\[\mathbf{h}_{\mathcal{N}(i)}^{(k)} = \text{AGGREGATE}(\{\mathbf{h}_j^{(k-1)} : j \in \mathcal{N}(i)\})\]

\[\mathbf{h}_i^{(k)} = \sigma(\mathbf{W}^{(k)} \cdot [\mathbf{h}_i^{(k-1)}, \mathbf{h}_{\mathcal{N}(i)}^{(k)}])\]

&lt;p&gt;Hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AGGREGATE&lt;/code&gt; có thể là trung bình (&lt;em&gt;mean&lt;/em&gt;), cực đại (&lt;em&gt;max&lt;/em&gt;) hoặc LSTM trên tập láng giềng. Cách lấy mẫu này cho phép huấn luyện theo &lt;em&gt;mini-batch&lt;/em&gt; và xử lý hiệu quả các đồ thị lớn có số láng giềng biến thiên mạnh.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và trực giác&lt;/h2&gt;

&lt;p&gt;Xét bài toán phân loại nút trên một mạng xã hội: mỗi nút là một người dùng (có đặc trưng tuổi, vị trí, sở thích), mỗi cạnh là quan hệ bạn bè, và mục tiêu là dự đoán ai sẽ quan tâm đến một sản phẩm mới.&lt;/p&gt;

&lt;p&gt;Với một GNN 2 tầng, ban đầu \(\mathbf{h}_i^{(0)}\) chỉ chứa đặc trưng cá nhân của người dùng \(i\). Sau tầng thứ nhất, \(\mathbf{h}_i^{(1)}\) tích hợp thêm thông tin từ bạn bè trực tiếp (láng giềng 1 bước) — chẳng hạn phản ánh rằng nhóm bạn của người dùng A phần lớn ở độ tuổi 25–30, sống tại đô thị và quan tâm công nghệ. Sau tầng thứ hai, \(\mathbf{h}_i^{(2)}\) tiếp tục tổng hợp thông tin từ bạn của bạn (vùng lân cận 2 bước), nắm bắt ngữ cảnh cộng đồng rộng hơn. Nhờ kết hợp cả thuộc tính cá nhân lẫn cấu trúc lân cận, mô hình dự đoán chính xác hơn so với việc chỉ dựa vào hồ sơ riêng lẻ của từng người dùng.&lt;/p&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GCNLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single Graph Convolutional Layer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Parameter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xavier_uniform_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (num_nodes, in_features)
        adj: (num_nodes, num_nodes) adjacency matrix
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Add self-loops
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;adj_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Normalize
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;deg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;deg_inv_sqrt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;deg_inv_sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deg_inv_sqrt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;inf&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;diag&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deg_inv_sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;adj_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Apply convolution
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;support&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;support&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GCN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2-layer Graph Convolutional Network&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gc1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GCNLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gc2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GCNLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_nodes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;gcn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GCN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Random graph
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Symmetric
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gcn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GCN output: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (100, 7)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Each node gets class predictions using graph structure!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;GNN liên hệ mật thiết với lý thuyết đồ thị phổ (&lt;em&gt;spectral graph theory&lt;/em&gt;). Ma trận Laplacian và phép phân rã trị riêng cung cấp cơ sở toán học để mở rộng phép tích chập từ lưới đều trong CNN sang cấu trúc đồ thị tùy ý.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1609.02907&quot;&gt;“Semi-Supervised Classification with Graph Convolutional Networks” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Thomas Kipf, Max Welling&lt;br /&gt;
Giới thiệu GCN cho bài toán phân loại nút bán giám sát, kết hợp cấu trúc đồ thị với số lượng nhãn hạn chế.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.02216&quot;&gt;“Inductive Representation Learning on Large Graphs” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: William Hamilton, Rex Ying, Jure Leskovec&lt;br /&gt;
GraphSAGE dùng kỹ thuật lấy mẫu lân cận để huấn luyện &lt;em&gt;mini-batch&lt;/em&gt; trên đồ thị lớn, mở rộng GNN từ thiết lập chuyển dẫn (&lt;em&gt;transductive&lt;/em&gt; — đồ thị cố định) sang quy nạp (&lt;em&gt;inductive&lt;/em&gt; — tổng quát hóa sang nút và đồ thị chưa từng gặp).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1710.10903&quot;&gt;“Graph Attention Networks” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Petar Veličković, Guillem Cucurull, Arantxa Casanova, Adriana Romero, Pietro Liò, Yoshua Bengio&lt;br /&gt;
GAT áp dụng cơ chế &lt;em&gt;attention&lt;/em&gt; để học trọng số đóng góp khác nhau cho từng láng giềng thay vì dùng trọng số cố định theo bậc nút.&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;Bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;p&gt;Hiện tượng làm mịn quá mức (&lt;em&gt;oversmoothing&lt;/em&gt;) dễ xảy ra khi xếp quá nhiều tầng GNN: biểu diễn của các nút dần trở nên giống nhau và mất khả năng phân biệt do tổng hợp thông tin từ vùng lân cận quá rộng. Có thể giảm thiểu bằng cách thêm kết nối tắt (&lt;em&gt;skip connection&lt;/em&gt;), chuẩn hóa và giữ độ sâu vừa phải (thường 2–3 tầng là đủ cho nhiều bài toán).&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;p&gt;Mạng nơ-ron đồ thị xử lý dữ liệu dạng đồ thị bằng cơ chế truyền thông điệp, cập nhật biểu diễn từng nút qua các phép tổng hợp láng giềng bất biến hoán vị. GCN sử dụng ma trận kề chuẩn hóa cho tích chập đồ thị, GraphSAGE lấy mẫu lân cận để mở rộng quy mô, còn GAT học trọng số láng giềng bằng &lt;em&gt;attention&lt;/em&gt;. GNN giúp áp dụng học sâu lên dữ liệu quan hệ không đều đặn — nơi CNN và RNN truyền thống không phù hợp — phục vụ các bài toán trên mạng xã hội, phân tử, đồ thị tri thức và hệ thống gợi ý.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=eGoszzMkGfU&quot;&gt;Graph Neural Networks Explained: A Clear Guide to GNN Basics &amp;amp; Models&lt;/a&gt; — IBM Technology, tiếng Anh. Minh họa nút, cạnh và phép cập nhật bất biến hoán vị trong GNN.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=1DmNdMUbDkg&quot;&gt;Message Passing: How Graph Neural Networks Actually Work&lt;/a&gt; — The Synthetic Mind, tiếng Anh. Giải thích chi tiết bước tổng hợp thông tin từ láng giềng tương ứng với công thức trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Linear transformations and matrices&lt;/td&gt;
          &lt;td&gt;Chapter 3, Essence of linear algebra](https://www.youtube.com/watch?v=kYB8IZa5AuE) — 3Blue1Brown, tiếng Anh. Ôn lại ý nghĩa hình học của phép nhân ma trận tuyến tính áp dụng ngay sau bước tổng hợp láng giềng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>22 Mạng Neuron Đồ thị</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter22/22_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter22/22_00_Introduction</id>
   <content type="html">&lt;p&gt;Ảnh là lưới điểm ảnh đều đặn, văn bản là chuỗi từ một chiều thẳng hàng — nhưng thế giới tự nhiên lại hiếm khi ngăn nắp như vậy: một phân tử thuốc là mạng lưới nguyên tử nối nhau theo liên kết hóa học, một mạng xã hội là chằng chịt hàng tỷ mối quan hệ, còn bản đồ giao thông là đồ thị ngã tư có trọng số. Nếu ta cố ép một đồ thị thành mảng 1D hay ma trận cố định, chỉ cần đánh số lại thứ tự các đỉnh là toàn bộ đầu vào thay đổi! &lt;strong&gt;Mạng Nơ-ron Đồ thị (GNN)&lt;/strong&gt; ra đời để học trực tiếp trên cấu trúc liên kết bất biến theo hoán vị đó.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-mạng-nơ-ron-đồ-thị-gnn&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Mạng Nơ-ron Đồ thị (GNN)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tính bất biến và đẳng biến hoán vị (Permutation Invariance/Equivariance):&lt;/strong&gt; Mọi phép toán trên đồ thị phải cho kết quả không phụ thuộc vào thứ tự đánh chỉ số đỉnh, nhờ các phép gộp đối xứng (tổng, trung bình, cực đại).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khung truyền thông điệp (Message Passing Neural Networks):&lt;/strong&gt; Mỗi đỉnh cập nhật biểu diễn của mình qua ba bước: tạo thông điệp từ láng giềng, tổng hợp thông điệp, và cập nhật trạng thái — sau \(K\) tầng, mỗi đỉnh “nhìn” được vùng lân cận bán kính \(K\) bước.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ba kiến trúc kinh điển — GCN, GraphSAGE, GAT:&lt;/strong&gt; Lần lượt mở rộng từ tích chập chuẩn hóa bậc đỉnh (GCN), lấy mẫu láng giềng quy mô lớn (GraphSAGE), đến cơ chế chú ý gán trọng số động cho từng cạnh (GAT).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đồ thị hiện đại (Graph Transformer &amp;amp; AlphaFold 3):&lt;/strong&gt; Khắc phục hiện tượng quá mịn (&lt;em&gt;oversmoothing&lt;/em&gt;) và thắt cổ chai (&lt;em&gt;oversquashing&lt;/em&gt;) bằng chú ý toàn cục kèm mã hóa cấu trúc hình học 3D.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-biểu-diễn-đồ-thị-bằng-ma-trận-kề-a-và-ý-nghĩa-của-lũy-thừa-a2&quot;&gt;Giải thích: Biểu diễn đồ thị bằng ma trận kề \(A\) và ý nghĩa của lũy thừa \(A^2\)&lt;/h3&gt;

&lt;p&gt;Xét đồ thị vô hướng 3 đỉnh dạng đường thẳng \(1 - 2 - 3\) (đỉnh 2 nối với 1 và 3; đỉnh 1 và 3 không nối trực tiếp). Ma trận kề là:
\(A = \begin{pmatrix} 0 &amp;amp; 1 &amp;amp; 0 \\ 1 &amp;amp; 0 &amp;amp; 1 \\ 0 &amp;amp; 1 &amp;amp; 0 \end{pmatrix}.\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính \(A^2\):&lt;/strong&gt;
\(A^2 = \begin{pmatrix} 1 &amp;amp; 0 &amp;amp; 1 \\ 0 &amp;amp; 2 &amp;amp; 0 \\ 1 &amp;amp; 0 &amp;amp; 1 \end{pmatrix}.\)
Phần tử \((A^2)_{1,3} = 1\) cho biết có đúng &lt;strong&gt;1 đường đi độ dài 2&lt;/strong&gt; nối đỉnh 1 sang đỉnh 3 (qua đỉnh 2); còn \((A^2)_{2,2} = 2\) là bậc của đỉnh 2.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trực giác nhiều tầng GNN:&lt;/strong&gt; 1 tầng GNN nhân với \(A\) chỉ truyền tin giữa láng giềng trực tiếp (đỉnh 1 chỉ thấy đỉnh 2). Sau 2 tầng GNN (tương ứng tích \(A^2\)), thông tin từ đỉnh 3 đã lan qua đỉnh 2 để chạm tới đỉnh 1 — giải thích vì sao chiều sâu \(K\) của GNN chính là bán kính trường tiếp nhận trên đồ thị!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mạng nơ-ron đồ thị (&lt;em&gt;graph neural network&lt;/em&gt;, GNN) mở rộng học sâu sang dữ liệu có cấu trúc đồ thị như mạng xã hội, phân tử hóa học, đồ thị tri thức và hệ thống gợi ý. Chương này trình bày cách biểu diễn đồ thị, cơ chế truyền thông điệp (&lt;em&gt;message passing&lt;/em&gt;), các kiến trúc Graph Convolutional Network (GCN), GraphSAGE, Graph Attention Network (GAT) cùng các tác vụ phân loại nút, dự đoán cạnh và sinh đồ thị.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần truyền thông điệp, xem thêm bài &lt;strong&gt;22-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về Graph Transformer và AlphaFold 3.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=eGoszzMkGfU&quot;&gt;Graph Neural Networks Explained: A Clear Guide to GNN Basics &amp;amp; Models&lt;/a&gt; — IBM Technology, tiếng Anh. Giới thiệu tổng quan mạng nơ-ron đồ thị và cơ chế truyền thông điệp dọc theo các cạnh.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=1DmNdMUbDkg&quot;&gt;Message Passing: How Graph Neural Networks Actually Work&lt;/a&gt; — The Synthetic Mind, tiếng Anh. Phân tích chi tiết từng bước của một vòng truyền thông điệp trong GNN.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>21-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter21/21_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter21/21_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Nếu phải chọn một ứng dụng đã đưa Học Tăng cường Sâu lên trang nhất toàn cầu trong giai đoạn 2022–2026, đó chắc chắn là &lt;strong&gt;hậu huấn luyện Mô hình Ngôn ngữ Lớn&lt;/strong&gt;: từ &lt;strong&gt;RLHF với PPO&lt;/strong&gt; giúp ChatGPT biết đối thoại hữu ích và an toàn, sang &lt;strong&gt;DPO&lt;/strong&gt; loại bỏ hoàn toàn mô hình phần thưởng, và mới nhất là &lt;strong&gt;GRPO&lt;/strong&gt; (Group Relative Policy Optimization) đánh thức năng lực tự suy luận chuỗi tư duy (Chain-of-Thought) trên các bài toán toán học và lập trình khó!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-tiến-hóa-ba-thế-hệ-hậu-huấn-luyện-llm-bằng-deep-rl-20222026&quot;&gt;Kiến thức cần nhớ: Tiến hóa ba thế hệ hậu huấn luyện LLM bằng Deep RL (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;RLHF với PPO:&lt;/strong&gt; Huấn luyện Reward Model từ cặp sở thích người dùng (mô hình Bradley–Terry), rồi dùng PPO tối ưu LLM đồng thời giữ gần mô hình tham chiếu qua phạt \(\beta D_{\text{KL}}(\pi_\theta \| \pi_{\text{ref}})\) — mạnh nhưng tốn 4 bản sao mô hình trong VRAM.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;DPO (Direct Preference Optimization):&lt;/strong&gt; Biến đổi giải tích nghiệm tối ưu của bài toán RLHF có ràng buộc KL để tối ưu trực tiếp trên dữ liệu cặp \((y_w, y_l)\) bằng hàm loss giống cross-entropy mà không cần Reward Model hay Critic.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GRPO (Group Relative Policy Optimization) &amp;amp; RLVR:&lt;/strong&gt; Sinh một nhóm \(G\) lời giải cho cùng một đề bài, chấm điểm bằng bộ kiểm chứng chính xác (trình biên dịch code, đáp số toán), rồi dùng chuẩn hóa z-score ngay trong nhóm làm Advantage — bỏ hẳn mạng Critic khổng lồ của PPO!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm soát Reward Hacking:&lt;/strong&gt; Cân bằng hệ số KL \(\beta\) và thiết kế phần thưởng kiểm chứng được (verifiable rewards) để mô hình không lách luật bằng cách viết câu trả lời dài dòng sáo rỗng.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-advantage-theo-nhóm-trong-grpo-trên-4-lời-giải-toán&quot;&gt;Giải thích: Tính tay Advantage theo nhóm trong GRPO trên 4 lời giải toán&lt;/h3&gt;

&lt;p&gt;Giả sử cho cùng một bài toán, mô hình sinh ra nhóm \(G = 4\) lời giải và bộ chấm tự động trả về phần thưởng nhị phân (đúng \(= 1\), sai \(= 0\)): \(\mathbf{r} = [1,\; 0,\; 1,\; 0]\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính trung bình và độ lệch chuẩn trong nhóm:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Trung bình: \(\mu_r = \frac{1 + 0 + 1 + 0}{4} = 0{,}50\).&lt;/li&gt;
      &lt;li&gt;Độ lệch chuẩn: \(\sigma_r = \sqrt{\frac{(0{,}5)^2 + (-0{,}5)^2 + (0{,}5)^2 + (-0{,}5)^2}{4}} = \sqrt{0{,}25} = 0{,}50\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính lợi thế tương đối trong nhóm (Group Relative Advantage):&lt;/strong&gt;
\(A_i = \frac{r_i - \mu_r}{\sigma_r + \epsilon} \implies \mathbf{A} = [+1{,}0,\; -1{,}0,\; +1{,}0,\; -1{,}0].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu quả kiến trúc:&lt;/strong&gt; Hai lời giải đúng nhận lực đẩy tăng xác suất \(+1{,}0\), hai lời giải sai nhận lực kéo giảm \(-1{,}0\) — hoàn toàn &lt;strong&gt;không cần huấn luyện một mạng Critic 70 tỷ tham số&lt;/strong&gt; như PPO, tiết kiệm gần một nửa bộ nhớ GPU cho huấn luyện mô hình suy luận!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-rl-sâu-sau-dqnppo--rlhf-dpo-và-grpo&quot;&gt;Tùy chọn: RL sâu sau DQN/PPO — RLHF, DPO và GRPO&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế lý thuyết về DQN, bộ đệm phát lại hay PPO trong bài cốt lõi. Nội dung cập nhật hệ thống &lt;strong&gt;căn chỉnh mô hình ngôn ngữ&lt;/strong&gt; giai đoạn 2022–2026 — lĩnh vực đưa học tăng cường sâu vào ứng dụng rộng rãi ngoài phạm vi trò chơi.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;PPO vẫn tối đa hóa hàm mục tiêu thay thế có cắt ngưỡng. Trong bài toán căn chỉnh mô hình ngôn ngữ, quy trình ban đầu bổ sung &lt;strong&gt;mô hình phần thưởng&lt;/strong&gt;, sau đó nhanh chóng xuất hiện các phương pháp &lt;strong&gt;loại bỏ vòng lặp RL tường minh&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;1-rlhf-với-ppo&quot;&gt;1. RLHF với PPO&lt;/h2&gt;

&lt;p&gt;Theo &lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Ouyang et al., 2022&lt;/a&gt; và &lt;a href=&quot;https://arxiv.org/abs/2204.05862&quot;&gt;Bai et al., 2022&lt;/a&gt; (Anthropic HH), quy trình RLHF gồm ba bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Tinh chỉnh có giám sát (SFT) trên dữ liệu minh họa.&lt;/li&gt;
  &lt;li&gt;Huấn luyện mô hình phần thưởng \(r_\phi\) từ các cặp so sánh ưu tiên của con người.&lt;/li&gt;
  &lt;li&gt;Tối ưu chính sách bằng PPO theo phần thưởng \(r_\phi\) kèm số hạng phạt KL giữ mô hình gần với bản SFT ban đầu.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Đây chính là mô hình &lt;em&gt;actor–critic&lt;/em&gt; của Chương 21 áp dụng lên chuỗi token, nhưng chi phí huấn luyện cao (cần duy trì thêm mô hình giá trị, phải lấy mẫu trực tuyến và dễ mất ổn định).&lt;/p&gt;

&lt;h2 id=&quot;2-dpo-tối-ưu-sở-thích-không-cần-mô-hình-phần-thưởng&quot;&gt;2. DPO: Tối ưu sở thích không cần mô hình phần thưởng&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Rafailov et al., 2023&lt;/a&gt; biến đổi bài toán tối ưu RLHF thành hàm mất mát &lt;strong&gt;phân loại&lt;/strong&gt; trực tiếp trên các cặp phản hồi thắng/thua \((y_w, y_l)\):&lt;/p&gt;

\[\mathcal{L}_{\mathrm{DPO}} = -\log\sigma\Big(\beta\log\frac{\pi_\theta(y_w|x)}{\pi_{\mathrm{ref}}(y_w|x)} - \beta\log\frac{\pi_\theta(y_l|x)}{\pi_{\mathrm{ref}}(y_l|x)}\Big).\]

&lt;p&gt;Phương pháp này không cần vòng lặp lấy mẫu trực tuyến khi huấn luyện. DPO cùng các biến thể (IPO, KTO, ORPO) trở thành công thức căn chỉnh phổ biến trong hệ sinh thái mã nguồn mở giai đoạn 2024–2025 (ví dụ thư viện &lt;a href=&quot;https://github.com/huggingface/trl&quot;&gt;trl&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;3-ứng-dụng-cụ-thể&quot;&gt;3. Ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;grpo-và-huấn-luyện-mô-hình-suy-luận&quot;&gt;GRPO và huấn luyện mô hình suy luận&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2402.03300&quot;&gt;Shao et al., 2024&lt;/a&gt; (DeepSeekMath) đề xuất &lt;strong&gt;Group Relative Policy Optimization (GRPO)&lt;/strong&gt;: với mỗi prompt, mô hình sinh ra một nhóm nhiều câu trả lời rồi ước lượng lợi thế (&lt;em&gt;advantage&lt;/em&gt;) tương đối từ phần thưởng của chính nhóm đó, không cần huấn luyện mạng giá trị (&lt;em&gt;critic&lt;/em&gt;) riêng. Các mô hình suy luận sau đó (như dòng DeepSeek-R1 năm 2025) đã phổ biến hóa hướng tiếp cận này.&lt;/p&gt;

&lt;h3 id=&quot;mô-hình-thế-giới-world-model&quot;&gt;Mô hình thế giới (World Model)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2301.04104&quot;&gt;Hafner et al., 2023&lt;/a&gt; (DreamerV3) học một MDP trong không gian ẩn (kiểu VAE) và lập kế hoạch trực tiếp bên trong mô hình đó. Đây là nhánh bổ sung quan trọng của deep RL ngoài bài toán hội thoại LLM.&lt;/p&gt;

&lt;h3 id=&quot;phần-mềm-phổ-biến&quot;&gt;Phần mềm phổ biến&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/trl&quot;&gt;huggingface/trl&lt;/a&gt; — bộ công cụ huấn luyện PPO, DPO và GRPO.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/OpenRLHF/OpenRLHF&quot;&gt;OpenRLHF&lt;/a&gt; và &lt;a href=&quot;https://github.com/volcengine/verl&quot;&gt;verl&lt;/a&gt; — khung huấn luyện RLHF phân tán.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/vwxyzjn/cleanrl&quot;&gt;CleanRL&lt;/a&gt; và &lt;a href=&quot;https://github.com/DLR-RM/stable-baselines3&quot;&gt;Stable-Baselines3&lt;/a&gt; — thư viện deep RL cổ điển (ngoài LLM).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;InstructGPT (Ouyang et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;DPO (Rafailov et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2402.03300&quot;&gt;DeepSeekMath — GRPO (Shao et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2301.04104&quot;&gt;DreamerV3 (Hafner et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-bài-này-bổ-sung-gì-cho-ghi-chú-cốt-lõi&quot;&gt;5. Bài này bổ sung gì cho ghi chú cốt lõi&lt;/h2&gt;

&lt;p&gt;Trước hết cần nắm vững cơ chế DQN và PPO trong bài cốt lõi. Bài này bổ sung các kỹ thuật &lt;strong&gt;tối ưu theo sở thích cho mô hình ngôn ngữ&lt;/strong&gt; (RLHF, DPO, GRPO), không thay đổi các phương trình Bellman nền tảng. Phần tổng hợp lộ trình căn chỉnh LLM (SFT → mô hình phần thưởng / PPO → DPO) nằm ở bài &lt;strong&gt;26-03&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8jtAzxUwDj0&quot;&gt;Proximal Policy Optimization (PPO) for LLMs Explained Intuitively&lt;/a&gt; — Julia Turc, tiếng Anh. Giải thích trực quan cách PPO được áp dụng trong quy trình RLHF cho mô hình ngôn ngữ lớn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=k2pD3k1485A&quot;&gt;Direct Preference Optimization (DPO) - How to fine-tune LLMs directly without reinforcement learning&lt;/a&gt; — Luis Serrano Academy, tiếng Anh. Trình bày DPO, mục tiêu tối ưu sở thích được đặt cạnh PPO trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qPN_XZcJf_s&quot;&gt;Reinforcement Learning with Human Feedback (RLHF), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa vòng phản hồi con người mà cả PPO và DPO đều hướng tới tối ưu.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>21-01 Học Tăng cường Sâu</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter21/21_01_Deep_RL/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter21/21_01_Deep_RL</id>
   <content type="html">&lt;p&gt;Khi mới ghép mạng nơ-ron vào Q-Learning, các nhà nghiên cứu nhanh chóng gặp một hiện tượng kỳ lạ: mạng học tốt ở vài trăm bước đầu, rồi đột nhiên giá trị Q phình lên vô cực và chính sách sụp đổ hoàn toàn! Lý do? Mục tiêu \(y = r + \gamma \max_{a&apos;} Q_\theta(s&apos;, a&apos;)\) tự chạy theo chính trọng số \(\theta\) đang bị cập nhật — giống như một chú chó đuổi theo chính cái đuôi của mình. Bài học này trình bày trọn vẹn hai dòng thuật toán trụ cột của Deep RL: &lt;strong&gt;DQN&lt;/strong&gt; (Experience Replay, Target Network, Double DQN) và &lt;strong&gt;Policy Gradient / Actor–Critic / PPO&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cơ-chế-toán-học-của-dqn-policy-gradient-và-ppo&quot;&gt;Kiến thức cần nhớ: Cơ chế toán học của DQN, Policy Gradient và PPO&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Experience Replay &amp;amp; Target Network (DQN):&lt;/strong&gt; Lưu bộ bốn \((s, a, r, s&apos;)\) vào bộ đệm để lấy mẫu i.i.d. phá tương quan thời gian, và đóng băng mạng đích \(\theta^-\) trong \(C\) bước giúp mục tiêu TD đứng yên.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Double DQN (tách chọn hành động và đánh giá):&lt;/strong&gt; Dùng mạng online chọn \(a^* = \arg\max_a Q_\theta(s&apos;, a)\) nhưng dùng mạng đích định giá \(Q_{\theta^-}(s&apos;, a^*)\) để triệt tiêu độ lệch ước lượng quá cao (&lt;em&gt;overestimation bias&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định lý Policy Gradient và giảm phương sai bằng Advantage:&lt;/strong&gt; \(\nabla_\theta J(\theta) = \mathbb{E}[\nabla_\theta \log \pi_\theta(a\mid s)\, A(s, a)]\), trong đó trừ đường cơ sở \(V(s)\) không làm lệch kỳ vọng gradient nhưng giảm mạnh dao động.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mục tiêu cắt cụt của PPO (Clipped Surrogate Objective):&lt;/strong&gt; Ràng buộc tỷ số xác suất \(r_t(\theta) = \frac{\pi_\theta(a_t\mid s_t)}{\pi_{\theta_{\text{old}}}(a_t\mid s_t)}\) trong đoạn \([1 - \epsilon, 1 + \epsilon]\) để ngăn một bước cập nhật quá mạnh phá hủy chính sách.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-hàm-mục-tiêu-clipped-ppo-khi-advantage-dương-và-âm&quot;&gt;Giải thích: Tính tay một bước hàm mục tiêu Clipped PPO khi Advantage dương và âm&lt;/h3&gt;

&lt;p&gt;Hàm mục tiêu cắt cụt của PPO tại bước \(t\) với ngưỡng \(\epsilon = 0{,}2\) là:
\(L^{\text{CLIP}}_t(\theta) = \min\Big(r_t(\theta)\hat{A}_t,\; \text{clip}(r_t(\theta), 0{,}8, 1{,}2)\hat{A}_t\Big).\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp 1 — Hành động tốt (\(\hat{A}_t = +2{,}0\)):&lt;/strong&gt; Chính sách mới tăng xác suất hành động này quá mạnh lên \(r_t = 1{,}50\).&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Không cắt: \(1{,}50 \times 2{,}0 = 3{,}00\).&lt;/li&gt;
  &lt;li&gt;Sau khi cắt vào \([0{,}8, 1{,}2]\): \(1{,}20 \times 2{,}0 = 2{,}40\).&lt;/li&gt;
  &lt;li&gt;Lấy \(\min(3{,}00,\; 2{,}40) = 2{,}40\) → hàm mục tiêu đi ngang, &lt;strong&gt;gradient bằng 0&lt;/strong&gt;, ngăn chính sách đẩy xác suất đi quá xa!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp 2 — Hành động xấu (\(\hat{A}_t = -2{,}0\)):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nếu chính sách mới giảm xác suất xuống \(r_t = 0{,}60\): \(\min(0{,}60(-2),\; 0{,}80(-2)) = \min(-1{,}20,\; -1{,}60) = -1{,}60\) (cắt chặn, ngừng phạt thêm).&lt;/li&gt;
  &lt;li&gt;Nếu chính sách mới lại &lt;em&gt;lỡ tăng&lt;/em&gt; xác suất hành động xấu lên \(r_t = 1{,}40\): \(\min(1{,}40(-2),\; 1{,}20(-2)) = \min(-2{,}80,\; -2{,}40) = -2{,}80\) (không bị cắt — vẫn giữ nguyên gradient phạt mạnh để kéo nó quay lại!).&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;học-tăng-cường-sâu-kết-hợp-mạng-nơ-ron-với-ra-quyết-định-tuần-tự&quot;&gt;Học Tăng cường Sâu: Kết hợp Mạng Nơ-ron với Ra quyết định Tuần tự&lt;/h1&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Học tăng cường sâu (&lt;em&gt;deep reinforcement learning&lt;/em&gt;, deep RL) kết hợp khả năng học biểu diễn của mạng nơ-ron sâu với khung ra quyết định tuần tự của học tăng cường, giúp tác tử học hành vi phức tạp trực tiếp từ dữ liệu đầu vào nhiều chiều như hình ảnh hoặc cảm biến thô. Trong khi RL cổ điển thường đòi hỏi trích xuất đặc trưng thủ công và chỉ xử lý tốt không gian trạng thái nhỏ, deep RL học đồng thời cả biểu diễn lẫn chính sách theo kiểu đầu–cuối, mở rộng phạm vi sang các bài toán như chơi trò chơi điện tử từ pixel, điều khiển robot qua camera, chơi cờ vua và cờ vây ở trình độ cao, và học các thao tác vật lý phức tạp qua thử–sai.&lt;/p&gt;

&lt;p&gt;Ý tưởng cốt lõi của deep RL là dùng mạng nơ-ron làm bộ xấp xỉ cho hàm giá trị hoặc chính sách. Thay vì lưu một bảng \(Q(s,a)\) tường minh cho mọi cặp trạng thái–hành động (bất khả thi với không gian trạng thái lớn như khung hình Atari 84×84×4 có tới \(256^{84 \times 84 \times 4} \approx 10^{67000}\) trạng thái khả dĩ), ta xấp xỉ \(Q(s,a) \approx Q(s,a;\theta)\) bằng mạng nơ-ron với tham số \(\theta\). Nhờ khả năng tổng quát hóa của mạng, kiến thức học được ở một trạng thái có thể áp dụng cho các trạng thái tương tự mà không cần duyệt cạn toàn bộ không gian.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, việc kết hợp học sâu với RL nảy sinh nhiều thách thức đặc thù. Thứ nhất, tác tử tự tạo ra dữ liệu huấn luyện qua tương tác, khiến các mẫu liên tiếp có tương quan mạnh và vi phạm giả định độc lập, cùng phân bố (i.i.d.) của huấn luyện mạng nơ-ron chuẩn. Thứ hai, giá trị mục tiêu trong Q-learning thay đổi liên tục theo mạng \(Q\) đang được cập nhật, tạo ra hiện tượng “mục tiêu di chuyển” gây mất ổn định. Thứ ba, sự đánh đổi khám phá–khai thác trở nên nhạy cảm hơn vì hành động hiện tại quyết định trực tiếp dữ liệu tương lai mà tác tử quan sát được.&lt;/p&gt;

&lt;p&gt;Deep Q-Network (DQN) do DeepMind giới thiệu năm 2013 khắc phục hai thách thức đầu tiên bằng hai kỹ thuật quan trọng: &lt;em&gt;experience replay&lt;/em&gt; (phát lại trải nghiệm) và &lt;em&gt;target network&lt;/em&gt; (mạng đích). &lt;em&gt;Experience replay&lt;/em&gt; lưu các tương tác quá khứ vào một bộ đệm và lấy mẫu ngẫu nhiên để huấn luyện, giúp phá vỡ tương quan thời gian và tái sử dụng các trải nghiệm hiếm. &lt;em&gt;Target network&lt;/em&gt; giữ bản sao tham số được cập nhật chậm để cung cấp mục tiêu ổn định, hạn chế dao động khi tối ưu. Nhờ kết hợp các kỹ thuật này, DQN có thể học chơi nhiều trò chơi Atari trực tiếp từ pixel ở mức ngang hoặc vượt người chơi.&lt;/p&gt;

&lt;p&gt;Ứng dụng của deep RL mở rộng ra ngoài phạm vi trò chơi. AlphaGo kết hợp mạng nơ-ron sâu với tìm kiếm cây Monte Carlo (MCTS) để đánh bại nhà vô địch thế giới môn cờ vây. Trong robot học, tác tử học các kỹ năng thao tác phức tạp qua tương tác thử–sai. Trong xử lý ngôn ngữ tự nhiên, học tăng cường từ phản hồi con người (RLHF) được dùng để căn chỉnh mô hình ngôn ngữ theo tiêu chí hữu ích và an toàn. Trong xe tự lái, deep RL hỗ trợ học chính sách điều khiển từ môi trường mô phỏng và dữ liệu thực tế.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Deep Q-Network mở rộng Q-learning sang không gian trạng thái liên tục bằng xấp xỉ hàm nơ-ron \(Q(s,a;\theta)\). Với một bước chuyển trạng thái \((s_t, a_t, r_t, s_{t+1})\), quy tắc cập nhật Q-learning dạng bảng là:&lt;/p&gt;

\[Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha[r_t + \gamma \max_{a&apos;} Q(s_{t+1}, a&apos;) - Q(s_t, a_t)]\]

&lt;p&gt;Khi thay bằng mạng nơ-ron, bài toán trở thành tối thiểu hóa bình phương sai số chênh lệch thời gian (TD error) bằng hạ gradient:&lt;/p&gt;

\[\mathcal{L}(\theta) = \mathbb{E}_{(s,a,r,s&apos;) \sim \mathcal{D}}\left[\left(r + \gamma \max_{a&apos;} Q(s&apos;, a&apos;; \theta^-) - Q(s,a;\theta)\right)^2\right]\]

&lt;p&gt;trong đó \(\mathcal{D}\) là bộ đệm &lt;em&gt;experience replay&lt;/em&gt; và \(\theta^-\) là tham số của &lt;em&gt;target network&lt;/em&gt; (được đồng bộ định kỳ từ \(\theta\)).&lt;/p&gt;

&lt;p&gt;Gradient của hàm mất mát theo \(\theta\) là:&lt;/p&gt;

\[\nabla_\theta \mathcal{L}(\theta) = -2\,\mathbb{E}\left[\left(r + \gamma \max_{a&apos;} Q(s&apos;, a&apos;; \theta^-) - Q(s,a;\theta)\right) \nabla_\theta Q(s,a;\theta)\right]\]

&lt;p&gt;Lưu ý rằng mục tiêu \(r + \gamma \max_{a&apos;} Q(s&apos;, a&apos;; \theta^-)\) được coi là hằng số khi lấy đạo hàm (không lan truyền gradient qua \(\theta^-\)), tránh vòng phản hồi mất ổn định.&lt;/p&gt;

&lt;h3 id=&quot;experience-replay&quot;&gt;Experience Replay&lt;/h3&gt;

&lt;p&gt;Bộ đệm \(\mathcal{D}\) lưu các bộ chuyển trạng thái gần đây \(\mathcal{D} = \{(s_i, a_i, r_i, s_i&apos;)\}_{i=1}^N\) với dung lượng \(N\) (thường từ 100.000 đến 1.000.000). Trong mỗi bước huấn luyện:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Tác tử thực hiện hành động, quan sát chuyển trạng thái và lưu vào \(\mathcal{D}\).&lt;/li&gt;
  &lt;li&gt;Lấy mẫu ngẫu nhiên một &lt;em&gt;mini-batch&lt;/em&gt; từ \(\mathcal{D}\).&lt;/li&gt;
  &lt;li&gt;Tính hàm mất mát và gradient trên &lt;em&gt;mini-batch&lt;/em&gt; đó.&lt;/li&gt;
  &lt;li&gt;Cập nhật \(\theta\) bằng hạ gradient.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Việc lấy mẫu ngẫu nhiên phá vỡ tương quan thời gian giữa các bước liên tiếp và cải thiện hiệu quả sử dụng mẫu vì mỗi trải nghiệm có thể được dùng lại trong nhiều lần cập nhật.&lt;/p&gt;

&lt;h3 id=&quot;target-network&quot;&gt;Target Network&lt;/h3&gt;

&lt;p&gt;Hệ thống duy trì hai mạng có cùng kiến trúc: mạng chính (&lt;em&gt;online network&lt;/em&gt;) \(Q(s,a;\theta)\) cập nhật ở mỗi bước, và &lt;em&gt;target network&lt;/em&gt; \(Q(s,a;\theta^-)\) chỉ sao chép tham số sau mỗi \(C\) bước:&lt;/p&gt;

\[\theta^- \leftarrow \theta \quad \text{every } C \text{ steps}\]

&lt;p&gt;Cơ chế này giữ cố định mục tiêu trong suốt \(C\) bước (thường chọn \(C = 10.000\)), giảm thiểu hiện tượng dao động hoặc phân kỳ khi huấn luyện.&lt;/p&gt;

&lt;h3 id=&quot;phương-pháp-gradient-chính-sách-policy-gradient&quot;&gt;Phương pháp Gradient Chính sách (Policy Gradient)&lt;/h3&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Thay vì học hàm giá trị, ta có thể tham số hóa trực tiếp chính sách $$\pi(a&lt;/td&gt;
      &lt;td&gt;s;\theta)$$ để tối đa hóa tổng phần thưởng chiết khấu kỳ vọng:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\left[\sum_{t=0}^T \gamma^t r_t\right]\]

&lt;p&gt;Theo định lý gradient chính sách:&lt;/p&gt;

\[\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\left[\sum_{t=0}^T \nabla_\theta \log \pi_\theta(a_t|s_t) \cdot G_t\right]\]

&lt;p&gt;trong đó \(G_t = \sum_{k=t}^T \gamma^{k-t} r_k\) là tổng phần thưởng chiết khấu tính từ thời điểm \(t\). Nhờ đó, ta có thể ước lượng gradient bằng cách lấy mẫu các quỹ đạo và nhân log-xác suất của từng hành động với \(G_t\): hành động mang lại lợi ích cao được tăng xác suất, còn hành động kém hiệu quả bị giảm xác suất.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Phương pháp &lt;strong&gt;Actor–Critic&lt;/strong&gt; kết hợp cả hai hướng: &lt;em&gt;actor&lt;/em&gt; (chính sách $$\pi(a&lt;/td&gt;
      &lt;td&gt;s;\theta)\() chọn hành động, còn *critic* (hàm giá trị\)V(s;\phi)$$) đánh giá chất lượng trạng thái. &lt;em&gt;Actor&lt;/em&gt; cập nhật dựa trên hàm lợi thế (&lt;em&gt;advantage&lt;/em&gt;):&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[\nabla_\theta J(\theta) \propto \nabla_\theta \log \pi_\theta(a_t|s_t) \cdot A(s_t, a_t)\]

&lt;p&gt;trong đó \(A(s_t, a_t) = Q(s_t, a_t) - V(s_t)\) đo mức độ vượt trội của hành động \(a_t\) so với mức trung bình tại trạng thái \(s_t\). Trong khi đó, &lt;em&gt;critic&lt;/em&gt; liên tục cập nhật để ước lượng giá trị chính xác hơn, giúp giảm phương sai của gradient cho &lt;em&gt;actor&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và trực giác&lt;/h2&gt;

&lt;p&gt;Xét bài toán huấn luyện tác tử chơi Pong trực tiếp từ pixel. Trạng thái là ảnh xám 84×84 (ghép nhiều khung hình liên tiếp để nắm được vận tốc bóng), hành động gồm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{lên, xuống, đứng yên}&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Ban đầu, tác tử hành động ngẫu nhiên và thỉnh thoảng đỡ trúng bóng, nhận phần thưởng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+1&lt;/code&gt;. DQN cập nhật giá trị \(Q\) cho các trạng thái và hành động dẫn tới kết quả đó: chẳng hạn khi bóng đang bay về phía vợt từ góc trên bên trái, hành động “đi lên” dần có giá trị \(Q\) cao hơn. Sau hàng nghìn ván chơi, mạng học được các quy luật điều khiển:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Bóng ở cao, vợt ở thấp → đi lên có giá trị \(Q\) cao.&lt;/li&gt;
  &lt;li&gt;Bóng ở thấp, vợt ở cao → đi xuống có giá trị \(Q\) cao.&lt;/li&gt;
  &lt;li&gt;Bóng ngang vợt → đứng yên có giá trị \(Q\) cao.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nhờ xử lý chuỗi khung hình chồng nhau, mạng không chỉ nhận biết vị trí hiện tại của bóng mà còn suy ra hướng chuyển động để đón trước. Đồng thời, bộ đệm &lt;em&gt;experience replay&lt;/em&gt; lưu trữ nhiều tình huống khác nhau; việc lấy mẫu ngẫu nhiên giúp mạng tránh hiện tượng quên thảm họa (&lt;em&gt;catastrophic forgetting&lt;/em&gt;) đối với các tình huống ít gặp gần đây.&lt;/p&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;

&lt;p&gt;Ví dụ cài đặt tác tử DQN với &lt;em&gt;experience replay&lt;/em&gt; và &lt;em&gt;target network&lt;/em&gt;:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;collections&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;deque&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DQN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Deep Q-Network for Atari-style games.
    
    Architecture: Conv layers extract features from frames,
    fully connected layers output Q-values for each action.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DQN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Input: (batch, 4, 84, 84) - 4 stacked frames
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Calculate conv output size
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;conv_output_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Fully connected layers
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Q-value per action
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x: (batch, 4, 84, 84) stacked frames&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ReplayBuffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Experience replay buffer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;buffer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;deque&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;maxlen&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__len__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DQNAgent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Complete DQN agent with experience replay and target network&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;state_shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Online and target networks
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DQN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DQN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;load_state_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;state_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.00025&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;memory&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ReplayBuffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.99&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon_decay&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.995&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_update_freq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;select_action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ε-greedy action selection&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;state_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;q_values&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q_values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single training step on mini-batch from replay buffer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;memory&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Sample mini-batch
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rewards&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dones&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;memory&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Convert to tensors
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LongTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;rewards&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rewards&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;next_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dones&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute current Q-values
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;current_q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gather&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute target Q-values using target network
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;next_q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;target_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;target_q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rewards&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_q&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute loss
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;current_q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Optimize
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Gradient clipping for stability
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip_grad_norm_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Update target network periodically
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_update_freq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;load_state_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;state_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Decay epsilon
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon_decay&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Deep Q-Network (DQN) Agent&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate DQN components
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;84&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;84&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 4 stacked frames
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DQNAgent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DQN Components:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Policy network: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Target network: Same architecture, updated every &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_update_freq&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; steps&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Replay buffer: Capacity &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;memory&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;maxlen&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Batch size: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Discount γ: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Initial ε: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (decays to &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon_min&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simulate training loop structure
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DQN Training Loop:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  1. Select action using ε-greedy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  2. Execute in environment, observe reward and next state&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  3. Store transition in replay buffer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  4. Sample mini-batch from buffer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  5. Compute Q-learning loss with target network&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  6. Update policy network via gradient descent&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  7. Periodically copy policy → target network&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This combination of techniques enables stable deep RL training!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Deep RL liên hệ chặt chẽ với học có giám sát thông qua học bắt chước (&lt;em&gt;imitation learning&lt;/em&gt;): tác tử học chính sách ban đầu từ các cặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(trạng thái, hành động)&lt;/code&gt; của chuyên gia, sau đó tiếp tục tinh chỉnh bằng RL để thích nghi tốt hơn với môi trường.&lt;/p&gt;

&lt;p&gt;Ngoài tối ưu dựa trên gradient, các chiến lược tiến hóa (&lt;em&gt;evolution strategies&lt;/em&gt; / &lt;em&gt;neuroevolution&lt;/em&gt;) cung cấp một hướng tiếp cận khác bằng cách tiến hóa một quần thể chính sách qua chọn lọc và đột biến. Phương pháp này có thể cạnh tranh tốt trong các bài toán mà ước lượng gradient kém ổn định.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.5602&quot;&gt;“Playing Atari with Deep Reinforcement Learning” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Volodymyr Mnih et al. (DeepMind)&lt;br /&gt;
Giới thiệu DQN — kết hợp Q-learning với CNN sâu, &lt;em&gt;experience replay&lt;/em&gt; và &lt;em&gt;target network&lt;/em&gt; để học chơi trò chơi Atari trực tiếp từ pixel.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.nature.com/articles/nature14236&quot;&gt;“Human-level control through deep reinforcement learning” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Volodymyr Mnih et al. (DeepMind)&lt;br /&gt;
Công bố trên &lt;em&gt;Nature&lt;/em&gt; cho thấy một kiến trúc DQN và bộ siêu tham số thống nhất có thể đạt hiệu năng ngang người chơi trên 49 trò chơi Atari, khẳng định khả năng giải các bài toán điều khiển từ đầu vào nhiều chiều.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1602.01783&quot;&gt;“Asynchronous Methods for Deep Reinforcement Learning” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Volodymyr Mnih et al.&lt;br /&gt;
A3C chạy song song nhiều tác tử cập nhật bất đồng bộ, giảm nhu cầu dùng bộ đệm &lt;em&gt;experience replay&lt;/em&gt; và khẳng định hiệu quả của kiến trúc &lt;em&gt;actor–critic&lt;/em&gt; bên cạnh phương pháp dựa trên hàm giá trị.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1707.06347&quot;&gt;“Proximal Policy Optimization Algorithms” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, Oleg Klimov&lt;br /&gt;
PPO sử dụng hàm mục tiêu thay thế bị cắt ngưỡng (&lt;em&gt;clipped surrogate objective&lt;/em&gt;) để hạn chế bước cập nhật chính sách quá lớn, trở thành thuật toán gradient chính sách phổ biến nhờ sự đơn giản và ổn định.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.nature.com/articles/nature24270&quot;&gt;“Mastering the game of Go without human knowledge” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: David Silver et al. (DeepMind)&lt;br /&gt;
AlphaGo Zero đạt trình độ cờ vây vượt trội chỉ qua tự đấu mà không cần dữ liệu ván đấu của con người, kết hợp deep RL với tìm kiếm cây Monte Carlo (MCTS).&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;Bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;p&gt;Định hình phần thưởng (&lt;em&gt;reward shaping&lt;/em&gt;) có thể đẩy nhanh quá trình học nhưng cũng dễ gây tác dụng ngược: tác tử có thể tối ưu hóa phần thưởng trung gian thay vì mục tiêu cuối cùng (&lt;em&gt;reward hacking&lt;/em&gt;). Cần luôn kiểm chứng hành vi thực tế của tác tử trên phần thưởng gốc.&lt;/p&gt;

&lt;p&gt;Deep RL nhạy cảm với siêu tham số hơn nhiều so với học có giám sát. Tốc độ học, kích thước bộ đệm phát lại, tần suất cập nhật mạng đích và lịch giảm \(\varepsilon\) đều tác động mạnh tới sự hội tụ. Nên bắt đầu từ bộ siêu tham số đã kiểm chứng trên bài toán tương tự rồi mới tinh chỉnh dần.&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;p&gt;Học tăng cường sâu sử dụng mạng nơ-ron để xấp xỉ hàm giá trị hoặc chính sách, cho phép học trực tiếp từ đầu vào nhiều chiều như hình ảnh. DQN kết hợp &lt;em&gt;experience replay&lt;/em&gt; (phá tương quan thời gian) và &lt;em&gt;target network&lt;/em&gt; (ổn định mục tiêu Q-learning), trong khi các phương pháp gradient chính sách (REINFORCE, actor–critic, PPO) tối ưu trực tiếp chính sách và phù hợp hơn với không gian hành động liên tục. Dù đạt nhiều kết quả nổi bật trong trò chơi, robot và căn chỉnh mô hình ngôn ngữ, deep RL vẫn đối mặt với các thách thức về hiệu quả mẫu, độ nhạy siêu tham số và tính ổn định khi huấn luyện.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Lecture 14&lt;/td&gt;
          &lt;td&gt;Deep Reinforcement Learning](https://www.youtube.com/watch?v=lvoHnicueoE) — Stanford University School of Engineering, tiếng Anh. Trình bày cả DQN và phương pháp gradient chính sách trong cùng một bài giảng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=x83WmvbRa2I&quot;&gt;Deep Q-Networks Explained!&lt;/a&gt; — CodeEmporium, tiếng Anh. Giải thích chậm và trực quan về mạng Q và bộ đệm phát lại.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KHZVXao4qXs&quot;&gt;RL Course by David Silver - Lecture 7: Policy Gradient Methods&lt;/a&gt; — Google DeepMind, tiếng Anh. Bài giảng chuyên sâu về phương pháp gradient chính sách, bổ sung phần còn lại của bài.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>21 Học Tăng cường Sâu</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter21/21_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter21/21_00_Introduction</id>
   <content type="html">&lt;p&gt;Trò chơi Atari Breakout chỉ có màn hình nhỏ \(84 \times 84\) mức xám, nhưng số trạng thái khả dĩ của nó đã vượt xa số nguyên tử trong vũ trụ quan sát được — mọi bảng Q của Chương 20 lập tức trở nên vô dụng! Bằng cách thay bảng Q bằng mạng nơ-ron sâu (&lt;strong&gt;DQN&lt;/strong&gt;) và mở rộng sang tối ưu chính sách trực tiếp (&lt;strong&gt;Policy Gradient / PPO&lt;/strong&gt;), &lt;strong&gt;Học Tăng cường Sâu (Deep RL)&lt;/strong&gt; đã mở đường cho AlphaGo, robot điều khiển liên tục và hậu huấn luyện LLM hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-học-tăng-cường-sâu-deep-rl&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Học Tăng cường Sâu (Deep RL)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xấp xỉ hàm giá trị sâu (DQN) và hai trụ cột ổn định:&lt;/strong&gt; Khắc phục “bộ ba chết người” (xấp xỉ hàm + bootstrapping + off-policy) bằng &lt;em&gt;Experience Replay&lt;/em&gt; (phá tương quan chuỗi) và &lt;em&gt;Target Network&lt;/em&gt; (cố định mục tiêu TD).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tối ưu chính sách trực tiếp (REINFORCE / Policy Gradient):&lt;/strong&gt; Tham số hóa trực tiếp phân phối hành động \(\pi_\theta(a\mid s)\), xử lý tự nhiên không gian hành động liên tục (góc khớp robot, vô lăng xe).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc Actor–Critic và ước lượng lợi thế (GAE):&lt;/strong&gt; Kết hợp Actor (chọn hành động) với Critic (đánh giá \(V(s)\) làm đường cơ sở giảm phương sai gradient).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tối ưu vùng tin cậy (PPO) và hậu huấn luyện LLM (RLHF/DPO/GRPO):&lt;/strong&gt; Chặn độ lệch mỗi bước cập nhật chính sách để huấn luyện ổn định ở quy mô lớn.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-vì-sao-không-thể-dùng-bảng-q-cho-màn-hình-atari-và-mạng-dqn-nén-không-gian-ra-sao&quot;&gt;Giải thích: Vì sao không thể dùng bảng Q cho màn hình Atari và mạng DQN nén không gian ra sao?&lt;/h3&gt;

&lt;p&gt;Xét đầu vào chuẩn của DQN trên Atari: chồng \(4\) khung hình liên tiếp kích thước \(84 \times 84\) với \(256\) mức xám/pixel và \(4\) hành động điều khiển.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kích thước bảng Q cổ điển:&lt;/strong&gt; Số trạng thái là \(256^{4 \times 84 \times 84} = 256^{28{,}224} &amp;gt; 10^{67{,}900}\) — bất khả thi tuyệt đối để lưu trữ hay ghé thăm từng ô!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mạng tích chập DQN:&lt;/strong&gt; Nhận thẳng tensor \(4 \times 84 \times 84\) qua 3 tầng tích chập và 2 tầng tuyến tính (chỉ khoảng \(1{,}7\text{ triệu}\) tham số) để xuất ra đồng thời \(4\) giá trị \(Q_\theta(s, a_1), \dots, Q_\theta(s, a_4)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sức mạnh tổng quát hóa:&lt;/strong&gt; Khi quả bóng nhích sang phải 2 pixel, bảng Q coi đó là trạng thái hoàn toàn xa lạ; còn mạng DQN nhờ bộ lọc tích chập nhận ra ngay cấu trúc giống trạng thái cũ và kế thừa trọn vẹn ước lượng giá trị!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Học tăng cường sâu (&lt;em&gt;deep reinforcement learning&lt;/em&gt;) kết hợp mạng nơ-ron sâu với học tăng cường để xử lý không gian trạng thái nhiều chiều. Chương này trình bày DQN (&lt;em&gt;Deep Q-Network&lt;/em&gt;), các phương pháp gradient chính sách (REINFORCE, A3C), kiến trúc &lt;em&gt;actor–critic&lt;/em&gt; (A2C, PPO) cùng các ứng dụng trong trò chơi (như AlphaGo) và điều khiển robot, làm rõ cách học sâu mở rộng RL sang các bài toán thực tế phức tạp.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau DQN và PPO, xem thêm bài &lt;strong&gt;21-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về RLHF, DPO và GRPO trong căn chỉnh mô hình ngôn ngữ.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Lecture 14&lt;/td&gt;
          &lt;td&gt;Deep Reinforcement Learning](https://www.youtube.com/watch?v=lvoHnicueoE) — Stanford University School of Engineering, tiếng Anh. Bài giảng CS231n bao quát hai nội dung trọng tâm của chương là DQN và phương pháp gradient chính sách.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8JVRbHAVCws&quot;&gt;MIT 6.S191 (2024): Reinforcement Learning&lt;/a&gt; — Alexander Amini, tiếng Anh. Trình bày tổng quan học tăng cường sâu với các ví dụ cập nhật năm 2024.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=x83WmvbRa2I&quot;&gt;Deep Q-Networks Explained!&lt;/a&gt; — CodeEmporium, tiếng Anh. Giải thích chi tiết DQN — nhánh phương pháp dựa trên hàm giá trị.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>20-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter20/20_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter20/20_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Khi nghe đến Học Tăng cường, nhiều người chỉ nghĩ tới robot đi bộ hay AI chơi cờ vây; nhưng trên thực tế, phần lớn hệ thống RL đang tạo ra giá trị kinh tế khổng lồ mỗi giây hôm nay lại nằm ở &lt;strong&gt;hệ thống gợi ý (Contextual Bandits)&lt;/strong&gt;, &lt;strong&gt;RL ngoại tuyến trên dữ liệu log (Offline RL)&lt;/strong&gt; và đặc biệt là &lt;strong&gt;khung MDP của RLHF&lt;/strong&gt; giúp căn chỉnh các mô hình ngôn ngữ lớn như ChatGPT, Claude và Gemini!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-ứng-dụng-thực-chiến-của-nền-tảng-rl-hiện-đại-20222026&quot;&gt;Kiến thức cần nhớ: Ba ứng dụng thực chiến của nền tảng RL hiện đại (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình hóa sinh văn bản LLM dưới dạng MDP (RLHF):&lt;/strong&gt; Coi chuỗi token đã sinh là trạng thái \(s_t\), token kế tiếp là hành động \(a_t \in V\), chính sách là chính LLM \(\pi_\theta(a_t\mid s_t)\), và phần thưởng nằm ở cuối câu kèm phạt KL để không trôi xa mô hình gốc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Contextual Multi-Armed Bandits trong xếp hạng &amp;amp; quảng cáo:&lt;/strong&gt; Bài toán RL một bước (không có chuyển trạng thái dài hạn) dùng UCB hoặc Thompson Sampling để vừa khai thác nội dung có tỷ lệ nhấp cao vừa khám phá nội dung mới.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;RL ngoại tuyến (Offline / Batch RL — CQL, IQL):&lt;/strong&gt; Huấn luyện chính sách hoàn toàn từ nhật ký lịch sử cố định (y tế, tài chính, công nghiệp) mà không được phép tương tác mạo hiểm với môi trường thật.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bẫy phân phối lệch (Distributional Shift) trong Offline RL:&lt;/strong&gt; Hiểu lý do Q-Learning tiêu chuẩn ước lượng quá cao các hành động ngoài tập log (OOD actions) và cần ràng buộc bảo thủ (conservative penalty).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-điểm-chọn-cánh-tay-bằng-thuật-toán-ucb1-upper-confidence-bound-trong-bandit&quot;&gt;Giải thích: Tính điểm chọn cánh tay bằng thuật toán UCB1 (Upper Confidence Bound) trong Bandit&lt;/h3&gt;

&lt;p&gt;Một hệ thống gợi ý tin tức có 2 bài viết ứng viên sau tổng cộng \(t = 100\) lượt hiển thị (\(\ln 100 \approx 4{,}605\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bài A:&lt;/strong&gt; Đã hiển thị \(N_A = 80\) lần, tỷ lệ nhấp trung bình \(\hat{\mu}_A = 0{,}20\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài B:&lt;/strong&gt; Mới hiển thị \(N_B = 5\) lần, tỷ lệ nhấp trung bình \(\hat{\mu}_B = 0{,}15\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Áp dụng công thức UCB1 (hệ số khám phá \(c = 0{,}5\)): \(\text{UCB}(a) = \hat{\mu}_a + c\sqrt{\frac{\ln t}{N_a}}\):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bài A:&lt;/strong&gt; \(0{,}20 + 0{,}5\sqrt{\frac{4{,}605}{80}} = 0{,}20 + 0{,}5(0{,}240) = 0{,}320\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài B:&lt;/strong&gt; \(0{,}15 + 0{,}5\sqrt{\frac{4{,}605}{5}} = 0{,}15 + 0{,}5(0{,}960) = 0{,}630\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quyết định:&lt;/strong&gt; Dù trung bình của B đang thấp hơn A (\(0{,}15 &amp;lt; 0{,}20\)), phần thưởng cho độ bất định của B lớn gấp 4 lần A nên UCB1 chọn &lt;strong&gt;khám phá Bài B&lt;/strong&gt; trước — ngay khi \(N_B\) tăng lên, khoảng tin cậy tự thu hẹp lại mà không cần tinh chỉnh \(\epsilon\) thủ công!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-nền-tảng-rl-trong-thực-tế--bandit-hệ-thống-gợi-ý-và-mdp-của-rlhf&quot;&gt;Tùy chọn: Nền tảng RL trong thực tế — Bandit, hệ thống gợi ý và MDP của RLHF&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế định nghĩa về MDP, tổng phần thưởng chiết khấu hay hàm chính sách/giá trị. Nội dung cho thấy các khái niệm đó xuất hiện ở đâu trong các hệ thống khoa học dữ liệu giai đoạn 2022–2026, đặc biệt là huấn luyện mô hình ngôn ngữ theo sở thích con người.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;MDP \((S,A,P,R,\gamma)\) vẫn là khung mô hình nền tảng. Một ứng dụng đáng chú ý là &lt;strong&gt;căn chỉnh mô hình hội thoại&lt;/strong&gt; (&lt;em&gt;chat alignment&lt;/em&gt;), trong đó “môi trường” chính là con người (hoặc mô hình phần thưởng) đánh giá toàn bộ câu trả lời sinh ra.&lt;/p&gt;

&lt;h2 id=&quot;1-rlhf-dưới-góc-nhìn-mdp&quot;&gt;1. RLHF dưới góc nhìn MDP&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Ouyang et al., 2022&lt;/a&gt; (InstructGPT) mô hình hóa mỗi prompt là trạng thái ban đầu, mỗi token sinh ra là một hành động, và điểm số từ mô hình phần thưởng đã học \(r_\phi\) đóng vai trò hàm phần thưởng \(R\). Sau đó, PPO (xem Chương 21) tối đa hóa mục tiêu:&lt;/p&gt;

\[J(\theta) = \mathbb{E}_{\pi_\theta}[r_\phi] - \beta\, D_{\mathrm{KL}}(\pi_\theta \,\|\, \pi_{\mathrm{ref}}).\]

&lt;p&gt;Số hạng phạt KL giữ cho chính sách mới không lệch quá xa chính sách tham chiếu ban đầu, tương tự nguyên lý bảo thủ trong RL. Chi tiết về PPO và DPO sẽ được trình bày ở bài tùy chọn Chương 21; điểm cốt lõi ở đây là hệ thuật ngữ của Chương 20 được sử dụng trực tiếp trong thực tế công nghiệp.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-cụ-thể&quot;&gt;2. Ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;contextual-bandit-trong-bài-toán-xếp-hạng&quot;&gt;Contextual Bandit trong bài toán xếp hạng&lt;/h3&gt;

&lt;p&gt;Các hệ thống bảng tin và gửi thông báo thường được mô hình hóa bằng &lt;strong&gt;contextual bandit&lt;/strong&gt; thay vì MDP đầy đủ: chỉ có một bước hành động và phần thưởng phản hồi ngay lập tức (như lượt nhấp chuột). Các thư viện phổ biến gồm &lt;a href=&quot;https://github.com/VowpalWabbit/vowpal_wabbit&quot;&gt;Vowpal Wabbit&lt;/a&gt; và &lt;a href=&quot;https://github.com/ray-project/ray&quot;&gt;Ray RLlib&lt;/a&gt;, dựa trực tiếp trên lý thuyết đánh đổi khám phá–khai thác của chương này.&lt;/p&gt;

&lt;h3 id=&quot;rl-ngoại-tuyến-offline--batch-rl-trên-dữ-liệu-log&quot;&gt;RL ngoại tuyến (Offline / Batch RL) trên dữ liệu log&lt;/h3&gt;

&lt;p&gt;Khi không thể thử nghiệm tự do hoặc đặt lại môi trường thực (như nhà máy hay thị trường tài chính), mô hình phải học từ tập dữ liệu tương tác \((s,a,r,s&apos;)\) đã ghi nhận sẵn. &lt;a href=&quot;https://arxiv.org/abs/2005.01643&quot;&gt;Levine et al., 2020&lt;/a&gt; tổng hợp nền tảng của RL ngoại tuyến; các ứng dụng giai đoạn 2022–2025 thường sử dụng &lt;em&gt;conservative Q-learning&lt;/em&gt; và &lt;em&gt;fitted policy&lt;/em&gt; trên dữ liệu log của hệ thống gợi ý.&lt;/p&gt;

&lt;h3 id=&quot;mô-phỏng-trước-khi-triển-khai-thực-tế&quot;&gt;Mô phỏng trước khi triển khai thực tế&lt;/h3&gt;

&lt;p&gt;Trong robot và hệ thống quảng cáo, môi trường mô phỏng (&lt;em&gt;simulator&lt;/em&gt;) vẫn được dùng để giảm chi phí tương tác. Định nghĩa chặt chẽ về xác suất chuyển trạng thái \(P\) và hàm phần thưởng \(R\) trong chương này là cơ sở để kiểm tra xem bộ mô phỏng có phản ánh đúng thực tế hay không.&lt;/p&gt;

&lt;h2 id=&quot;3-phần-mềm-phổ-biến&quot;&gt;3. Phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/Farama-Foundation/Gymnasium&quot;&gt;Gymnasium&lt;/a&gt; — nhánh kế thừa từ năm 2023 trở đi của OpenAI Gym.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/trl&quot;&gt;huggingface/trl&lt;/a&gt; — thư viện huấn luyện RLHF (xem thêm Chương 21).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/VowpalWabbit/vowpal_wabbit&quot;&gt;vw&lt;/a&gt; — công cụ triển khai bandit trong sản phẩm thực tế.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;InstructGPT (Ouyang et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://gymnasium.farama.org/&quot;&gt;Gymnasium&lt;/a&gt; — giao diện MDP chuẩn được duy trì và dùng phổ biến trong các khóa học giai đoạn 2023–2026.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2005.01643&quot;&gt;Offline RL survey (Levine et al., 2020)&lt;/a&gt; — tài liệu tổng quan cho các bài toán học tăng cường từ dữ liệu log.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-bài-này-bổ-sung-gì-cho-ghi-chú-cốt-lõi&quot;&gt;5. Bài này bổ sung gì cho ghi chú cốt lõi&lt;/h2&gt;

&lt;p&gt;Trước hết cần nắm vững trạng thái, tổng phần thưởng chiết khấu và hệ phương trình Bellman. Bài này chỉ minh họa &lt;strong&gt;các bài toán MDP đã được triển khai rộng rãi&lt;/strong&gt; (bandit, RL ngoại tuyến trên log và RLHF), không thay đổi định nghĩa của hàm giá trị.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qPN_XZcJf_s&quot;&gt;Reinforcement Learning with Human Feedback (RLHF), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích RLHF như một bài toán MDP với phần thưởng học từ phản hồi con người, bám sát nội dung bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=T_X4XFwKX8k&quot;&gt;Reinforcement Learning from Human Feedback (RLHF) Explained&lt;/a&gt; — IBM Technology, tiếng Anh. Tóm tắt ngắn gọn vòng lặp RLHF theo góc nhìn ứng dụng doanh nghiệp.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=lfHX2hHRMVQ&quot;&gt;RL Course by David Silver - Lecture 2: Markov Decision Process&lt;/a&gt; — Google DeepMind, tiếng Anh. Ôn lại hệ khái niệm MDP làm nền tảng cho các ứng dụng trên.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>20-01 Cơ sở Học Tăng cường</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter20/20_01_RL_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter20/20_01_RL_Fundamentals</id>
   <content type="html">&lt;p&gt;Điều kỳ diệu của &lt;strong&gt;Q-Learning&lt;/strong&gt; (Chris Watkins, 1989) là tác tử không cần ai đưa cho bản đồ xác suất của môi trường, cũng không cần chờ tới cuối ván mới rút kinh nghiệm — chỉ sau &lt;em&gt;một bước đi duy nhất&lt;/em&gt; từ trạng thái \(s\) sang \(s&apos;\), nó đã có thể tự hiệu chỉnh niềm tin của mình bằng sai số thời gian TD (&lt;em&gt;Temporal Difference Error&lt;/em&gt;). Bài học nền tảng này dẫn bạn qua phương trình Bellman, sự khác biệt tinh tế giữa on-policy (SARSA) và off-policy (Q-Learning), cùng vòng lặp cài đặt bảng Q hoàn chỉnh.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-khung-toán-học-cốt-lõi-của-mdp-và-q-learning&quot;&gt;Kiến thức cần nhớ: Khung toán học cốt lõi của MDP và Q-Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phương trình kỳ vọng và tối ưu Bellman:&lt;/strong&gt; Thiết lập điều kiện điểm bất động cho \(V^*(s) = \max_a Q^*(s, a)\) và \(Q^*(s, a) = R(s,a) + \gamma \sum_{s&apos;} P(s&apos;\mid s,a)\max_{a&apos;} Q^*(s&apos;, a&apos;)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bootstrapping và sai số TD (\(\delta_t\)):&lt;/strong&gt; Thay vì dùng tổng phần thưởng thật đến hết tập (Monte Carlo — phương sai cao), dùng ngay ước lượng \(r + \gamma \max_{a&apos;} Q(s&apos;, a&apos;)\) làm mục tiêu cập nhật tại mỗi bước.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Off-Policy (Q-Learning) vs. On-Policy (SARSA):&lt;/strong&gt; Q-Learning luôn cập nhật theo hành động tham lam \(\max_{a&apos;} Q(s&apos;, a&apos;)\) bất kể đang khám phá \(\epsilon\)-greedy (tìm đường tối ưu sát mép vực), còn SARSA cập nhật theo đúng hành động thực tế \(a&apos;\) (an toàn hơn khi có nhiễu khám phá).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Giới hạn của học tăng cường dạng bảng (Tabular RL):&lt;/strong&gt; Giải thích vì sao bảng $$&lt;/td&gt;
          &lt;td&gt;\mathcal{S}&lt;/td&gt;
          &lt;td&gt;\times&lt;/td&gt;
          &lt;td&gt;\mathcal{A}&lt;/td&gt;
          &lt;td&gt;$$ sụp đổ khi trạng thái là ảnh pixel liên tục — cầu nối sang Học Tăng cường Sâu (Chương 21).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-cập-nhật-q-learning-trên-bảng-q-nhỏ&quot;&gt;Giải thích: Tính tay một bước cập nhật Q-Learning trên bảng Q nhỏ&lt;/h3&gt;

&lt;p&gt;Giả sử tác tử đang ở ô \(s_1\), chọn hành động &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Phải&lt;/code&gt;, nhận phần thưởng tức thì \(r = -1\) và chuyển sang ô \(s_2\). Biết tốc độ học \(\alpha = 0{,}5\), hệ số chiết khấu \(\gamma = 0{,}9\), và các giá trị Q hiện tại là:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[Q(s_1, \text{Phải}) = 2{,}0\]
  &lt;/li&gt;
  &lt;li&gt;Tại ô kế tiếp \(s_2\): \(Q(s_2, \text{Lên}) = 8{,}0\), \(Q(s_2, \text{Phải}) = 5{,}0\).&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính mục tiêu TD (TD Target):&lt;/strong&gt;
\(y = r + \gamma \max_{a&apos;} Q(s_2, a&apos;) = -1 + 0{,}9 \times \max(8{,}0,\; 5{,}0) = -1 + 0{,}9(8{,}0) = 6{,}2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính sai số TD (TD Error):&lt;/strong&gt;
\(\delta = y - Q(s_1, \text{Phải}) = 6{,}2 - 2{,}0 = +4{,}2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật bảng Q:&lt;/strong&gt;
\(Q_{\text{mới}}(s_1, \text{Phải}) = 2{,}0 + 0{,}5 \times (+4{,}2) = 4{,}1.\)
Nhìn cách thông tin phần thưởng tốt ở \(s_2\) (\(8{,}0\)) vừa lan ngược lại một bước về \(s_1\) (kéo từ \(2{,}0 \to 4{,}1\)) — lặp lại đủ số lần, giá trị mục tiêu sẽ lan tỏa khắp toàn bộ bản đồ!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;học-tăng-cường-học-từ-tương-tác&quot;&gt;Học Tăng cường: Học từ Tương tác&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Reinforcement_learning_diagram.svg/800px-Reinforcement_learning_diagram.svg.png&quot; alt=&quot;Reinforcement Learning Diagram&quot; /&gt;
&lt;em&gt;Hình ảnh: Sơ đồ học tăng cường với tác tử, môi trường, hành động và phần thưởng. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Học tăng cường (&lt;em&gt;reinforcement learning&lt;/em&gt;, RL) khác biệt căn bản so với học có giám sát và học không giám sát. Thay vì học từ dữ liệu đã gán nhãn hay tìm cấu trúc trong dữ liệu không nhãn, tác tử RL học bằng cách tương tác trực tiếp với môi trường: thực hiện hành động, quan sát trạng thái mới và nhận phần thưởng. Mục tiêu của tác tử là tìm ra một chính sách (&lt;em&gt;policy&lt;/em&gt;) — chiến lược chọn hành động — sao cho tối đa hóa phần thưởng tích lũy theo thời gian. Quá trình học thử–sai với phần thưởng trễ này gần với cách con người và động vật rèn luyện kỹ năng: thử nghiệm, quan sát kết quả và điều chỉnh hành vi dần dần.&lt;/p&gt;

&lt;p&gt;Học tăng cường có những thách thức đặc thù so với học có giám sát. Trong học có giám sát, mô hình được cung cấp đáp án đúng cho từng đầu vào. Trong RL, tác tử chỉ nhận được tín hiệu phần thưởng cho biết kết quả tốt hay xấu, chứ không biết hành động nào là tối ưu. Do đó, tác tử phải đối mặt với sự đánh đổi giữa khám phá và khai thác (&lt;em&gt;exploration–exploitation&lt;/em&gt;): nên tiếp tục dùng các hành động tốt đã biết hay thử các hành động mới có thể mang lại phần thưởng cao hơn? Bên cạnh đó, phần thưởng thường bị trễ — hệ quả của một hành động có thể chỉ bộc lộ sau nhiều bước (chẳng hạn một nước đi sớm trong cờ vua ảnh hưởng đến kết quả cuối ván). Điều này tạo ra bài toán gán công trạng (&lt;em&gt;credit assignment&lt;/em&gt;): xác định hành động nào trong chuỗi đã góp phần tạo nên phần thưởng cuối cùng.&lt;/p&gt;

&lt;p&gt;Khung toán học của quá trình quyết định Markov (&lt;em&gt;Markov Decision Process&lt;/em&gt;, MDP) mô tả chặt chẽ bài toán ra quyết định tuần tự dưới sự bất định. Trạng thái (&lt;em&gt;state&lt;/em&gt;) biểu diễn tình trạng của môi trường; hành động (&lt;em&gt;action&lt;/em&gt;) là lựa chọn của tác tử; hàm chuyển trạng thái (&lt;em&gt;transition&lt;/em&gt;) mô tả cách trạng thái thay đổi (có thể mang tính ngẫu nhiên); và phần thưởng (&lt;em&gt;reward&lt;/em&gt;) đóng vai trò tín hiệu phản hồi. Tính chất Markov — trạng thái kế tiếp chỉ phụ thuộc vào trạng thái và hành động hiện tại, không phụ thuộc toàn bộ lịch sử trước đó — giúp đơn giản hóa việc phân tích và phù hợp với nhiều bài toán thực tế khi trạng thái được thiết kế đầy đủ. Hàm giá trị (&lt;em&gt;value function&lt;/em&gt;) ước lượng tổng phần thưởng tương lai kỳ vọng từ một trạng thái hoặc cặp trạng thái–hành động, còn chính sách tối ưu chọn hành động để tối đa hóa kỳ vọng đó.&lt;/p&gt;

&lt;p&gt;Khi kết hợp với học sâu thành học tăng cường sâu (&lt;em&gt;deep reinforcement learning&lt;/em&gt;), RL có thể xử lý không gian trạng thái chiều cao (như hình ảnh) và không gian hành động lớn nhờ mạng nơ-ron xấp xỉ hàm giá trị hoặc chính sách. Hướng tiếp cận này đã đạt nhiều kết quả nổi bật như AlphaGo học chơi cờ vây qua tự đấu, chơi trò chơi Atari trực tiếp từ pixel, điều khiển thao tác robot và căn chỉnh mô hình ngôn ngữ thông qua học tăng cường từ phản hồi con người (RLHF). Các kiến thức nền tảng trong chương này chuẩn bị trực tiếp cho phần học tăng cường sâu ở chương tiếp theo.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Một MDP được định nghĩa bởi bộ năm thành phần \((\mathcal{S}, \mathcal{A}, \mathcal{P}, \mathcal{R}, \gamma)\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathcal{S}\): Không gian trạng thái (tập hợp mọi cấu hình khả dĩ của môi trường).&lt;/li&gt;
  &lt;li&gt;\(\mathcal{A}\): Không gian hành động (tập các lựa chọn của tác tử).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;\(\mathcal{P}\): Hàm xác suất chuyển trạng thái $$P(s_{t+1}&lt;/td&gt;
          &lt;td&gt;s_t, a_t)$$ (động lực học môi trường).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;\(\mathcal{R}\): Hàm phần thưởng \(R(s_t, a_t, s_{t+1})\) (tín hiệu phản hồi).&lt;/li&gt;
  &lt;li&gt;\(\gamma \in [0,1)\): Hệ số chiết khấu (cân bằng giữa phần thưởng tức thời và phần thưởng tương lai).&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Tác tử hành động theo chính sách $$\pi(a&lt;/td&gt;
      &lt;td&gt;s)\(— xác suất chọn hành động\)a\(tại trạng thái\)s\(. Mục tiêu là tìm chính sách tối ưu\)\pi^&lt;em&gt;$$ tối đa hóa tổng phần thưởng chiết khấu kỳ vọng (&lt;/em&gt;expected return*):&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[J(\pi) = \mathbb{E}_{\tau \sim \pi}\left[\sum_{t=0}^\infty \gamma^t r_t\right]\]

&lt;p&gt;trong đó \(\tau = (s_0, a_0, r_0, s_1, a_1, r_1, \ldots)\) là một quỹ đạo (&lt;em&gt;trajectory&lt;/em&gt;).&lt;/p&gt;

&lt;h3 id=&quot;hàm-giá-trị&quot;&gt;Hàm giá trị&lt;/h3&gt;

&lt;p&gt;Hàm giá trị trạng thái đo tổng phần thưởng chiết khấu kỳ vọng khi bắt đầu từ trạng thái \(s\) và tuân theo chính sách \(\pi\):&lt;/p&gt;

\[V^\pi(s) = \mathbb{E}_{\pi}\left[\sum_{t=0}^\infty \gamma^t r_t \mid s_0 = s\right]\]

&lt;p&gt;Hàm giá trị hành động (hàm \(Q\)) đo kỳ vọng đó khi thực hiện hành động \(a\) tại trạng thái \(s\) rồi tiếp tục theo chính sách \(\pi\):&lt;/p&gt;

\[Q^\pi(s,a) = \mathbb{E}_{\pi}\left[\sum_{t=0}^\infty \gamma^t r_t \mid s_0 = s, a_0 = a\right]\]

&lt;p&gt;Hai hàm này thỏa mãn các phương trình Bellman thể hiện mối quan hệ đệ quy giữa trạng thái hiện tại và trạng thái kế tiếp:&lt;/p&gt;

\[V^\pi(s) = \sum_a \pi(a|s) \sum_{s&apos;} P(s&apos;|s,a)[R(s,a,s&apos;) + \gamma V^\pi(s&apos;)]\]

\[Q^\pi(s,a) = \sum_{s&apos;} P(s&apos;|s,a)[R(s,a,s&apos;) + \gamma \sum_{a&apos;} \pi(a&apos;|s&apos;) Q^\pi(s&apos;, a&apos;)]\]

&lt;p&gt;Các hàm giá trị tối ưu thỏa mãn phương trình tối ưu Bellman:&lt;/p&gt;

\[V^*(s) = \max_a \sum_{s&apos;} P(s&apos;|s,a)[R(s,a,s&apos;) + \gamma V^*(s&apos;)]\]

\[Q^*(s,a) = \sum_{s&apos;} P(s&apos;|s,a)[R(s,a,s&apos;) + \gamma \max_{a&apos;} Q^*(s&apos;, a&apos;)]\]

&lt;p&gt;Khi biết \(Q^*\), chính sách tối ưu được xác định bằng cách chọn tham lam: \(\pi^*(s) = \arg\max_a Q^*(s,a)\).&lt;/p&gt;

&lt;h3 id=&quot;q-learning&quot;&gt;Q-Learning&lt;/h3&gt;

&lt;p&gt;Q-learning học trực tiếp \(Q^*\) mà không cần biết trước xác suất chuyển trạng thái, dựa trên học chênh lệch thời gian (&lt;em&gt;temporal difference learning&lt;/em&gt;):&lt;/p&gt;

\[Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha[r_t + \gamma \max_{a&apos;} Q(s_{t+1}, a&apos;) - Q(s_t, a_t)]\]

&lt;p&gt;Quy tắc cập nhật sử dụng phần thưởng quan sát được \(r_t\) cùng ước lượng giá trị tương lai \(\max_{a&apos;} Q(s_{t+1}, a&apos;)\) để hiệu chỉnh ước lượng hiện tại \(Q(s_t, a_t)\). Cơ chế &lt;em&gt;bootstrap&lt;/em&gt; — dùng một ước lượng để cập nhật ước lượng khác — cho phép tác tử học trực tiếp từ trải nghiệm mà không cần mô hình môi trường.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và trực giác&lt;/h2&gt;

&lt;p&gt;Xét bài toán huấn luyện tác tử di chuyển trên lưới 5×5 để tìm đường tới đích. Trạng thái là tọa độ ô (25 trạng thái), hành động gồm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{lên, xuống, trái, phải}&lt;/code&gt;, phần thưởng là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+10&lt;/code&gt; khi đến đích và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-1&lt;/code&gt; ở mỗi bước khác (nhằm khuyến khích đi đường ngắn nhất).&lt;/p&gt;

&lt;p&gt;Ban đầu, các giá trị \(Q\) đều bằng 0 hoặc ngẫu nhiên. Tác tử xuất phát từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(0, 0)&lt;/code&gt; và di chuyển ngẫu nhiên cho đến khi tình cờ chạm đích &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 4)&lt;/code&gt; và nhận &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+10&lt;/code&gt;. Q-learning cập nhật:&lt;/p&gt;

\[Q((4,3), \text{right}) \leftarrow Q((4,3), \text{right}) + \alpha[10 + 0 - Q((4,3), \text{right})]\]

&lt;p&gt;Nhờ đó, giá trị \(Q\) của hành động đi sang phải từ ô &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 3)&lt;/code&gt; tăng lên. Ở các lượt sau, khi quay lại &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 3)&lt;/code&gt;, tác tử sẽ ưu tiên đi sang phải nếu dùng chính sách \(\varepsilon\)-greedy.&lt;/p&gt;

&lt;p&gt;Qua nhiều lượt chơi (&lt;em&gt;episode&lt;/em&gt;), thông tin phần thưởng lan truyền ngược dần về các ô trước đó: \(Q((4, 2), \text{right})\) tăng vì dẫn tới &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 3)&lt;/code&gt; đã có giá trị cao. Cuối cùng, bảng giá trị \(Q\) tạo thành một trường giá trị dẫn hướng về đích từ mọi vị trí xuất phát trên lưới.&lt;/p&gt;

&lt;h3 id=&quot;ứng-dụng-varepsilon-greedy-trong-luồng-gợi-ý&quot;&gt;Ứng dụng: \(\varepsilon\)-greedy trong luồng gợi ý&lt;/h3&gt;

&lt;p&gt;Các hệ thống gợi ý video hoặc sản phẩm cũng đối mặt với bài toán &lt;strong&gt;khám phá–khai thác&lt;/strong&gt;: nếu chỉ hiển thị những nội dung chắc chắn người dùng thích, hệ thống dễ nhốt người dùng trong “bong bóng sở thích” (&lt;em&gt;filter bubble&lt;/em&gt;); do đó cần xen kẽ &lt;strong&gt;khám phá&lt;/strong&gt; các chủ đề mới.&lt;/p&gt;

&lt;p&gt;Chính sách &lt;strong&gt;\(\varepsilon\)-greedy&lt;/strong&gt; được dùng phổ biến: với xác suất \(1-\varepsilon\) hệ thống chọn mục tối ưu theo mô hình (khai thác), và với xác suất \(\varepsilon\) chọn ngẫu nhiên (khám phá). Chẳng hạn với \(\varepsilon=0.1\), khoảng 90% lựa chọn là tối ưu và 10% là thử nghiệm ngẫu nhiên.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter20/recsys_epsilon_greedy.jpg&quot; alt=&quot;ε-greedy 90% / 10%&quot; /&gt;
&lt;em&gt;Hình: Chính sách ε-greedy — phần lớn thời gian chọn phương án tối ưu, phần nhỏ còn lại thử nghiệm ngẫu nhiên. (Minh họa từ video giải thích recommendation system)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter20/recsys_epsilon_greedy_detail.jpg&quot; alt=&quot;Chi tiết ε-greedy trong ranking&quot; /&gt;
&lt;em&gt;Hình: Khám phá có chủ đích giúp phát hiện chủ đề mới (ví dụ “công nghệ”) ngay cả khi mô hình đang ưu tiên chủ đề cũ. (Minh họa từ video giải thích recommendation system)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Trong hệ thống gợi ý, “phần thưởng” có thể là thời gian xem (&lt;em&gt;watch-time&lt;/em&gt;), lượt thích hoặc tổ hợp nhiều mục tiêu — vẫn nằm trong khung bài toán MDP/bandit với sự đánh đổi khám phá–khai thác quen thuộc.&lt;/p&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GridWorld&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Simple grid environment for RL demonstration&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;goal&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;reset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Execute action, return (next_state, reward, done)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# up,down,left,right
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;new_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;new_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;new_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;new_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;goal&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;goal&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Q-Learning
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;env&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GridWorld&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Q(state, action)
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Learning rate
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Discount
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Exploration
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Q-Learning agent...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;episode&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;env&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;total_reward&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# ε-greedy action selection
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;env&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total_reward&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Q-learning update
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;best_next_action&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_next_action&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)])&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;episode&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Episode &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;episode&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Reward = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_reward&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Learned optimal policy!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Học tăng cường liên hệ chặt chẽ với lý thuyết điều khiển, vận trù học và kinh tế học thông qua bài toán ra quyết định tối ưu dưới bất định. Quy hoạch động (&lt;em&gt;dynamic programming&lt;/em&gt;) giải bài toán chính sách tối ưu khi đã biết rõ mô hình động lực học môi trường, còn RL mở rộng sang trường hợp không biết trước mô hình và phải học thông qua tương tác.&lt;/p&gt;

&lt;p&gt;RL cũng liên quan đến học có giám sát qua học bắt chước (&lt;em&gt;imitation learning&lt;/em&gt;) và học tăng cường nghịch (&lt;em&gt;inverse RL&lt;/em&gt;). Thay vì học từ tín hiệu phần thưởng tường minh, tác tử có thể học trực tiếp từ dữ liệu minh họa của chuyên gia (học bắt chước) hoặc suy luận ngược lại hàm phần thưởng từ hành vi chuyên gia (&lt;em&gt;inverse RL&lt;/em&gt;).&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-và-tài-liệu-nền-tảng&quot;&gt;6. Các bài báo và tài liệu nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://incompleteideas.net/book/the-book-2nd.html&quot;&gt;“Reinforcement Learning: An Introduction” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Richard Sutton, Andrew Barto&lt;br /&gt;
Giáo trình chuẩn mực về học tăng cường, trình bày hệ thống nền tảng toán học và các thuật toán cốt lõi.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.5602&quot;&gt;“Playing Atari with Deep Reinforcement Learning” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Volodymyr Mnih et al.&lt;br /&gt;
DQN kết hợp Q-learning với mạng nơ-ron sâu, bộ đệm phát lại trải nghiệm (&lt;em&gt;experience replay&lt;/em&gt;) và mạng đích (&lt;em&gt;target network&lt;/em&gt;) để chơi trò chơi Atari trực tiếp từ pixel, mở đầu cho lĩnh vực học tăng cường sâu.&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;Bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;p&gt;Cân bằng giữa khám phá và khai thác là yếu tố quyết định hiệu quả huấn luyện. Khai thác thuần túy (chỉ chọn hành động tốt nhất đã biết) dễ mắc kẹt ở nghiệm cục bộ, còn khám phá thuần túy (chọn ngẫu nhiên liên tục) không tận dụng được kiến thức đã học. Các chiến lược như \(\varepsilon\)-greedy, chọn hành động theo softmax hoặc UCB giúp điều tiết hợp lý hai yếu tố này.&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;p&gt;Học tăng cường huấn luyện tác tử thông qua tương tác với môi trường để tìm chính sách tối đa hóa phần thưởng tích lũy. MDP mô hình hóa bài toán ra quyết định tuần tự bằng trạng thái, hành động, xác suất chuyển trạng thái và phần thưởng. Hàm giá trị ước lượng tổng phần thưởng tương lai kỳ vọng, đóng vai trò mục tiêu học. Q-learning học hàm giá trị hành động tối ưu qua cập nhật chênh lệch thời gian mà không cần biết trước mô hình môi trường. Dù phần thưởng trễ, bài toán gán công trạng và sự đánh đổi khám phá–khai thác khiến RL khó hơn học có giám sát, phương pháp này đặc biệt hữu ích khi không có sẵn nhãn giám sát tối ưu.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1444915507374636&quot;&gt;Thuật toán gợi ý (TikTok-style recommendation)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=2pWv7GOvuf0&quot;&gt;RL Course by David Silver - Lecture 1: Introduction to Reinforcement Learning&lt;/a&gt; — Google DeepMind, tiếng Anh. Giới thiệu phần thưởng, chính sách và hàm giá trị.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=lfHX2hHRMVQ&quot;&gt;RL Course by David Silver - Lecture 2: Markov Decision Process&lt;/a&gt; — Google DeepMind, tiếng Anh. Trình bày trạng thái, hành động và hệ phương trình Bellman tương ứng với phần toán học trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=9hbQieQh7-o&quot;&gt;Reinforcement Learning with Neural Networks: Essential Concepts&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa cách dùng mạng nơ-ron xấp xỉ các đối tượng RL, bước đệm cho chương tiếp theo.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>20 Cơ sở Học Tăng cường</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter20/20_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter20/20_00_Introduction</id>
   <content type="html">&lt;p&gt;Một kỳ thủ cờ vây thực hiện nước đi thứ 42 ở giữa bàn cờ — phải tới 150 nước sau ván đấu mới ngã ngũ thắng hay thua. Làm sao họ biết được liệu nước đi thứ 42 đó là tuyệt chiêu hay sai lầm chí mạng? Khác hoàn toàn với học có giám sát (biết ngay đáp án đúng sau mỗi mẫu), &lt;strong&gt;Học Tăng cường (Reinforcement Learning — RL)&lt;/strong&gt; mô hình hóa bài toán &lt;em&gt;ra quyết định tuần tự dưới tín hiệu thưởng trễ&lt;/em&gt; — nơi mỗi hành động vừa mang lại phần thưởng, vừa thay đổi hoàn toàn tương lai mà tác tử sẽ đối mặt.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-học-tăng-cường-cổ-điển&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Học Tăng cường cổ điển&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Quá trình quyết định Markov (MDP):&lt;/strong&gt; Bộ năm toán học \((\mathcal{S}, \mathcal{A}, P, R, \gamma)\) định nghĩa trạng thái, hành động, động lực chuyển trạng thái, phần thưởng và hệ số chiết khấu tương lai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương trình Bellman và hàm giá trị (\(V^\pi, Q^\pi\)):&lt;/strong&gt; Biểu diễn giá trị dài hạn một cách đệ quy: giá trị hôm nay bằng phần thưởng tức thì cộng giá trị chiết khấu của ngày mai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khám phá vs. Khai thác (Exploration vs. Exploitation):&lt;/strong&gt; Giải bài toán cân bằng kinh điển giữa chọn hành động tốt nhất đã biết và thử hành động mới (\(\epsilon\)-greedy, UCB, Thompson Sampling).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học sai phân thời gian (TD Learning, SARSA, Q-Learning):&lt;/strong&gt; Cập nhật ước lượng giá trị ngay sau từng bước tương tác mà không cần biết trước mô hình môi trường \(P\) hay chờ hết ván đấu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tổng-phần-thưởng-chiết-khấu-return-g_t-và-ảnh-hưởng-của-hệ-số-gamma&quot;&gt;Giải thích: Tính tổng phần thưởng chiết khấu (Return \(G_t\)) và ảnh hưởng của hệ số \(\gamma\)&lt;/h3&gt;

&lt;p&gt;Giả sử một tác tử đi qua chuỗi 3 bước nhận phần thưởng lần lượt là \(r_1 = 0\), \(r_2 = 0\), \(r_3 = +10\) (thắng ở bước cuối).&lt;/p&gt;

&lt;p&gt;Công thức lợi ích chiết khấu từ thời điểm \(t=0\) là \(G_0 = r_1 + \gamma r_2 + \gamma^2 r_3\):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tác tử “thiển cận” (\(\gamma = 0{,}5\)):&lt;/strong&gt;
\(G_0 = 0 + 0{,}5(0) + (0{,}5)^2(10) = 2{,}50.\)
Nếu có một hành động khác cho ngay \(r_1 = +3\) rồi kết thúc, tác tử sẽ chọn ngay \(+3\) thay vì chờ \(+10\) sau 3 bước.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tác tử “nhìn xa” (\(\gamma = 0{,}95\)):&lt;/strong&gt;
\(G_0 = 0 + 0{,}95(0) + (0{,}95)^2(10) = 0{,}9025 \times 10 = 9{,}025.\)
Lúc này giá trị dài hạn \(9{,}025 \gg 3\), nên tác tử sẵn sàng hy sinh lợi ích nhỏ trước mắt để theo đuổi chiến thắng lớn về sau.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Học tăng cường (&lt;em&gt;reinforcement learning&lt;/em&gt;, RL) huấn luyện tác tử (&lt;em&gt;agent&lt;/em&gt;) ra quyết định tuần tự nhằm tối đa hóa phần thưởng tích lũy. Chương này giới thiệu khung bài toán RL gồm tác tử, môi trường (&lt;em&gt;environment&lt;/em&gt;), trạng thái (&lt;em&gt;state&lt;/em&gt;), hành động (&lt;em&gt;action&lt;/em&gt;), phần thưởng (&lt;em&gt;reward&lt;/em&gt;) và chính sách (&lt;em&gt;policy&lt;/em&gt;). Nội dung đi qua quá trình quyết định Markov (&lt;em&gt;Markov Decision Process&lt;/em&gt;, MDP), hàm giá trị (&lt;em&gt;value function&lt;/em&gt;), Q-learning và các phương pháp gradient chính sách (&lt;em&gt;policy gradient&lt;/em&gt;), tạo nền tảng cho học tăng cường sâu ở chương tiếp theo.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần nền tảng MDP, xem thêm bài &lt;strong&gt;20-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về bandit, RL ngoại tuyến (&lt;em&gt;offline RL&lt;/em&gt;) trên dữ liệu log và góc nhìn MDP của RLHF.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Liên kết sang chủ đề LLM:&lt;/strong&gt; Phần tổng quan về RLHF, PPO và DPO cho mô hình ngôn ngữ nằm ở &lt;strong&gt;26-03&lt;/strong&gt;; các suy diễn toán học về RL nằm tại chương này và Chương 21.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=2pWv7GOvuf0&quot;&gt;RL Course by David Silver - Lecture 1: Introduction to Reinforcement Learning&lt;/a&gt; — Google DeepMind, tiếng Anh. Bài giảng mở đầu của David Silver về tác tử, môi trường và khung bài toán học tăng cường.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=lfHX2hHRMVQ&quot;&gt;RL Course by David Silver - Lecture 2: Markov Decision Process&lt;/a&gt; — Google DeepMind, tiếng Anh. Trình bày chi tiết quá trình quyết định Markov, tương ứng với phần toán học trong bài sau.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8JVRbHAVCws&quot;&gt;MIT 6.S191 (2024): Reinforcement Learning&lt;/a&gt; — Alexander Amini, tiếng Anh. Giới thiệu các khái niệm cốt lõi của RL kèm ví dụ ứng dụng hiện đại.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>19-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter19/19_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter19/19_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Chỉ vài năm trước, muốn xây dựng một hệ thống nhận dạng tiếng nói cho tiếng Việt hoặc một chuyên ngành hẹp, bạn phải gom hàng nghìn giờ ghi âm căn chỉnh thủ công theo từng âm vị cùng mô hình ngôn ngữ rời rạc. Sự xuất hiện của &lt;strong&gt;Whisper&lt;/strong&gt;, các &lt;strong&gt;Neural Audio Codec&lt;/strong&gt; (EnCodec, Mimi) và hệ thống hội thoại giọng nói song công (full-duplex speech-to-speech) đã thống nhất hoàn toàn thế giới âm thanh với kiến trúc Transformer.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-công-nghệ-tiếng-nói-hiện-đại-20222026&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của công nghệ Tiếng nói hiện đại (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Whisper và huấn luyện giám sát yếu đa nhiệm:&lt;/strong&gt; Dùng một kiến trúc Encoder–Decoder duy nhất trên 680.000+ giờ âm thanh đa ngữ để đồng thời nhận dạng ngôn ngữ, ghi chép có dấu câu, gắn mốc thời gian và dịch sang tiếng Anh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thước đo chất lượng ASR — Word Error Rate (WER) và CER:&lt;/strong&gt; Đo lường chính xác sai số thay thế (S), xóa (D) và chèn (I) dựa trên khoảng cách biên tập Levenshtein.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Residual Vector Quantization (RVQ) Audio Codec:&lt;/strong&gt; Nén sóng âm thành nhiều tầng mã rời rạc tốc độ bit cực thấp (\(1{,}5\text{–}6\text{ kbps}\)), biến sinh giọng nói thành bài toán dự đoán token kế tiếp giống LLM.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giao tiếp giọng nói song công (Full-Duplex Speech Models):&lt;/strong&gt; Giảm độ trễ phản hồi xuống dưới 300 ms bằng cách xử lý luồng âm thanh trực tiếp (audio-in, audio-out) thay vì nối chuỗi chậm chạp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ASR → LLM → TTS&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-word-error-rate-wer-và-tốc-độ-bit-của-một-neural-audio-codec&quot;&gt;Giải thích: Tính tay Word Error Rate (WER) và tốc độ bit của một Neural Audio Codec&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Tính tay WER:&lt;/strong&gt; Giả sử câu chuẩn (&lt;em&gt;reference&lt;/em&gt;) có \(N = 8\) từ: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;hôm nay trời nắng đẹp và rất mát&lt;/code&gt;, còn mô hình ASR xuất ra: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;hôm nay trời rất nắng và rất mát mẻ&lt;/code&gt;.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;So khớp tối ưu: chèn thêm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rất&lt;/code&gt; trước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nắng&lt;/code&gt; (\(I = 1\)), xóa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;đẹp&lt;/code&gt; (\(D = 1\)), chèn thêm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mẻ&lt;/code&gt; ở cuối (\(I = 1\)), không có thay thế trực tiếp (hoặc tính tương đương: \(S=1, D=0, I=1\)? Chú ý: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nắng đẹp&lt;/code&gt; → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rất nắng&lt;/code&gt; là chèn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;rất&lt;/code&gt; + xóa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;đẹp&lt;/code&gt; = 2 phép, cộng chèn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mẻ&lt;/code&gt; = 1 phép, tổng khoảng cách biên tập \(= 3\)).&lt;/li&gt;
  &lt;li&gt;
\[\text{WER} = \frac{S + D + I}{N} = \frac{3}{8} = 37{,}5\%.\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Tốc độ bit của RVQ Audio Codec:&lt;/strong&gt; Giả sử codec chạy ở tần số khung \(f_{\text{frame}} = 50\text{ Hz}\) (mỗi giây tạo 50 khung), dùng \(Q = 8\) tầng sổ mã (&lt;em&gt;codebooks&lt;/em&gt;), mỗi sổ mã có \(1{,}024 = 2^{10}\) mã (\(10\text{ bit/mã}\)).&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tốc độ bit: \(50 \times 8 \times 10 = 4{,}000\text{ bit/giây} = 4{,}0\text{ kbps}\) — nhỏ hơn &lt;strong&gt;64 lần&lt;/strong&gt; so với âm thanh PCM 16 kHz / 16-bit gốc (\(256\text{ kbps}\)) nhưng vẫn giữ đủ ngữ điệu và âm sắc người nói!&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;tùy-chọn-tiếng-nói-và-âm-thanh-sau-whisper--asr-đa-ngữ-codec-và-tts&quot;&gt;Tùy chọn: Tiếng nói và âm thanh sau Whisper — ASR đa ngữ, Codec và TTS&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;. Phần mở đầu chương đã giới thiệu Whisper và WaveNet; bài này cập nhật các &lt;strong&gt;công cụ và mô hình thực tế giai đoạn 2022–2026&lt;/strong&gt; như ASR quy mô Whisper, codec nơ-ron và dịch tiếng nói đa ngữ. Nội dung không thay thế phần lý thuyết nền tảng về spectrogram và MFCC.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;1-whisper-trở-thành-chuẩn-mực-cho-asr&quot;&gt;1. Whisper trở thành chuẩn mực cho ASR&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2212.04356&quot;&gt;Radford et al., 2022&lt;/a&gt; huấn luyện mô hình Transformer &lt;em&gt;encoder–decoder&lt;/em&gt; trên dữ liệu tiếng nói đa ngữ giám sát yếu. Bộ giải mã (&lt;em&gt;decoder&lt;/em&gt;) phân rã xác suất đầu ra theo dạng tự hồi quy:&lt;/p&gt;

\[p(y\mid x) = \prod_t p(y_t \mid y_{&amp;lt;t}, x),\]

&lt;p&gt;trong đó \(x\) là phổ đồ log-mel (&lt;em&gt;log-mel spectrogram&lt;/em&gt;). Các phiên bản trọng số &lt;strong&gt;large-v2 / large-v3&lt;/strong&gt; cùng thư viện &lt;a href=&quot;https://github.com/SYSTRAN/faster-whisper&quot;&gt;faster-whisper&lt;/a&gt; (dựa trên CTranslate2) là lựa chọn phổ biến trong quy trình Python thực tế. Về kiến trúc, mô hình dựa trên Transformer ở Chương 08, nhưng cho phép nhận dạng tiếng nói ổn định mà không cần xây dựng hệ thống HMM riêng cho từng ngôn ngữ.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-cụ-thể&quot;&gt;2. Ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;dịch-tiếng-nói-và-hệ-thống-giao-tiếp-song-công&quot;&gt;Dịch tiếng nói và hệ thống giao tiếp song công&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2308.11596&quot;&gt;SeamlessM4T (2023)&lt;/a&gt; hợp nhất ba tác vụ ASR, dịch máy và TTS trong cùng một khung mô hình. Các API thời gian thực / đa phương thức (&lt;em&gt;realtime / omni&lt;/em&gt;) giai đoạn 2024–2025 đưa mô hình này vào sản phẩm theo dạng luồng: nhận luồng âm thanh đầu vào và trả về luồng token hoặc âm thanh đầu ra trực tiếp.&lt;/p&gt;

&lt;h3 id=&quot;codec-nơ-ron-làm-nền-cho-mô-hình-sinh-âm-thanh&quot;&gt;Codec nơ-ron làm nền cho mô hình sinh âm thanh&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.13438&quot;&gt;EnCodec&lt;/a&gt; và &lt;a href=&quot;https://arxiv.org/abs/2306.06546&quot;&gt;DAC&lt;/a&gt; (đã nhắc ở bài tùy chọn Chương 12) chuyển dạng sóng âm thanh thành chuỗi token rời rạc để các mô hình như MusicGen hay AudioLM xử lý. Trong tổng hợp tiếng nói (TTS), hướng tiếp cận cũng chuyển từ sinh trực tiếp từng mẫu sóng kiểu WaveNet sang mô hình &lt;strong&gt;codec-LM kết hợp vocoder&lt;/strong&gt; (như CosyVoice, XTTS, OpenVoice).&lt;/p&gt;

&lt;h3 id=&quot;phân-tách-người-nói-và-ghi-chú-cuộc-họp&quot;&gt;Phân tách người nói và ghi chú cuộc họp&lt;/h3&gt;

&lt;p&gt;Kết hợp Whisper với &lt;a href=&quot;https://github.com/pyannote/pyannote-audio&quot;&gt;pyannote&lt;/a&gt; là quy trình phổ biến cho hệ thống ghi chú cuộc họp giai đoạn 2023–2026: trước tiên nhận dạng tiếng nói (ASR), tiếp theo gán nhãn người nói (&lt;em&gt;speaker diarization&lt;/em&gt;), và cuối cùng tóm tắt nội dung bằng LLM (xem bài tùy chọn Chương 18).&lt;/p&gt;

&lt;h2 id=&quot;3-phần-mềm-phổ-biến&quot;&gt;3. Phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/openai/whisper&quot;&gt;openai/whisper&lt;/a&gt; và &lt;a href=&quot;https://github.com/SYSTRAN/faster-whisper&quot;&gt;SYSTRAN/faster-whisper&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/seamless_communication&quot;&gt;facebookresearch/seamless_communication&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/audiocraft&quot;&gt;facebookresearch/audiocraft&lt;/a&gt; và &lt;a href=&quot;https://github.com/coqui-ai/TTS&quot;&gt;coqui-ai/TTS&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2212.04356&quot;&gt;Whisper (Radford et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2308.11596&quot;&gt;SeamlessM4T (2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.13438&quot;&gt;EnCodec (Défossez et al., 2022)&lt;/a&gt; và &lt;a href=&quot;https://arxiv.org/abs/2306.06546&quot;&gt;DAC (Kumar et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-bài-này-bổ-sung-gì-cho-ghi-chú-cốt-lõi&quot;&gt;5. Bài này bổ sung gì cho ghi chú cốt lõi&lt;/h2&gt;

&lt;p&gt;Phần mở đầu chương phác họa bức tranh nền tảng (spectrogram, DeepSpeech, WaveNet), còn bài này cập nhật các &lt;strong&gt;mô hình tiền huấn luyện và codec&lt;/strong&gt; thường được cài đặt và sử dụng trong thực tế đến năm 2026.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=uFOkMme19Zs&quot;&gt;OpenAI’s Whisper Model Explained&lt;/a&gt; — What’s AI by Louis-François Bouchard, tiếng Anh. Trình bày cơ chế của Whisper, hệ thống ASR mặc định được đề cập trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=SJo7vPgRlBQ&quot;&gt;Mel Frequency Cepstral Coefficients (MFCC) Explained&lt;/a&gt; — DataMListic, tiếng Anh. Giải thích các đặc trưng thang mel làm đầu vào cho các mô hình tiếng nói.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=4_SH2nfbQZ8&quot;&gt;Mel-Frequency Cepstral Coefficients Explained Easily&lt;/a&gt; — Valerio Velardo - The Sound of AI, tiếng Anh. Hướng dẫn cách tính các đặc trưng mel để hiểu rõ bản chất đầu vào của Whisper.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>19 Xử lý Tiếng nói và Âm thanh</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter19/19_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter19/19_00_Introduction</id>
   <content type="html">&lt;p&gt;Một đoạn ghi âm dài vỏn vẹn 10 giây ở tần số lấy mẫu 16 kHz thực chất là một chuỗi &lt;strong&gt;160.000 con số&lt;/strong&gt; dao động liên tục theo áp suất không khí — dài hơn cả một cuốn tiểu thuyết ngắn nếu coi mỗi mẫu là một token! Vậy làm thế nào máy tính có thể nghe ra giọng nói tiếng Việt giữa quán cà phê ồn ào, hay tự cất giọng đọc đầy cảm xúc? Chương &lt;strong&gt;Xử lý Tiếng nói và Âm thanh&lt;/strong&gt; mở ra cánh cửa biến sóng âm thô thành biểu diễn thời gian–tần số (Log-Mel Spectrogram) và kết nối với các kiến trúc ASR/TTS hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-học-sâu-cho-tiếng-nói-và-âm-thanh&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Học sâu cho Tiếng nói và Âm thanh&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Biến đổi thời gian–tần số (STFT và Log-Mel Spectrogram):&lt;/strong&gt; Chuyển sóng âm 1D siêu dài thành ảnh 2D theo khung thời gian và băng tần Mel mô phỏng độ nhạy phi tuyến của tai người.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Căn chỉnh chuỗi độ dài khác nhau (CTC &amp;amp; Attention Encoder–Decoder):&lt;/strong&gt; Giải quyết bài toán cốt lõi của nhận dạng tiếng nói (ASR): 500 khung âm thanh chỉ tương ứng với 15 ký tự văn bản mà không biết chính xác ký tự nào bắt đầu ở mili-giây nào.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng hợp tiếng nói (TTS) và Vocoder nơ-ron:&lt;/strong&gt; Từ mô hình hai giai đoạn (văn bản → spectrogram → sóng âm qua HiFi-GAN) đến mô hình end-to-end và codec âm thanh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa mô hình nền âm thanh (2022–2026):&lt;/strong&gt; Whisper đa ngữ quy mô lớn, bộ mã hóa âm thanh rời rạc (RVQ Audio Codec) và hội thoại giọng nói song công thời gian thực.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-kích-thước-log-mel-spectrogram-từ-một-đoạn-ghi-âm-5-giây-ở-16-khz&quot;&gt;Giải thích: Tính kích thước Log-Mel Spectrogram từ một đoạn ghi âm 5 giây ở 16 kHz&lt;/h3&gt;

&lt;p&gt;Xét một đoạn ghi âm dài \(5\) giây ở tần số lấy mẫu \(f_s = 16{,}000\text{ Hz}\) (tổng cộng \(5 \times 16{,}000 = 80{,}000\) mẫu sóng âm thô). Ta áp dụng cấu hình chuẩn kiểu Whisper: cửa sổ FFT dài \(25\text{ ms}\) (\(400\) mẫu), bước nhảy (&lt;em&gt;hop length&lt;/em&gt;) \(10\text{ ms}\) (\(160\) mẫu), và \(80\) băng lọc Mel.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Số khung thời gian (frames):&lt;/strong&gt;
\(T = \left\lfloor\frac{80{,}000 - 400}{160}\right\rfloor + 1 = \lfloor 497{,}5 \rfloor + 1 = 498\text{ khung} \;(\approx 500\text{ khung}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kích thước tensor Log-Mel Spectrogram:&lt;/strong&gt; \(80 \times 498 = 39{,}840\) giá trị — ngắn hơn &lt;strong&gt;160 lần&lt;/strong&gt; theo chiều thời gian (từ \(80{,}000\) bước xuống \(498\) bước)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuyển đổi thang tần số Hertz sang Mel:&lt;/strong&gt; Theo công thức \(m(f) = 2595\log_{10}(1 + f/700)\):
    &lt;ul&gt;
      &lt;li&gt;Khoảng \(0 \to 1{,}000\text{ Hz}\) chiếm \(2595\log_{10}(2{,}429) \approx 1{,}000\text{ Mel}\).&lt;/li&gt;
      &lt;li&gt;Khoảng \(4{,}000 \to 5{,}000\text{ Hz}\) (cũng rộng \(1{,}000\text{ Hz}\)) chỉ chiếm \(2595\log_{10}(8{,}143/6{,}714) \approx 217\text{ Mel}\) — thể hiện chính xác tai người phân biệt cao độ cực tinh ở dải tần thấp chứa nguyên âm và thô hơn ở dải tần cao.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Học sâu đã làm thay đổi đáng kể lĩnh vực xử lý âm thanh, hỗ trợ hiệu quả các bài toán nhận dạng tiếng nói, nhận diện người nói, sinh nhạc và tổng hợp âm thanh. Chương này trình bày các biểu diễn âm thanh phổ biến (phổ đồ / &lt;em&gt;spectrogram&lt;/em&gt;, MFCC), kiến trúc nhận dạng tiếng nói (DeepSpeech, Whisper), chuyển văn bản thành tiếng nói (&lt;em&gt;text-to-speech&lt;/em&gt; — WaveNet, Tacotron) và các mô hình sinh nhạc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần tổng quan này, xem thêm bài &lt;strong&gt;19-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về nhận dạng tiếng nói quy mô lớn với Whisper, SeamlessM4T và các codec nơ-ron.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=SJo7vPgRlBQ&quot;&gt;Mel Frequency Cepstral Coefficients (MFCC) Explained&lt;/a&gt; — DataMListic, tiếng Anh. Giới thiệu MFCC — đặc trưng âm thanh đầu vào phổ biến cho các mô hình xử lý tiếng nói.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=4_SH2nfbQZ8&quot;&gt;Mel-Frequency Cepstral Coefficients Explained Easily&lt;/a&gt; — Valerio Velardo - The Sound of AI, tiếng Anh. Giải thích chi tiết hơn về thang mel và phép biến đổi cepstrum nếu cần bổ sung nền tảng.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=uFOkMme19Zs&quot;&gt;OpenAI’s Whisper Model Explained&lt;/a&gt; — What’s AI by Louis-François Bouchard, tiếng Anh. Trình bày tổng quan kiến trúc và cách hoạt động của hệ thống nhận dạng tiếng nói Whisper.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>18-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter18/18_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter18/18_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Nếu ở năm 2015 kỹ sư NLP chủ yếu tải vector Word2Vec/GloVe về để đưa vào LSTM phân loại cảm xúc, thì ngày nay nhúng từ tĩnh đã nhường sân khấu cho &lt;strong&gt;Mô hình Ngôn ngữ Lớn (LLM)&lt;/strong&gt; và &lt;strong&gt;nhúng ngữ nghĩa cấp đoạn văn (Dense Embeddings)&lt;/strong&gt; làm trái tim của hệ thống &lt;strong&gt;RAG (Retrieval-Augmented Generation)&lt;/strong&gt;. Bài cập nhật này giải thích mạch chuyển tiếp liền lạc từ một vector cho mỗi từ sang hệ thống vừa truy hồi tri thức vừa sinh câu trả lời có căn cứ.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-nlp-hiện-đại-20222026&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của NLP hiện đại (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Subword Tokenization (BPE / Unigram) và nhúng theo ngữ cảnh:&lt;/strong&gt; Biến văn bản thành chuỗi token con rồi đi qua nhiều tầng Self-Attention để cùng một từ mang vector khác nhau hoàn toàn theo ngữ cảnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Truy hồi dày (Dense Retrieval) và RAG:&lt;/strong&gt; Nhúng cả câu hỏi lẫn các đoạn tài liệu thành vector chuẩn hóa, tìm top-\(k\) đoạn gần nhất bằng tích vô hướng (hoặc kết hợp BM25), rồi nạp vào cửa sổ ngữ cảnh của LLM để giảm ảo giác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trích xuất có cấu trúc (Structured Outputs / JSON Schema):&lt;/strong&gt; Dùng giải mã có ràng buộc ngữ pháp để ép LLM trả về dữ liệu JSON hợp lệ 100% cho các hệ thống phần mềm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá hệ thống NLP ứng dụng:&lt;/strong&gt; Tách biệt rõ hai tầng lỗi trong RAG — lỗi truy hồi (Recall@k, MRR) và lỗi sinh câu trả lời trung thực (Faithfulness) — thay vì đánh giá mơ hồ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-điểm-truy-hồi-lai-hybrid-search-bm25--dense-cosine-bằng-rrf-trong-rag&quot;&gt;Giải thích: Tính tay điểm truy hồi lai (Hybrid Search: BM25 + Dense Cosine bằng RRF) trong RAG&lt;/h3&gt;

&lt;p&gt;Trong hệ thống RAG thực tế, ta thường kết hợp xếp hạng từ khóa (BM25) với xếp hạng vector ngữ nghĩa (Dense Embedding) bằng công thức &lt;strong&gt;Reciprocal Rank Fusion (RRF)&lt;/strong&gt; với hằng số làm mượt \(k = 60\):
\(\text{RRF}(d) = \frac{1}{k + r_{\text{BM25}}(d)} + \frac{1}{k + r_{\text{dense}}(d)}.\)&lt;/p&gt;

&lt;p&gt;Xét 3 đoạn tài liệu ứng viên cho câu hỏi về mã lỗi kỹ thuật &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ERR_409&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đoạn A&lt;/strong&gt; (chứa đúng mã &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ERR_409&lt;/code&gt; và giải thích đúng nghĩa): hạng BM25 \(= 1\), hạng Dense \(= 2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đoạn B&lt;/strong&gt; (diễn đạt đồng nghĩa rất tốt nhưng không ghi mã lỗi): hạng BM25 \(= 15\), hạng Dense \(= 1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đoạn C&lt;/strong&gt; (lặp mã &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ERR_409&lt;/code&gt; trong log rác): hạng BM25 \(= 2\), hạng Dense \(= 20\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tính điểm RRF:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;\(\text{RRF}(A) = \frac{1}{61} + \frac{1}{62} \approx 0{,}01639 + 0{,}01613 = 0{,}03252\) (&lt;strong&gt;Hạng 1&lt;/strong&gt;).&lt;/li&gt;
  &lt;li&gt;\(\text{RRF}(B) = \frac{1}{75} + \frac{1}{61} \approx 0{,}01333 + 0{,}01639 = 0{,}02972\) (&lt;strong&gt;Hạng 2&lt;/strong&gt;).&lt;/li&gt;
  &lt;li&gt;\(\text{RRF}(C) = \frac{1}{62} + \frac{1}{80} \approx 0{,}01613 + 0{,}01250 = 0{,}02863\) (&lt;strong&gt;Hạng 3&lt;/strong&gt;).
RRF tự động đưa đoạn A (tốt cả từ khóa lẫn ngữ nghĩa) lên đầu mà không cần cân chỉnh thang đo khó nhằn giữa điểm BM25 không bị chặn và cosin trong \([-1, 1]\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-nlp-sau-nhúng-từ-tĩnh--llm-rag-và-tokenizer&quot;&gt;Tùy chọn: NLP sau nhúng từ tĩnh — LLM, RAG và Tokenizer&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế phần hình học của Word2Vec hay GloVe. Bài trước đã giới thiệu vectơ theo ngữ cảnh của BERT; bài này cập nhật &lt;strong&gt;hệ sinh thái ứng dụng&lt;/strong&gt; được dùng rộng rãi trong các sản phẩm NLP giai đoạn 2022–2026.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Nhúng từ tĩnh vẫn là mô hình dẫn nhập trực quan cho nguyên lý “gần nhau là tương tự”. Tuy nhiên, hầu hết hệ thống NLP mới không dừng ở đó mà sử dụng &lt;strong&gt;mô hình ngôn ngữ chỉ-decoder&lt;/strong&gt; kết hợp với truy xuất thông tin, gọi công cụ hoặc trích xuất dữ liệu có cấu trúc.&lt;/p&gt;

&lt;h2 id=&quot;1-từ-một-vector-cho-mỗi-từ-đến-câu-trả-lời-được-sinh-ra&quot;&gt;1. Từ một vector cho mỗi từ đến câu trả lời được sinh ra&lt;/h2&gt;

&lt;p&gt;Một dịch vụ NLP trong giai đoạn 2024–2026 thường gồm ba thành phần chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Tokenizer tách dưới từ (BPE / Unigram: &lt;a href=&quot;https://github.com/openai/tiktoken&quot;&gt;tiktoken&lt;/a&gt;, SentencePiece).&lt;/li&gt;
  &lt;li&gt;Mô hình Transformer tinh chỉnh theo chỉ dẫn (xem bài tùy chọn Chương 08).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;RAG&lt;/strong&gt; (tùy chọn): nhúng câu truy vấn, truy xuất các đoạn tài liệu liên quan rồi đưa vào ngữ cảnh của mô hình ngôn ngữ.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bảng nhúng \(E\in\mathbb{R}^{V\times d}\) đã học trong chương này vẫn là tầng đầu tiên (tầng 0) của mô hình ngôn ngữ đó; phần triển khai thực tế xoay quanh các lớp xử lý phía trên.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-cụ-thể&quot;&gt;2. Ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;sinh-tăng-cường-truy-hồi-rag&quot;&gt;Sinh tăng cường truy hồi (RAG)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2005.11401&quot;&gt;Lewis et al., 2020&lt;/a&gt; (RAG, được áp dụng rộng rãi từ sau 2022) cùng các bộ nhúng truy xuất như Dense Passage, &lt;a href=&quot;https://arxiv.org/abs/2212.03533&quot;&gt;E5&lt;/a&gt; và &lt;a href=&quot;https://arxiv.org/abs/2308.03281&quot;&gt;GTE&lt;/a&gt; biến mô hình “truy xuất + sinh văn bản” thành kiến trúc phổ biến trong NLP doanh nghiệp. Khi đánh giá hệ thống loại này, cần kiểm tra mức độ bám sát nguồn (&lt;em&gt;groundedness&lt;/em&gt;) thay vì chỉ dựa vào các chỉ số như BLEU.&lt;/p&gt;

&lt;h3 id=&quot;trích-xuất-có-cấu-trúc-và-phân-loại&quot;&gt;Trích xuất có cấu trúc và phân loại&lt;/h3&gt;

&lt;p&gt;Thay vì xây dựng mô hình BiLSTM-CRF riêng cho từng tác vụ, nhiều nhóm kỹ sư dùng prompt hoặc tinh chỉnh LoRA cho mô hình ngôn ngữ để xuất trực tiếp định dạng JSON (phục vụ NER, phân tích cảm xúc, định tuyến yêu cầu hỗ trợ). Dù vậy, các bộ mã hóa nhỏ như BERT hay DeBERTa vẫn được ưu tiên khi độ trễ thấp và độ hiệu chỉnh xác suất (&lt;em&gt;calibration&lt;/em&gt;) quan trọng hơn một mô hình decoder 7B.&lt;/p&gt;

&lt;h3 id=&quot;tokenization-trong-thực-hành&quot;&gt;Tokenization trong thực hành&lt;/h3&gt;

&lt;p&gt;Cách chia từ vựng dưới từ (&lt;em&gt;subword&lt;/em&gt;) ảnh hưởng trực tiếp đến chi phí suy luận và chất lượng xử lý đa ngôn ngữ. Dù thuật toán BPE không mới, việc hiểu và sử dụng thành thạo các tokenizer như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tiktoken&lt;/code&gt; hoặc tokenizer của Llama trên dữ liệu thực tế nhiều nhiễu là kỹ năng quan trọng trong giai đoạn 2022–2026.&lt;/p&gt;

&lt;h2 id=&quot;3-phần-mềm-phổ-biến&quot;&gt;3. Phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/transformers&quot;&gt;huggingface/transformers&lt;/a&gt; và &lt;a href=&quot;https://github.com/huggingface/datasets&quot;&gt;datasets&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/langchain-ai/langchain&quot;&gt;langchain&lt;/a&gt; và &lt;a href=&quot;https://github.com/run-llama/llama_index&quot;&gt;llama_index&lt;/a&gt; — khung tích hợp RAG (thuật toán cốt lõi vẫn là nhúng–truy hồi–sinh).&lt;/li&gt;
  &lt;li&gt;Sentence-Transformers và E5 — các mô hình nhúng phục vụ truy hồi.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2212.03533&quot;&gt;E5 (Wang et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2005.11401&quot;&gt;RAG (Lewis et al., 2020)&lt;/a&gt; — kiến trúc được triển khai lại trong hầu hết hệ thống giai đoạn 2023–2026.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2307.09288&quot;&gt;Llama 2 (Touvron et al., 2023)&lt;/a&gt; — mô hình ngôn ngữ mở tinh chỉnh theo chỉ dẫn dùng làm bộ sinh.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-bài-này-bổ-sung-gì-cho-ghi-chú-cốt-lõi&quot;&gt;5. Bài này bổ sung gì cho ghi chú cốt lõi&lt;/h2&gt;

&lt;p&gt;Trước hết cần nắm vững số học vectơ của Word2Vec và sự khác biệt giữa nhúng tĩnh với nhúng theo ngữ cảnh. Bài này chỉ bổ sung bối cảnh ứng dụng gồm &lt;strong&gt;RAG, bộ sinh tinh chỉnh theo chỉ dẫn và tokenizer hiện đại&lt;/strong&gt;, không thay đổi phần suy diễn skip-gram cốt lõi.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=LPZh9BOjkQs&quot;&gt;Large Language Models explained briefly&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Tổng quan ngắn gọn về cách các mô hình ngôn ngữ lớn sinh câu trả lời, vượt ra ngoài nhúng từ tĩnh.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, tiếng Anh. Giải thích cơ chế biểu diễn theo ngữ cảnh bên trong Transformer thay cho một vectơ cố định cho mỗi từ.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Trình bày cách ứng dụng và vận hành các mô hình ngôn ngữ lớn trong thực tế.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>18-01 Nhúng Từ và Biểu diễn Ngôn ngữ</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter18/18_01_Word_Embeddings/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter18/18_01_Word_Embeddings</id>
   <content type="html">&lt;p&gt;Phép tính nổi tiếng nhất lịch sử NLP hiện đại không phải là một định lý giải tích phức tạp, mà là một phép cộng trừ tiểu học: \(\vec{\text{king}} - \vec{\text{man}} + \vec{\text{woman}} \approx \vec{\text{queen}}\). Làm thế nào một mạng nơ-ron nông chỉ gồm đúng hai ma trận trọng số như &lt;strong&gt;Word2Vec (Skip-gram)&lt;/strong&gt; hay phép phân tích ma trận đồng xuất hiện của &lt;strong&gt;GloVe&lt;/strong&gt; lại có thể tự động chưng cất ra cả giới tính, số ít/số nhiều lẫn quan hệ thủ đô–quốc gia? Bài học này mổ xẻ trọn vẹn cơ chế toán học và cài đặt của nhúng từ.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-nền-tảng-toán-học-và-kỹ-thuật-của-nhúng-từ&quot;&gt;Kiến thức cần nhớ: Nền tảng toán học và kỹ thuật của Nhúng Từ&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình Skip-gram và CBOW (Word2Vec):&lt;/strong&gt; Dự đoán từ ngữ cảnh quanh từ trung tâm (hoặc ngược lại) bằng tích vô hướng giữa hai ma trận nhúng \(\mathbf{v}_w\) (đầu vào) và \(\mathbf{u}_c\) (ngữ cảnh).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Lấy mẫu âm (Negative Sampling — SGNS):&lt;/strong&gt; Thay phép Softmax cực đắt trên toàn bộ $$&lt;/td&gt;
          &lt;td&gt;V&lt;/td&gt;
          &lt;td&gt;\(từ bằng\)1\(cặp dương và\)k\(cặp âm rút theo phân phối\)P_n(w) \propto \text{count}(w)^{3/4}\(, giảm độ phức tạp mỗi bước từ\)O(&lt;/td&gt;
          &lt;td&gt;V&lt;/td&gt;
          &lt;td&gt;)\(xuống\)O(k)$$.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GloVe (Global Vectors):&lt;/strong&gt; Khai thác thống kê đồng xuất hiện toàn cục bằng hồi quy bình phương có trọng số \(\mathbf{v}_i^\top \mathbf{u}_j + b_i + \tilde{b}_j \approx \ln X_{ij}\), kết nối trực tiếp phương pháp đếm ma trận với mạng dự đoán.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FastText và giới hạn từ đa nghĩa:&lt;/strong&gt; Biểu diễn từ bằng tổng các n-gram ký tự để xử lý từ hiếm/sai chính tả, đồng thời chỉ rõ giới hạn cố hữu của nhúng tĩnh (ví dụ từ “đường” trong “đường phố” và “đường ăn” bị gộp chung một vector).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-hàm-mất-mát-skip-gram-negative-sampling-sgns&quot;&gt;Giải thích: Tính tay một bước hàm mất mát Skip-gram Negative Sampling (SGNS)&lt;/h3&gt;

&lt;p&gt;Xét từ trung tâm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt; có vector \(\mathbf{v} = (1{,}0,\; 0{,}5)\), từ ngữ cảnh thật &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ngủ&lt;/code&gt; có vector \(\mathbf{u}_{+} = (0{,}8,\; 0{,}4)\), và 2 mẫu âm ngẫu nhiên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;búa&lt;/code&gt; (\(\mathbf{u}_{-,1} = (-0{,}5,\; 0{,}2)\)), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;thuế&lt;/code&gt; (\(\mathbf{u}_{-,2} = (0{,}4,\; -0{,}8)\)). Hàm loss SGNS là:
\(\mathcal{L} = -\ln \sigma(\mathbf{u}_+^\top \mathbf{v}) - \sum_{k=1}^{2} \ln \sigma(-\mathbf{u}_{-,k}^\top \mathbf{v}).\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính các tích vô hướng:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Cặp dương: \(\mathbf{u}_+^\top \mathbf{v} = 0{,}8(1{,}0) + 0{,}4(0{,}5) = 1{,}00\).&lt;/li&gt;
      &lt;li&gt;Mẫu âm 1: \(\mathbf{u}_{-,1}^\top \mathbf{v} = -0{,}5(1{,}0) + 0{,}2(0{,}5) = -0{,}40\) → đổi dấu thành \(+0{,}40\).&lt;/li&gt;
      &lt;li&gt;Mẫu âm 2: \(\mathbf{u}_{-,2}^\top \mathbf{v} = 0{,}4(1{,}0) - 0{,}8(0{,}5) = 0{,}00\) → đổi dấu vẫn là \(0{,}00\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính hàm Sigmoid và mất mát:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(\sigma(1{,}00) \approx 0{,}7311 \implies -\ln(0{,}7311) \approx 0{,}3132\).&lt;/li&gt;
      &lt;li&gt;\(\sigma(0{,}40) \approx 0{,}5987 \implies -\ln(0{,}5987) \approx 0{,}5130\).&lt;/li&gt;
      &lt;li&gt;\(\sigma(0{,}00) = 0{,}5000 \implies -\ln(0{,}5000) \approx 0{,}6931\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tổng loss:&lt;/strong&gt; \(\mathcal{L} \approx 0{,}3132 + 0{,}5130 + 0{,}6931 = 1{,}5193\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu quả tốc độ:&lt;/strong&gt; Thay vì tính \(50{,}000\) tích vô hướng cho Softmax, bước cập nhật này chỉ cần đúng \(3\) tích vô hướng (nhanh hơn hơn &lt;strong&gt;16.000 lần&lt;/strong&gt;) mà vẫn đẩy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt; lại gần &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ngủ&lt;/code&gt; và tách xa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;búa&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;thuế&lt;/code&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;nhúng-từ-biểu-diễn-ngôn-ngữ-trong-không-gian-vectơ&quot;&gt;Nhúng Từ: Biểu diễn Ngôn ngữ trong Không gian Vectơ&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/7/78/Word2vec.png/800px-Word2vec.png&quot; alt=&quot;Word2Vec Visualization&quot; /&gt;
&lt;em&gt;Hình ảnh: Minh họa nhúng Word2Vec trong không gian vectơ. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Nhúng từ (&lt;em&gt;word embedding&lt;/em&gt;) là một trong những kỹ thuật nền tảng của xử lý ngôn ngữ tự nhiên, thay đổi cách biểu diễn và xử lý văn bản trong các hệ thống học máy. Ý tưởng cốt lõi khá đơn giản: biểu diễn mỗi từ bằng một vectơ dày đặc các số thực (thường có 100–300 chiều) sao cho các từ gần nghĩa có vectơ gần nhau. Biểu diễn liên tục này thay thế các biểu diễn thưa trước đây như mã hóa &lt;em&gt;one-hot&lt;/em&gt; (vectơ hàng nghìn chiều, toàn số 0 trừ một vị trí) bằng các vectơ gọn hơn, phản ánh quan hệ ngữ nghĩa thông qua cấu trúc hình học trong không gian vectơ.&lt;/p&gt;

&lt;p&gt;Để thấy rõ vai trò của nhúng từ, cần xét hạn chế của biểu diễn rời rạc. Các phương pháp truyền thống coi từ là các ký hiệu độc lập — “king”, “queen” và “car” cách đều nhau và không chia sẻ cấu trúc nào. Với từ vựng 50.000 từ, mã hóa &lt;em&gt;one-hot&lt;/em&gt; tạo ra các vectơ 50.000 chiều trực giao đôi một, không mang thông tin về độ tương tự. Điều này cản trở khả năng tổng quát hóa: nếu mô hình học được mẫu câu “king lives in palace”, nó vẫn phải học lại độc lập với “queen lives in palace” dù hai từ gần nghĩa.&lt;/p&gt;

&lt;h3 id=&quot;từ-văn-bản--token--one-hot--bag-of-words&quot;&gt;Từ văn bản → token → one-hot / bag-of-words&lt;/h3&gt;

&lt;p&gt;Bước đầu tiên luôn là &lt;strong&gt;tokenization&lt;/strong&gt; (tách văn bản thành các từ hoặc token), sau đó chuyển sang biểu diễn số.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_tokenization.jpg&quot; alt=&quot;Tokenization&quot; /&gt;
&lt;em&gt;Hình: Câu được tách thành các token trước khi mã hóa. (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_one_hot_table.jpg&quot; alt=&quot;Bảng one-hot&quot; /&gt;
&lt;em&gt;Hình: Mỗi từ tương ứng một vector one-hot — trực giao, thưa và không mang thông tin ngữ nghĩa. (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_bag_of_words.jpg&quot; alt=&quot;Bag-of-words&quot; /&gt;
&lt;em&gt;Hình: Bag-of-words gộp các vector one-hot theo câu nên làm mất thứ tự từ. (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_onehot_limitations.jpg&quot; alt=&quot;Hạn chế one-hot / BoW&quot; /&gt;
&lt;em&gt;Hình: Ba hạn chế chính — mất thứ tự từ, biểu diễn thưa với số chiều lớn và thiếu quan hệ ngữ nghĩa. (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Nhúng từ khắc phục vấn đề này bằng cách học biểu diễn liên tục, trong đó các từ tương tự nằm gần nhau. Khoảng cách giữa vectơ “king” và “queen” nhỏ (cùng thuộc nhóm hoàng gia), còn “king” và “car” nằm xa nhau. Hơn nữa, không gian nhúng còn thể hiện các quan hệ loại suy qua phép toán vectơ: hướng từ “man” đến “woman” tương tự hướng từ “king” đến “queen”, phản ánh quan hệ giới tính. Nhờ đó, ta có thể tính loại suy bằng số học vectơ: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;king − man + woman ≈ queen&lt;/code&gt;. Cấu trúc này không được lập trình sẵn mà tự hình thành trong quá trình huấn luyện trên văn bản.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_semantic_space_2d.jpg&quot; alt=&quot;Không gian nhúng 2D&quot; /&gt;
&lt;em&gt;Hình: Các từ gần nghĩa gom cụm với nhau (vua/nữ hoàng/nam/nữ…); khoảng cách phản ánh quan hệ giữa chúng. (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_vector_arithmetic_benefits.jpg&quot; alt=&quot;Lợi ích vector hóa&quot; /&gt;
&lt;em&gt;Hình: Embedding hỗ trợ biểu diễn quan hệ ngữ nghĩa, suy luận từ vựng và học đặc trưng tự động. (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Mục tiêu huấn luyện nhúng từ dựa trên &lt;em&gt;giả thuyết phân bố&lt;/em&gt; (&lt;em&gt;distributional hypothesis&lt;/em&gt;) trong ngôn ngữ học: những từ xuất hiện trong các ngữ cảnh tương tự thường có nghĩa tương tự. Nguyên lý này cho phép học biểu diễn không giám sát trực tiếp từ kho ngữ liệu văn bản lớn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_distributional_context.jpg&quot; alt=&quot;Ngữ cảnh phân bố quanh “vua”&quot; /&gt;
&lt;em&gt;Hình: Từ “vua” thường đi cùng ngữ cảnh chiến đấu, nam giới, mạnh mẽ… — các từ đồng xuất hiện trong ngữ cảnh tương tự sẽ có embedding gần nhau. (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Các mô hình như Word2Vec và GloVe học nhúng từ bằng cách dự đoán từ ngữ cảnh từ từ đích (hoặc ngược lại), hoặc phân rã ma trận thống kê đồng xuất hiện. Các vectơ học được lưu giữ thông tin về ngữ nghĩa từ vựng, quy luật cú pháp và một phần tri thức thế giới chỉ từ thống kê đồng xuất hiện mà không cần nhãn thủ công.&lt;/p&gt;

&lt;p&gt;Nhúng từ đặt nền móng cho học sâu trong xử lý ngôn ngữ tự nhiên, cho phép mạng nơ-ron tận dụng kho văn bản chưa gán nhãn quy mô lớn để học biểu diễn và chuyển giao sang các tác vụ hạ nguồn. Trong giai đoạn 2013–2018, các bộ nhúng tiền huấn luyện như Word2Vec và GloVe là thành phần tiêu chuẩn trong hầu hết hệ thống NLP. Dù ngày nay nhúng theo ngữ cảnh từ BERT và GPT đã thay thế nhúng tĩnh ở nhiều tác vụ, việc nắm vững nhúng tĩnh vẫn cần thiết để hiểu sự phát triển của học biểu diễn trong NLP, cũng như phục vụ những ứng dụng ưu tiên tính đơn giản và hiệu quả tính toán.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Nhúng từ ánh xạ các ký hiệu rời rạc (từ) sang vectơ liên tục sao cho bảo toàn độ tương tự ngữ nghĩa. Cụ thể, với tập từ vựng \(V\) có kích thước $$&lt;/td&gt;
      &lt;td&gt;V&lt;/td&gt;
      &lt;td&gt;\(, ta học ma trận nhúng\)\mathbf{E} \in \mathbb{R}^{d \times&lt;/td&gt;
      &lt;td&gt;V&lt;/td&gt;
      &lt;td&gt;}\(, trong đó mỗi cột\)\mathbf{e}_w \in \mathbb{R}^d\(là vectơ nhúng của từ\)w\(. Số chiều nhúng thường là\)d = 100\text{–}300$$, nhỏ hơn rất nhiều so với kích thước từ vựng (10.000–100.000).&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;word2vec-mô-hình-skip-gram&quot;&gt;Word2Vec: Mô hình Skip-gram&lt;/h3&gt;

&lt;p&gt;Mô hình &lt;em&gt;skip-gram&lt;/em&gt; dự đoán các từ ngữ cảnh khi biết từ đích, dựa trên giả thuyết phân bố. Với chuỗi từ \(w_1, w_2, \ldots, w_T\) trong kho ngữ liệu, mục tiêu tối ưu là:&lt;/p&gt;

\[\max_\theta \frac{1}{T}\sum_{t=1}^T \sum_{-c \leq j \leq c, j \neq 0} \log p(w_{t+j} | w_t; \theta)\]

&lt;p&gt;trong đó \(c\) là kích thước cửa sổ ngữ cảnh (thường bằng 5), và \(\theta\) bao gồm ma trận nhúng đầu vào và trọng số đầu ra.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_context_window.jpg&quot; alt=&quot;Cửa sổ ngữ cảnh&quot; /&gt;
&lt;em&gt;Hình: Cửa sổ ngữ cảnh kích thước 1 — từ trung tâm học từ các từ lân cận (và ngược lại trong skip-gram/CBOW). (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_cbow_predict_word.jpg&quot; alt=&quot;CBOW-style: dự đoán từ giữa&quot; /&gt;
&lt;em&gt;Hình: Hai từ ngữ cảnh (one-hot) đi qua lớp ẩn nhỏ để dự đoán từ đích ở giữa. (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_onehot_to_hidden.jpg&quot; alt=&quot;One-hot → projection ẩn&quot; /&gt;
&lt;em&gt;Hình: Biểu diễn chiều từ vựng (ví dụ 5) được nén xuống chiều nhúng (ví dụ 3). (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_w1_w2_training.jpg&quot; alt=&quot;Ma trận W1, W2 khi huấn luyện&quot; /&gt;
&lt;em&gt;Hình: Quy trình đầy đủ: one-hot × W1 → lớp ẩn → × W2 → logit các từ; so sánh với nhãn thật để cập nhật trọng số. (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_embedding_matrix.jpg&quot; alt=&quot;Embedding matrix&quot; /&gt;
&lt;em&gt;Hình: Ma trận nhúng \(|V|\times d\) (ví dụ \(5\times 3\)) — mỗi hàng hoặc cột là vector đại diện cho một từ. (Minh họa từ video Word Embedding / Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Xác suất có điều kiện được tính qua hàm softmax:&lt;/p&gt;

\[p(w_O | w_I) = \frac{\exp(\mathbf{v}_{w_O}^T \mathbf{v}_{w_I})}{\sum_{w=1}^{|V|} \exp(\mathbf{v}_w^T \mathbf{v}_{w_I})}\]

&lt;p&gt;trong đó \(\mathbf{v}_{w_I}\) là vectơ nhúng đầu vào của từ \(w_I\) và \(\mathbf{v}_{w_O}\) là vectơ nhúng đầu ra của từ \(w_O\). Vì mẫu số phải tính tổng trên toàn bộ từ vựng nên chi phí tính toán rất cao, đòi hỏi các phương pháp xấp xỉ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lấy mẫu âm&lt;/strong&gt; (&lt;em&gt;negative sampling&lt;/em&gt;) xấp xỉ hàm softmax bằng cách chỉ lấy một vài từ âm thay vì tính tổng trên cả từ vựng:&lt;/p&gt;

\[\log \sigma(\mathbf{v}_{w_O}^T \mathbf{v}_{w_I}) + \sum_{i=1}^k \mathbb{E}_{w_i \sim P_n(w)}[\log \sigma(-\mathbf{v}_{w_i}^T \mathbf{v}_{w_I})]\]

&lt;p&gt;trong đó \(\sigma\) là hàm sigmoid, \(k\) là số mẫu âm (thường từ 5 đến 20), và \(P_n(w)\) là phân bố nhiễu (thường lấy phân bố unigram lũy thừa 3/4 để tăng xác suất chọn các từ hiếm). Cách này chuyển bài toán phân loại đa lớp trên toàn bộ từ vựng thành \(k+1\) bài toán phân loại nhị phân, giúp huấn luyện khả thi với từ vựng lớn.&lt;/p&gt;

&lt;p&gt;Một tính chất đáng chú ý của Word2Vec là các quan hệ ngữ nghĩa thường tương ứng với phép tịnh tiến tuyến tính trong không gian vectơ:&lt;/p&gt;

\[\mathbf{e}_{\text{queen}} \approx \mathbf{e}_{\text{king}} - \mathbf{e}_{\text{man}} + \mathbf{e}_{\text{woman}}\]

\[\mathbf{e}_{\text{Paris}} \approx \mathbf{e}_{\text{France}} - \mathbf{e}_{\text{Germany}} + \mathbf{e}_{\text{Berlin}}\]

&lt;p&gt;Các quan hệ loại suy này không được giám sát trực tiếp mà xuất hiện tự nhiên từ giả thuyết phân bố: “king” và “queen” chia sẻ nhiều ngữ cảnh về hoàng gia (ngai vàng, cung điện), còn “king” và “man” chia sẻ ngữ cảnh giới tính, tạo nên cấu trúc hình học nhất quán.&lt;/p&gt;

&lt;h3 id=&quot;glove-global-vectors&quot;&gt;GloVe: Global Vectors&lt;/h3&gt;

&lt;p&gt;GloVe đi theo hướng khác bằng cách phân rã trực tiếp ma trận thống kê đồng xuất hiện toàn cục. Gọi \(X_{ij}\) là số lần từ \(j\) xuất hiện trong ngữ cảnh của từ \(i\). GloVe tối thiểu hóa hàm mục tiêu:&lt;/p&gt;

\[J = \sum_{i,j=1}^{|V|} f(X_{ij})(\mathbf{w}_i^T \tilde{\mathbf{w}}_j + b_i + \tilde{b}_j - \log X_{ij})^2\]

&lt;p&gt;trong đó \(\mathbf{w}_i\) và \(\tilde{\mathbf{w}}_j\) lần lượt là vectơ nhúng của từ và từ ngữ cảnh, \(b_i, \tilde{b}_j\) là các hệ số điều chỉnh (&lt;em&gt;bias&lt;/em&gt;), còn \(f(X_{ij})\) là hàm trọng số:&lt;/p&gt;

\[f(x) = \begin{cases} (x/x_{\max})^\alpha &amp;amp; \text{if } x &amp;lt; x_{\max} \\ 1 &amp;amp; \text{otherwise} \end{cases}\]

&lt;p&gt;Hàm trọng số này giới hạn ảnh hưởng của các cặp từ đồng xuất hiện quá thường xuyên (như từ dừng) và gán trọng số nhỏ hơn cho các cặp hiếm. Nhờ kết hợp thống kê đồng xuất hiện toàn kho ngữ liệu với ngữ cảnh cục bộ, GloVe tạo ra nhúng từ có chất lượng ngang bằng hoặc cao hơn Word2Vec trong nhiều tác vụ.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và trực giác&lt;/h2&gt;

&lt;p&gt;Xét bài toán học nhúng cho một tập từ vựng nhỏ: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{cat, dog, car, truck, animal, vehicle}&lt;/code&gt;. Ban đầu, các vectơ được khởi tạo ngẫu nhiên. Khi duyệt qua kho văn bản:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;The cat is an animal&quot;&lt;/code&gt; → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;cat&quot;&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;animal&quot;&lt;/code&gt; đồng xuất hiện.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;The dog is an animal&quot;&lt;/code&gt; → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;dog&quot;&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;animal&quot;&lt;/code&gt; đồng xuất hiện.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;The car is a vehicle&quot;&lt;/code&gt; → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;car&quot;&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;vehicle&quot;&lt;/code&gt; đồng xuất hiện.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;The truck is a vehicle&quot;&lt;/code&gt; → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;truck&quot;&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;vehicle&quot;&lt;/code&gt; đồng xuất hiện.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mô hình dần điều chỉnh các vectơ sao cho:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;cat&quot;&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;dog&quot;&lt;/code&gt; nằm gần nhau (cùng xuất hiện với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;animal&quot;&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;car&quot;&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;truck&quot;&lt;/code&gt; nằm gần nhau (cùng xuất hiện với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;vehicle&quot;&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;cat&quot;&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;car&quot;&lt;/code&gt; nằm xa nhau (xuất hiện trong các ngữ cảnh khác biệt).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sau khi huấn luyện trên đủ dữ liệu, không gian nhúng 2D có thể sắp xếp tương tự sơ đồ sau:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;     animal
        ↑
    dog • cat
        |
    ----+---- 
        |
  truck • car
        ↓
     vehicle
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Các nhóm ngữ nghĩa (động vật và phương tiện) tách cụm rõ rệt, và trong từng nhóm các từ gần nghĩa nằm cạnh nhau. Nhờ đó ta có các quan hệ hình học như:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;cat&quot; − &quot;animal&quot; ≈ &quot;dog&quot; − &quot;animal&quot;&lt;/code&gt; (cùng biểu diễn quan hệ từ phạm trù chung đến thực thể cụ thể).&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;car&quot; + &quot;vehicle&quot; ≈ &quot;truck&quot;&lt;/code&gt; (nằm trong cùng cụm phương tiện).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cấu trúc hình học này giúp mô hình tổng quát hóa: thông tin học được về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;cat&quot;&lt;/code&gt; có thể chuyển giao sang &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;dog&quot;&lt;/code&gt; thông qua độ tương tự giữa hai vectơ.&lt;/p&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;

&lt;p&gt;Ví dụ cài đặt Word2Vec Skip-gram với lấy mẫu âm:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;collections&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Counter&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Word2VecSkipGram&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Skip-gram Word2Vec with negative sampling.
    
    Learns word embeddings by predicting context words from target words.
    Uses negative sampling to make training efficient.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Input and output embeddings
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Input: embeddings used when word is target
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Output: embeddings used when word is context
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initialize with small random values
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                                   &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;negative_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        target_words: (batch,) target word indices
        context_words: (batch,) context word indices (positive examples)
        negative_words: (batch, k) negative samples
        
        Returns negative log-likelihood
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Get embeddings
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;target_embeds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;input_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch, emb_dim)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;context_embeds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;output_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;context_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch, emb_dim)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;neg_embeds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;output_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;negative_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch, k, emb_dim)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Positive scores (target-context similarity)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;pos_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_embeds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context_embeds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch,)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;pos_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Negative scores (target-negative dissimilarity)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;neg_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bmm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neg_embeds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_embeds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch, k)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;neg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neg_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;neg_loss&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Prepare training data
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Word2Vec Embeddings&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simple corpus for demonstration
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
the cat sat on the mat .
the dog sat on the rug .
the cat and the dog are animals .
the car is a vehicle .
the truck is a vehicle .
cats and dogs are pets .
cars and trucks are vehicles .
&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;lower&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Build vocabulary
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;idx_to_word&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Corpus: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; words&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vocabulary: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; unique words&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample vocab: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate training pairs
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_training_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;window_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generate (target, context) pairs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Get context (words within window)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;context_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;window_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;context_end&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;window_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;context_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Don&apos;t pair with self
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;context_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_training_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;window_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; training pairs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample pairs: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train Word2Vec
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Word2VecSkipGram&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Small dim for demo
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training embeddings...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context_idx&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Sample negatives
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;neg_indices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# To tensors
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LongTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LongTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;context_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;negatives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LongTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neg_indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;negatives&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Analyze learned embeddings
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Analyzing Learned Embeddings&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Find nearest neighbors
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;find_nearest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx_to_word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Find k nearest words to query word&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;word_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;word_vec&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Compute cosine similarities
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;similarities&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_vec&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word_vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-10&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Get top k (excluding self)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;top_k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;similarities&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argsort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][::&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx_to_word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;similarities&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;top_k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test semantic similarity
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_words&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;dog&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;car&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;neighbors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;find_nearest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx_to_word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nearest to &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neighbors&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Embeddings learned semantic relationships from co-occurrence patterns!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Similar words (cat/dog, car/truck) have similar embeddings.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-mở-rộng-nhúng-trong-hệ-thống-gợi-ý-two-tower&quot;&gt;5. Mở rộng: Nhúng trong hệ thống gợi ý (Two-Tower)&lt;/h2&gt;

&lt;p&gt;Nguyên lý “vector gần nhau biểu thị mức độ tương tự” không chỉ áp dụng cho văn bản. Trong &lt;strong&gt;hệ thống gợi ý&lt;/strong&gt; (luồng video, thương mại điện tử), ta học hai tập biểu diễn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;User embedding&lt;/strong&gt; \(\mathbf{u} \in \mathbb{R}^d\) — biểu diễn sở thích của người dùng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Item embedding&lt;/strong&gt; \(\mathbf{v} \in \mathbb{R}^d\) — biểu diễn đặc trưng của nội dung hoặc sản phẩm.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mức độ phù hợp thường được tính bằng tích vô hướng hoặc độ tương tự cosine: \(s(u,i) = \mathbf{u}^\top \mathbf{v}\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/recsys_deep_ranking_nn.jpg&quot; alt=&quot;Mạng sâu sinh embedding&quot; /&gt;
&lt;em&gt;Hình: Mạng feedforward dùng để học biểu diễn và xếp hạng ứng viên. (Minh họa từ video giải thích recommendation system)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/recsys_embedding_128d.jpg&quot; alt=&quot;Embedding chiều 128&quot; /&gt;
&lt;em&gt;Hình: Đầu ra mạng được nén thành vector dày đặc (ví dụ \(1\times 128\)) đại diện cho sở thích người dùng hoặc đặc trưng item. (Minh họa từ video giải thích recommendation system)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Trong &lt;strong&gt;mô hình hai tháp (&lt;em&gt;two-tower&lt;/em&gt;)&lt;/strong&gt;, một tháp mã hóa người dùng và một tháp mã hóa nội dung/sản phẩm. Mô hình được huấn luyện sao cho các cặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(user, item)&lt;/code&gt; đã tương tác nằm gần nhau trong không gian nhúng, còn các cặp âm nằm xa nhau. Ưu điểm lớn khi triển khai quy mô lớn là có thể tính sẵn toàn bộ &lt;em&gt;item embedding&lt;/em&gt;; khi phục vụ trực tuyến (&lt;em&gt;serving&lt;/em&gt;), hệ thống chỉ cần mã hóa người dùng rồi tìm láng giềng gần nhất xấp xỉ (ANN) trên hàng tỷ mục.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/recsys_two_tower_matching.jpg&quot; alt=&quot;Two-tower: khớp hai vector 128-d&quot; /&gt;
&lt;em&gt;Hình: So khớp hai vector nhúng cùng số chiều (user và item) — cơ chế cốt lõi của truy xuất two-tower. (Minh họa từ video giải thích recommendation system)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;So với Word2Vec, thay vì ngữ cảnh từ xung quanh, tín hiệu huấn luyện ở đây là &lt;strong&gt;hành vi tương tác&lt;/strong&gt; (nhấp chuột, xem hết video, mua hàng). Giả thuyết phân bố trở thành: người dùng hoặc sản phẩm xuất hiện trong các ngữ cảnh tương tác tương tự sẽ có vectơ nhúng gần nhau.&lt;/p&gt;

&lt;h2 id=&quot;6-khái-niệm-liên-quan&quot;&gt;6. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Nhúng từ bắt nguồn từ ngữ nghĩa học phân bố (&lt;em&gt;distributional semantics&lt;/em&gt;) — quan điểm cho rằng nghĩa của một từ được xác định bởi ngữ cảnh sử dụng nó. Việc học vectơ sao cho các từ có ngữ cảnh tương tự nằm gần nhau chính là cách hiện thực hóa tính toán cho lý thuyết ngôn ngữ học này.&lt;/p&gt;

&lt;p&gt;Xét về mặt biểu diễn dữ liệu, nhúng từ cũng gần với các kỹ thuật giảm chiều như PCA hoặc autoencoder: vectơ &lt;em&gt;one-hot&lt;/em&gt; có số chiều bằng kích thước từ vựng được nén xuống vectơ dày đặc chiều thấp nhưng vẫn giữ được cấu trúc ngữ nghĩa. Điều này cho thấy số chiều nội tại cần thiết để biểu diễn nghĩa của từ nhỏ hơn rất nhiều so với tổng số từ.&lt;/p&gt;

&lt;p&gt;Quá trình phát triển từ nhúng tĩnh (Word2Vec, GloVe) sang nhúng theo ngữ cảnh (ELMo, BERT) khắc phục hạn chế của từ đa nghĩa. Nhúng tĩnh chỉ gán một vectơ duy nhất cho mỗi từ, nên “bank” (ngân hàng) và “bank” (bờ sông) có cùng biểu diễn. Ngược lại, nhúng theo ngữ cảnh sinh ra vectơ khác nhau tùy theo câu chứa nó.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/sa_vector_space_fruit_vs_companies.jpg&quot; alt=&quot;Không gian vector: trái cây vs công ty&quot; /&gt;
&lt;em&gt;Hình: Cụm “táo / chuối / cam…” tách khỏi cụm “Google / Microsoft / DeepSeek…”. (Minh họa từ video Transformer / Self-Attention nhập môn)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/sa_contextual_apple_company_vector.jpg&quot; alt=&quot;Sau self-attention: “Apple” theo nghĩa công ty&quot; /&gt;
&lt;em&gt;Hình: Khi câu nhắc đến điện thoại và màu sắc, vector “Apple” dịch chuyển về phía cụm các hãng công nghệ. (Minh họa từ video Transformer / Self-Attention nhập môn)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Sự chuyển dịch này đánh dấu bước tiến từ biểu diễn cố định ở cấp độ từ sang mô hình hóa ý nghĩa phụ thuộc ngữ cảnh của ngôn ngữ.&lt;/p&gt;

&lt;h2 id=&quot;7-các-bài-báo-nền-tảng&quot;&gt;7. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1301.3781&quot;&gt;“Efficient Estimation of Word Representations in Vector Space” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Tomas Mikolov, Kai Chen, Greg Corrado, Jeffrey Dean&lt;br /&gt;
Word2Vec giới thiệu hai kiến trúc hiệu quả (skip-gram và CBOW) cùng kỹ thuật lấy mẫu âm để học nhúng từ trên kho dữ liệu hàng tỷ từ. Bài báo cũng chỉ ra khả năng giải các phép loại suy ngữ nghĩa bằng số học vectơ, đưa nhúng từ trở thành thành phần phổ biến trong NLP.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://aclanthology.org/D14-1162/&quot;&gt;“GloVe: Global Vectors for Word Representation” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Jeffrey Pennington, Richard Socher, Christopher Manning&lt;br /&gt;
GloVe kết hợp ưu điểm của phân rã ma trận toàn cục và cửa sổ ngữ cảnh cục bộ bằng cách phân rã ma trận đồng xuất hiện của từ. Phương pháp đạt chất lượng ngang bằng hoặc tốt hơn Word2Vec, đồng thời gắn trực tiếp các phép toán vectơ với tỷ số xác suất đồng xuất hiện.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1802.05365&quot;&gt;“Deep contextualized word representations” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Matthew Peters, Mark Neumann, Mohit Iyyer, Matt Gardner, Christopher Clark, Kenton Lee, Luke Zettlemoyer&lt;br /&gt;
ELMo giới thiệu biểu diễn từ theo ngữ cảnh dựa trên mạng LSTM hai chiều sâu, khắc phục hạn chế của nhúng tĩnh đối với từ đa nghĩa. Bài báo cũng chỉ ra rằng các tầng khác nhau học các loại thông tin khác nhau (tầng thấp thiên về cú pháp, tầng cao thiên về ngữ nghĩa), mở đường cho BERT và các mô hình Transformer sau này.&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;Bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;p&gt;Sử dụng nhúng từ tiền huấn luyện mà không xử lý sự lệch từ vựng sẽ dẫn đến vấn đề từ ngoài từ vựng (&lt;em&gt;out-of-vocabulary&lt;/em&gt;, OOV). Khi dữ liệu tác vụ chứa các từ không có trong bộ nhúng tiền huấn luyện, có thể khắc phục bằng cách: dùng biểu diễn dưới từ (&lt;em&gt;subword&lt;/em&gt; như BPE, WordPiece), khởi tạo từ mới dựa trên trung bình các từ liên quan (chẳng hạn xấp xỉ “coronavirus” từ “virus” và “corona”), hoặc tinh chỉnh lại bộ nhúng trên dữ liệu thuộc miền chuyên biệt.&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;p&gt;Nhúng từ biểu diễn từ bằng các vectơ thực dày đặc, trong đó độ tương tự ngữ nghĩa tương ứng với sự gần gũi về mặt hình học, giúp mạng nơ-ron tổng quát hóa giữa các từ gần nghĩa. Word2Vec (skip-gram với lấy mẫu âm) và GloVe (phân rã ma trận đồng xuất hiện) đều học từ văn bản chưa gán nhãn dựa trên giả thuyết phân bố. Không gian nhúng học được thể hiện các tính chất như gom cụm ngữ nghĩa và phép toán loại suy (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;king − man + woman ≈ queen&lt;/code&gt;) mà không cần giám sát tường minh. Cùng cấu trúc hình học đó cũng được ứng dụng rộng rãi trong &lt;strong&gt;hệ thống gợi ý&lt;/strong&gt; qua &lt;em&gt;user/item embedding&lt;/em&gt; và mô hình &lt;em&gt;two-tower&lt;/em&gt;. Trong khi các mô hình nhúng theo ngữ cảnh như BERT giải quyết tốt hiện tượng đa nghĩa, nhúng tĩnh vẫn hữu ích nhờ tốc độ và tính dễ diễn giải, đồng thời là nền tảng để hiểu học biểu diễn trong NLP và nhiều lĩnh vực khác.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/930207546288223&quot;&gt;Transformer là gì? Self-Attention siêu dễ hiểu (Phần 1)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1501843101324752&quot;&gt;Word Embedding và Transformer hiểu ngôn ngữ&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1444915507374636&quot;&gt;Thuật toán gợi ý (TikTok-style recommendation)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=viZrOnJclY0&quot;&gt;Word Embedding and Word2Vec, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích rõ ràng skip-gram và giả thuyết phân bố — trọng tâm của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ISPId9Lhc1g&quot;&gt;The Illustrated Word2vec - A Gentle Intro to Word Embeddings in Machine Learning&lt;/a&gt; — Jay Alammar, tiếng Anh. Trình bày trực quan không gian vectơ từ và các ví dụ loại suy.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 2&lt;/td&gt;
          &lt;td&gt;Word Vector Representations: word2vec](https://www.youtube.com/watch?v=ERibwqs9p38) — Stanford University School of Engineering, tiếng Anh. Đi sâu vào hàm mục tiêu softmax và kỹ thuật lấy mẫu âm như phần nền tảng toán học trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>18 Xử lý Ngôn ngữ Tự nhiên</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter18/18_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter18/18_00_Introduction</id>
   <content type="html">&lt;p&gt;Với máy tính, hai chữ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cún&lt;/code&gt; chỉ là hai chuỗi mã ASCII vô hồn chẳng hề có điểm chung nào về mặt ký tự — giống hệt khoảng cách giữa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;máy kéo&lt;/code&gt;. Vậy làm sao mạng nơ-ron có thể hiểu rằng “mèo” gần với “chó”, “Hà Nội” gắn với “Việt Nam” như “Paris” gắn với “Pháp”? Chương &lt;strong&gt;Xử lý Ngôn ngữ Tự nhiên (NLP)&lt;/strong&gt; mở đầu bằng bước đột phá đã khai sinh toàn bộ kỷ nguyên ngôn ngữ hiện đại: biến từ ngữ rời rạc thành các tọa độ hình học giàu ngữ nghĩa trong không gian vector.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-xử-lý-ngôn-ngữ-tự-nhiên-bằng-học-sâu&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Xử lý Ngôn ngữ Tự nhiên bằng Học sâu&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Giả thuyết phân bố (Distributional Hypothesis):&lt;/strong&gt; “Bạn biết một từ qua những từ đứng cạnh nó” — nguyên lý ngôn ngữ học cho phép máy tự học ngữ nghĩa hoàn toàn từ ngữ cảnh văn bản thô.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhúng từ tĩnh (Word2Vec, GloVe, FastText):&lt;/strong&gt; Nén biểu diễn one-hot thưa hàng chục nghìn chiều xuống vector dày \(100\text{–}300\) chiều nơi phép cộng trừ vector phản ánh quan hệ ngữ nghĩa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tách từ con (Subword Tokenization — BPE, WordPiece):&lt;/strong&gt; Giải quyết triệt để từ ngoài từ điển (OOV) bằng cách ghép nghĩa từ các mảnh từ phổ biến.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuyển dịch sang nhúng theo ngữ cảnh và LLM (2022–2026):&lt;/strong&gt; Từ một vector cố định cho mỗi từ (không phân biệt từ đa nghĩa) sang biểu diễn động theo ngữ cảnh của Transformer, RAG và mô hình ngôn ngữ lớn.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-độ-thưa-và-tính-hình-học-giữa-one-hot-và-word-embedding&quot;&gt;Giải thích: So sánh độ thưa và tính hình học giữa One-Hot và Word Embedding&lt;/h3&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Giả sử bộ từ vựng có $$&lt;/td&gt;
      &lt;td&gt;V&lt;/td&gt;
      &lt;td&gt;= 50{,}000\(từ, trong đó `mèo` có chỉ số\)12\(, `chó` có chỉ số\)87\(, và `xe đạp` có chỉ số\)4{,}015$$.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Với biểu diễn One-Hot (\(50{,}000\) chiều):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Tích vô hướng \(\mathbf{e}_{\text{mèo}} \cdot \mathbf{e}_{\text{chó}} = 0\) và \(\mathbf{e}_{\text{mèo}} \cdot \mathbf{e}_{\text{xe đạp}} = 0\).&lt;/li&gt;
      &lt;li&gt;Khoảng cách Euclid giữa mọi cặp từ bất kỳ đều bằng nhau: \(\sqrt{1^2 + 1^2} = \sqrt{2} \approx 1{,}414\) — hoàn toàn mù ngữ nghĩa! Mỗi vector còn tốn \(50{,}000 \times 4\text{ byte} = 200\text{ KB}\) nếu lưu dạng dày.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Với Word Embedding (\(d = 300\) chiều):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Bộ nhớ mỗi từ giảm \(167\times\) xuống còn \(1{,}2\text{ KB}\).&lt;/li&gt;
      &lt;li&gt;Độ tương đồng cosin thu được sau huấn luyện điển hình: \(\cos(\mathbf{v}_{\text{mèo}}, \mathbf{v}_{\text{chó}}) \approx 0{,}78\) trong khi \(\cos(\mathbf{v}_{\text{mèo}}, \mathbf{v}_{\text{xe đạp}}) \approx 0{,}09\) — quan hệ ngữ nghĩa đã được mã hóa trực tiếp thành góc giữa các vector!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Xử lý ngôn ngữ tự nhiên (&lt;em&gt;natural language processing&lt;/em&gt;, NLP) áp dụng học sâu để phân tích và sinh ngôn ngữ tự nhiên. Chương này trình bày nhúng từ (&lt;em&gt;word embeddings&lt;/em&gt; — Word2Vec, GloVe), mô hình ngôn ngữ (GPT, BERT), các tác vụ gán nhãn chuỗi (NER, gán nhãn từ loại POS), phân loại văn bản, dịch máy, trả lời câu hỏi và sinh văn bản, cùng các kiến trúc NLP hiện đại và ứng dụng thực tiễn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý nhanh:&lt;/strong&gt; Ý tưởng “vector gần nhau biểu thị mức độ tương tự” của nhúng từ cũng là nền tảng của hệ thống gợi ý (&lt;em&gt;user/item embedding&lt;/em&gt;, kiến trúc &lt;em&gt;two-tower&lt;/em&gt;) — xem phần mở rộng trong bài nhúng từ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lộ trình trực quan (bài nhúng từ):&lt;/strong&gt; tách token (&lt;em&gt;tokenization&lt;/em&gt;) → one-hot / bag-of-words (và hạn chế của chúng) → không gian nhúng 2D cùng số học vector → cửa sổ ngữ cảnh Word2Vec / CBOW → ma trận nhúng \(W_1 \cdot W_2\). Transformer và BERT mở rộng nhúng &lt;strong&gt;tĩnh&lt;/strong&gt; thành biểu diễn &lt;strong&gt;theo ngữ cảnh&lt;/strong&gt; (cùng từ “Apple” nhưng mang nghĩa khác nhau sẽ có vector khác nhau) — nội dung nối tiếp ở Chương 08. Phần tổng hợp về mô hình ngôn ngữ chỉ-decoder (bảng nhúng token ở tầng đầu tiên, hàm mất mát cross-entropy dự đoán token kế tiếp và triển khai phục vụ) nằm ở &lt;strong&gt;Chương 26&lt;/strong&gt;.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/930207546288223&quot;&gt;Transformer là gì? Self-Attention siêu dễ hiểu (Phần 1)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1501843101324752&quot;&gt;Word Embedding và Transformer hiểu ngôn ngữ&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1444915507374636&quot;&gt;Thuật toán gợi ý (TikTok-style recommendation)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần nhúng từ, xem thêm bài &lt;strong&gt;18-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về RAG, mô hình ngôn ngữ tinh chỉnh theo chỉ dẫn và các tokenizer hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=viZrOnJclY0&quot;&gt;Word Embedding and Word2Vec, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giới thiệu trực quan cách biểu diễn mỗi từ thành một vector trong Word2Vec.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ISPId9Lhc1g&quot;&gt;The Illustrated Word2vec - A Gentle Intro to Word Embeddings in Machine Learning&lt;/a&gt; — Jay Alammar, tiếng Anh. Minh họa trực quan Word2Vec và các phép toán loại suy trên vector từ.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 2&lt;/td&gt;
          &lt;td&gt;Word Vector Representations: word2vec](https://www.youtube.com/watch?v=ERibwqs9p38) — Stanford University School of Engineering, tiếng Anh. Bài giảng chuyên sâu về biểu diễn vector từ và mục tiêu huấn luyện Word2Vec.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>17-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter17/17_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter17/17_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Suốt gần một thập kỷ, mọi bộ phát hiện đối tượng đều bị trói chặt vào hai thứ: danh sách lớp cố định (ví dụ đúng 80 lớp của COCO) và thuật toán hậu xử lý thủ công NMS. Từ năm 2022 đến 2026, cả hai rào cản đó đồng loạt bị phá vỡ: &lt;strong&gt;RT-DETR&lt;/strong&gt; loại bỏ hoàn toàn NMS nhờ khớp hai phía Hungarian, &lt;strong&gt;SAM / SAM 2&lt;/strong&gt; cắt tách bất kỳ vật thể nào trong ảnh/video chỉ bằng một cú nhấp chuột, còn &lt;strong&gt;Grounding DINO&lt;/strong&gt; tìm vật thể bằng câu mô tả tiếng người tự do!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-bước-ngoặt-của-thị-giác-máy-tính-hiện-đại-20222026&quot;&gt;Kiến thức cần nhớ: Ba bước ngoặt của Thị giác Máy tính hiện đại (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân đoạn theo Prompt (SAM &amp;amp; SAM 2):&lt;/strong&gt; Tách biệt bộ mã hóa ảnh nặng (chạy 1 lần) với bộ giải mã mặt nạ siêu nhẹ nhận prompt điểm/hộp/văn bản; SAM 2 mở rộng thêm bộ nhớ thời gian để theo dõi đối tượng xuyên suốt video.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bộ phát hiện Transformer thời gian thực (RT-DETR / RF-DETR):&lt;/strong&gt; Dùng phép khớp một-một Hungarian lúc huấn luyện nên mỗi truy vấn đối tượng (object query) tạo đúng một dự đoán, bỏ hẳn Anchor Boxes và NMS.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phát hiện từ vựng mở (Open-Vocabulary Detection — Grounding DINO, YOLO-World):&lt;/strong&gt; Trộn chéo đặc trưng ảnh với vector văn bản để phát hiện cả những vật thể chưa từng có trong tập nhãn cố định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuỗi kết hợp Grounding DINO + SAM:&lt;/strong&gt; Quy trình tiêu chuẩn công nghiệp cho gắn nhãn tự động (auto-labeling): nhập cụm từ văn bản → Grounding DINO khoanh hộp → SAM cắt chính xác mặt nạ pixel.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-bài-toán-khớp-một-một-hungarian-trong-detr-loại-bỏ-nms&quot;&gt;Giải thích: Tính tay bài toán khớp một-một Hungarian trong DETR (loại bỏ NMS)&lt;/h3&gt;

&lt;p&gt;Giả sử ảnh có 2 đối tượng thật (\(y_1\): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt;, \(y_2\): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chó&lt;/code&gt;) và bộ giải mã DETR tạo ra 3 dự đoán \((\hat{y}_1, \hat{y}_2, \hat{y}_3)\). Ma trận chi phí khớp (càng nhỏ càng tốt, gộp sai số lớp + sai số hộp GIoU) với đối tượng 3 là lớp rỗng \(\varnothing\) (no-object) cho bởi:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\hat{y}_1\): chi phí với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt; \(= 0{,}2\), với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chó&lt;/code&gt; \(= 2{,}5\), với \(\varnothing = 1{,}0\)&lt;/li&gt;
  &lt;li&gt;\(\hat{y}_2\): chi phí với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt; \(= 0{,}3\), với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chó&lt;/code&gt; \(= 0{,}4\), với \(\varnothing = 1{,}0\)&lt;/li&gt;
  &lt;li&gt;\(\hat{y}_3\): chi phí với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt; \(= 3{,}0\), với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chó&lt;/code&gt; \(= 2{,}8\), với \(\varnothing = 0{,}1\)&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;So sánh hai phương án gán song ánh:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Phương án A (\(\hat{y}_1 \to \text{mèo},\; \hat{y}_2 \to \text{chó},\; \hat{y}_3 \to \varnothing\)): tổng chi phí \(= 0{,}2 + 0{,}4 + 0{,}1 = 0{,}7\).&lt;/li&gt;
      &lt;li&gt;Phương án B (\(\hat{y}_2 \to \text{mèo},\; \hat{y}_1 \to \text{chó},\; \hat{y}_3 \to \varnothing\)): tổng chi phí \(= 0{,}3 + 2{,}5 + 0{,}1 = 2{,}9\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hệ quả kiến trúc:&lt;/strong&gt; Thuật toán Hungarian chọn phương án A (\(0{,}7\)). Vì &lt;strong&gt;chỉ duy nhất một truy vấn&lt;/strong&gt; được khớp vào &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mèo&lt;/code&gt; (còn mọi truy vấn dư đều bị phạt hướng về \(\varnothing\)), mạng tự học cách không bao giờ đẻ ra hai hộp chồng lên nhau — xóa sổ hoàn toàn nhu cầu dùng NMS!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-phát-hiện-và-phân-đoạn-sau-yolo--mask-r-cnn&quot;&gt;Tùy chọn: Phát hiện và phân đoạn sau YOLO / Mask R-CNN&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết về bộ phát hiện một/hai giai đoạn hay các ghi chú về YOLO và Faster R-CNN. Nội dung bổ sung các mô hình được sử dụng rộng rãi trong thực tế giai đoạn 2023–2025: &lt;strong&gt;SAM/SAM 2&lt;/strong&gt;, &lt;strong&gt;RT-DETR&lt;/strong&gt;, &lt;strong&gt;Grounding DINO&lt;/strong&gt; và các phiên bản YOLO mới.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Các khái niệm cốt lõi của chương như IoU, NMS và cơ chế ghép cặp dự đoán vẫn là tiêu chuẩn quyết định một hộp bao có chính xác hay không:&lt;/p&gt;

\[\mathrm{IoU}(A,B) = \frac{|A\cap B|}{|A\cup B|}.\]

&lt;p&gt;Tuy nhiên, các kiến trúc xoay quanh những chỉ số này đã thay đổi đáng kể.&lt;/p&gt;

&lt;h2 id=&quot;1-phân-đoạn-theo-prompt-sam-và-sam-2&quot;&gt;1. Phân đoạn theo prompt: SAM và SAM 2&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.02643&quot;&gt;Kirillov et al., 2023&lt;/a&gt; (Segment Anything) mô hình hóa bài toán phân đoạn như một tác vụ nền tảng &lt;strong&gt;theo prompt&lt;/strong&gt;: đầu vào là điểm, hộp bao hoặc mặt nạ sơ bộ, đầu ra là mặt nạ của từng thể hiện đối tượng. &lt;a href=&quot;https://arxiv.org/abs/2408.00714&quot;&gt;Ravi et al., 2024&lt;/a&gt; (SAM 2) bổ sung bộ nhớ theo luồng thời gian để xử lý &lt;strong&gt;video&lt;/strong&gt;. Trong quy trình khoa học dữ liệu thực tế, các mô hình này thường dùng để hỗ trợ gán nhãn nhanh (chấm vài điểm, xuất mặt nạ rồi huấn luyện một mô hình chuyên biệt nhỏ hơn), chứ không thay thế U-Net khi đã có tập dữ liệu y tế được gán nhãn chi tiết ở mức pixel.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-cụ-thể&quot;&gt;2. Ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;bộ-phát-hiện-detr-thời-gian-thực&quot;&gt;Bộ phát hiện DETR thời gian thực&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.08069&quot;&gt;Zhao et al., 2024&lt;/a&gt; (RT-DETR) cải thiện tốc độ cho dòng bộ phát hiện dựa trên Transformer đến mức có thể thay thế YOLO trong một số hệ thống thực tế, trong khi vẫn đánh giá bằng chỉ số mAP như phần lý thuyết đã trình bày.&lt;/p&gt;

&lt;h3 id=&quot;phát-hiện-từ-vựng-mở-grounding-dino--sam&quot;&gt;Phát hiện từ vựng mở: Grounding DINO + SAM&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.05499&quot;&gt;Liu et al., 2023&lt;/a&gt; (Grounding DINO) nhận truy vấn &lt;strong&gt;văn bản&lt;/strong&gt; (ví dụ “mũ bảo hiểm đỏ”) và trả về hộp bao tương ứng. Kết hợp Grounding DINO với SAM (“Grounded SAM”) là mẫu quy trình phổ biến trong gán nhãn dữ liệu và tri giác robot giai đoạn 2024–2026. Dù vậy, với các bài toán có tập nhãn cố định như kiểm đếm mã sản phẩm (SKU) trong nhà máy, bộ phát hiện tập đóng kiểu COCO vẫn là lựa chọn phù hợp.&lt;/p&gt;

&lt;h3 id=&quot;yolo-trong-triển-khai-thực-tế&quot;&gt;YOLO trong triển khai thực tế&lt;/h3&gt;

&lt;p&gt;Các phiên bản Ultralytics &lt;strong&gt;YOLOv8 / YOLO11&lt;/strong&gt; vẫn giữ thiết kế tích chập một giai đoạn, phù hợp khi yêu cầu về độ trễ thấp và khả năng xuất sang các định dạng triển khai (ONNX, TensorRT, CoreML) quan trọng hơn khả năng nhận dạng từ vựng mở.&lt;/p&gt;

&lt;h2 id=&quot;3-phần-mềm-phổ-biến&quot;&gt;3. Phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/sam2&quot;&gt;facebookresearch/sam2&lt;/a&gt; và Segment Anything.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/IDEA-Research/GroundingDINO&quot;&gt;IDEA-Research/GroundingDINO&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ultralytics/ultralytics&quot;&gt;ultralytics/ultralytics&lt;/a&gt; và &lt;a href=&quot;https://github.com/lyuwenyu/RT-DETR&quot;&gt;lyuwenyu/RT-DETR&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.02643&quot;&gt;Segment Anything (Kirillov et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2408.00714&quot;&gt;SAM 2 (Ravi et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.05499&quot;&gt;Grounding DINO (Liu et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.08069&quot;&gt;RT-DETR (Zhao et al., 2024)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-bài-này-bổ-sung-gì-cho-ghi-chú-cốt-lõi&quot;&gt;5. Bài này bổ sung gì cho ghi chú cốt lõi&lt;/h2&gt;

&lt;p&gt;Trước hết cần nắm vững cơ chế ghép cặp dự đoán và quy trình R-CNN/YOLO trong các bài cốt lõi. Bài này bổ sung các đầu phát hiện và phân đoạn &lt;strong&gt;theo prompt hoặc từ vựng mở&lt;/strong&gt; được dùng phổ biến trong các hệ thống giai đoạn 2023–2026.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=OhxJkqD1vuE&quot;&gt;Explaining the Segment Anything Model - Network architecture, Dataset, Training&lt;/a&gt; — Neural Breakdown with AVB, tiếng Anh. Giải thích kiến trúc, dữ liệu và cách huấn luyện của Segment Anything — mô hình phân đoạn theo prompt trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 11&lt;/td&gt;
          &lt;td&gt;Detection and Segmentation](https://www.youtube.com/watch?v=nDPWywWRIRo) — Stanford University School of Engineering, tiếng Anh. Ôn lại bài toán phát hiện và phân đoạn cổ điển mà SAM tổng quát hóa.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, tiếng Anh. Nền tảng về mạng xương sống thị giác bên dưới các mô hình phân đoạn theo prompt.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>17-01 Cơ sở Phát hiện Đối tượng</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter17/17_01_Object_Detection/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter17/17_01_Object_Detection</id>
   <content type="html">&lt;p&gt;Chọn YOLO tốc độ 120 khung hình/giây hay Faster R-CNN độ chính xác cao cho vật thể nhỏ? Câu trả lời không bao giờ là “cái nào mới hơn thì tốt hơn”, mà phụ thuộc vào ngân sách độ trễ, kích thước vật thể và phần cứng triển khai của bạn. Mục tổng quan này kết nối trực tiếp lý thuyết hình học (&lt;strong&gt;17-01-01&lt;/strong&gt;) với cài đặt PyTorch (&lt;strong&gt;17-01-02&lt;/strong&gt;) để bạn xây dựng trực giác thiết kế hệ thống phát hiện đối tượng.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hệ-quy-chiếu-chọn-kiến-trúc-phát-hiện-đối-tượng&quot;&gt;Kiến thức cần nhớ: Hệ quy chiếu chọn kiến trúc Phát hiện Đối tượng&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hai giai đoạn (Faster R-CNN + FPN):&lt;/strong&gt; Mạng đề xuất vùng (RPN) lọc ứng viên trước rồi trích xuất đặc trưng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RoIAlign&lt;/code&gt; trên từng hộp — mạnh về vật thể nhỏ, cảnh dày đặc, nhưng độ trễ cao hơn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Một giai đoạn (YOLO / RetinaNet / FCOS):&lt;/strong&gt; Dự đoán trực tiếp hộp bao và xác suất lớp trên các lưới đặc trưng đa tỷ lệ — tối ưu cho camera thời gian thực và thiết bị biên.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kim tự tháp đặc trưng (Feature Pyramid Network — FPN):&lt;/strong&gt; Trộn đặc trưng sâu (giàu ngữ nghĩa) với đặc trưng nông (độ phân giải cao) giúp phát hiện đồng thời cả biển báo nhỏ xíu lẫn tòa nhà lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mắt xích lý thuyết – thực hành:&lt;/strong&gt; Nắm chắc IoU/NMS/mAP trước khi tinh chỉnh Faster R-CNN trên tập dữ liệu tùy chỉnh.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-nhanh-tổng-số-hộp-neo-anchor-boxes-trên-kim-tự-tháp-đặc-trưng-3-mức&quot;&gt;Giải thích: Tính nhanh tổng số hộp neo (Anchor Boxes) trên kim tự tháp đặc trưng 3 mức&lt;/h3&gt;

&lt;p&gt;Giả sử ảnh đầu vào có kích thước \(640 \times 640\) đi qua xương sống FPN tạo ra 3 bản đồ đặc trưng với bước nhảy (stride) \(8, 16, 32\), và mỗi vị trí lưới đặt \(3\) hộp neo với các tỷ lệ khung hình khác nhau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mức P3 (stride 8 — bắt vật thể nhỏ):&lt;/strong&gt; Lưới \(80 \times 80 = 6{,}400\) ô → \(6{,}400 \times 3 = 19{,}200\) hộp neo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mức P4 (stride 16 — bắt vật thể trung bình):&lt;/strong&gt; Lưới \(40 \times 40 = 1{,}600\) ô → \(1{,}600 \times 3 = 4{,}800\) hộp neo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mức P5 (stride 32 — bắt vật thể lớn):&lt;/strong&gt; Lưới \(20 \times 20 = 400\) ô → \(400 \times 3 = 1{,}200\) hộp neo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng cộng:&lt;/strong&gt; \(19{,}200 + 4{,}800 + 1{,}200 = 25{,}200\) hộp ứng viên trên mỗi khung hình — trong đó hơn \(99\%\) là nền! Con số này giải thích ngay vì sao &lt;strong&gt;Focal Loss&lt;/strong&gt; và &lt;strong&gt;NMS&lt;/strong&gt; lại tối quan trọng để kiểm soát mất cân bằng lớp và lọc hộp trùng.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chủ đề phát hiện đối tượng (&lt;em&gt;object detection&lt;/em&gt;) được chia thành hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết&lt;/strong&gt; — IoU, hồi quy hộp bao (&lt;em&gt;bounding box&lt;/em&gt;), RPN và trực giác hoạt động.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt&lt;/strong&gt; — mã nguồn minh họa, các bài báo nền tảng và những lỗi thường gặp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=svn9-xV7wjk&quot;&gt;How YOLO Object Detection Works&lt;/a&gt; — DeepBean, tiếng Anh. Trình bày cách chia lưới, dự đoán hộp bao và điểm tin cậy đối tượng (&lt;em&gt;objectness&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 11&lt;/td&gt;
          &lt;td&gt;Detection and Segmentation](https://www.youtube.com/watch?v=nDPWywWRIRo) — Stanford University School of Engineering, tiếng Anh. Đặt YOLO trong bức tranh chung cùng các bộ phát hiện hai giai đoạn được so sánh trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, tiếng Anh. Làm rõ loại đặc trưng mà mạng xương sống tích chập cần trích xuất trước khi gắn thêm đầu phát hiện.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>17-01-02 Cài đặt Phát hiện Đối tượng</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter17/17_01_02_Object_Detection_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter17/17_01_02_Object_Detection_Implementation</id>
   <content type="html">&lt;p&gt;Cài đặt một bộ phát hiện đối tượng thực thụ với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torchvision&lt;/code&gt; khác hẳn bài toán phân loại ảnh ở một điểm cốt lõi: mỗi bức ảnh trong cùng một batch lại có &lt;strong&gt;số lượng hộp bao khác nhau&lt;/strong&gt; (ảnh này có 1 vật thể, ảnh kia có 12 vật thể), nên bạn không thể xếp chồng nhãn thành một tensor hình chữ nhật thông thường! Bài thực hành này dẫn bạn qua trọn bộ kỹ thuật tinh chỉnh Faster R-CNN: thay &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FastRCNNPredictor&lt;/code&gt;, viết &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;collate_fn&lt;/code&gt; chuẩn xác, xử lý định dạng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;boxes&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;labels&lt;/code&gt; và chạy suy luận kèm hậu xử lý ngưỡng tin cậy.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-kỹ-thuật-triển-khai-faster-r-cnn-thực-chiến-trong-pytorch&quot;&gt;Kiến thức cần nhớ: Kỹ thuật triển khai Faster R-CNN thực chiến trong PyTorch&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thay thế đầu dự đoán lớp và hộp (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FastRCNNPredictor&lt;/code&gt;):&lt;/strong&gt; Giữ nguyên xương sống ResNet-FPN và mạng RPN tiền huấn luyện COCO, chỉ đổi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;num_classes = N + 1&lt;/code&gt; (luôn cộng thêm lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; cho nền background!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cấu trúc Dataset &amp;amp; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;collate_fn&lt;/code&gt; động:&lt;/strong&gt; Trả về cặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(image, target_dict)&lt;/code&gt; với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;boxes&lt;/code&gt; dạng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[x_min, y_min, x_max, y_max]&lt;/code&gt; thỏa mãn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x_max &amp;gt; x_min&lt;/code&gt; và dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;collate_fn=lambda b: tuple(zip(*b))&lt;/code&gt; để giữ list các ảnh/nhãn có chiều dài khác nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hành vi hai chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train()&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval()&lt;/code&gt; của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torchvision&lt;/code&gt;:&lt;/strong&gt; Ở chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train()&lt;/code&gt;, mô hình nhận &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(images, targets)&lt;/code&gt; và trả về dictionary các thành phần loss (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss_classifier&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss_box_reg&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss_objectness&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss_rpn_box_reg&lt;/code&gt;); ở chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval()&lt;/code&gt;, nó chỉ nhận &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;images&lt;/code&gt; và trả về dự đoán đã qua NMS.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tăng cường dữ liệu đồng bộ hình học:&lt;/strong&gt; Mọi phép lật ngang, cắt hoặc đổi tỷ lệ ảnh đều phải biến đổi tọa độ hộp bao tương ứng (như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x_min_new = W - x_max&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-biến-đổi-tọa-độ-hộp-bao-khi-lật-ngang-ảnh-horizontal-flip-và-đổi-kích-thước&quot;&gt;Giải thích: Biến đổi tọa độ hộp bao khi lật ngang ảnh (Horizontal Flip) và đổi kích thước&lt;/h3&gt;

&lt;p&gt;Giả sử ảnh gốc có chiều rộng \(W = 800\), chiều cao \(H = 600\) và một hộp bao có tọa độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[x_min, y_min, x_max, y_max] = [120, 100, 320, 400]&lt;/code&gt;.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lật ngang ảnh (Horizontal Flip):&lt;/strong&gt; Chiều dọc \(y\) giữ nguyên, còn trục ngang lật đối xứng qua \(W = 800\) (chú ý đảo vai trò &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x_min&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x_max&lt;/code&gt;!):
    &lt;ul&gt;
      &lt;li&gt;
\[x_{\min}&apos; = W - x_{\max} = 800 - 320 = 480\]
      &lt;/li&gt;
      &lt;li&gt;
\[x_{\max}&apos; = W - x_{\min} = 800 - 120 = 680\]
      &lt;/li&gt;
      &lt;li&gt;Hộp mới: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[480, 100, 680, 400]&lt;/code&gt; (kiểm tra chiều rộng vẫn là \(680 - 480 = 200\) và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x_max&apos; &amp;gt; x_min&apos;&lt;/code&gt;).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thu nhỏ ảnh về \(400 \times 300\) (hệ số \(s_x = 0{,}5, s_y = 0{,}5\)):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Nhân các tọa độ theo trục tương ứng: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[240, 50, 340, 200]&lt;/code&gt;.&lt;/li&gt;
      &lt;li&gt;Nếu một lỗi nhỏ trong augmentation để lọt hộp suy biến có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x_max &amp;lt;= x_min&lt;/code&gt; (diện tích bằng 0), Faster R-CNN sẽ lập tức báo lỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AssertionError&lt;/code&gt; trong quá trình tính toán RPN.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;

&lt;p&gt;Ví dụ cài đặt đầy đủ theo kiến trúc Faster R-CNN:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision.models.detection&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fasterrcnn_resnet50_fpn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision.models.detection.faster_rcnn&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;FastRCNNPredictor&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision.transforms&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Object Detection with Faster R-CNN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Load pre-trained Faster R-CNN
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Loading Pre-trained Faster R-CNN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fasterrcnn_resnet50_fpn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DEFAULT&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Faster R-CNN architecture:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Backbone: ResNet-50 + Feature Pyramid Network&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Region Proposal Network (RPN): Generates object proposals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  RoI Pooling: Extracts features from proposals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Detection Head: Classifies and refines boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Adapt for custom dataset (e.g., 10 classes + background)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 10 object classes + background
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Replace the classifier
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;roi_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;box_predictor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cls_score&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;roi_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;box_predictor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;FastRCNNPredictor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adapted for &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; object classes + background&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 2. Prepare custom dataset format
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Dataset Format for Object Detection&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CustomDetectionDataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Object detection dataset format.
    
    Each sample returns:
    - image: (3, H, W) tensor
    - target: dictionary with:
        - boxes: (N, 4) tensor of [x1, y1, x2, y2] coordinates
        - labels: (N,) tensor of class indices
        - (optional) masks, keypoints, etc.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;annotations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;annotations&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__len__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__getitem__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Load image (simulated here)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Get annotations for this image
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [[x1,y1,x2,y2], ...]
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [class1, class2, ...]
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Convert to tensors
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;as_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;as_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;int64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create dummy data for demonstration
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Creating simulated detection dataset...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simulate 100 images with random objects
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;dummy_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;600&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;800&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simulate annotations (random boxes and classes)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dummy_annotations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n_objects&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1-4 objects per image
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Random boxes (x1, y1, x2, y2)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_objects&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;700&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;800&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;600&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Classes 1-10
&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;dummy_annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CustomDetectionDataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dummy_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dummy_annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                         &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;collate_fn&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dataset: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; images&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample annotation: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dummy_annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 3. Training
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;3. Training Object Detector&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Move model to device
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;cuda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cuda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;is_available&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Optimizer
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.005&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0005&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training for &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; epochs...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Using dummy data - in practice, use real annotated images)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward pass returns loss dict during training
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss_dict&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Combine losses
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training complete!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 4. Inference
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;4. Running Inference&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test on one image
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_img&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;600&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;800&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions for test image:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Boxes shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Labels shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Scores shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Filter by confidence threshold
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;confidence_threshold&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;confidence_threshold&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Detections with confidence &amp;gt; &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;confidence_threshold&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; objects detected&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;box&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;score&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;    Class &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: box=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;box&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, confidence=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;score&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Ví dụ cài đặt bộ phát hiện một giai đoạn kiểu YOLO:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single-Stage Detection (YOLO-style)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSingleStageDetector&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Simplified YOLO-style detector for educational purposes.
    
    Architecture:
    - Backbone CNN extracts features
    - Detection head predicts boxes + classes for grid cells
    - Each cell predicts B boxes with (x, y, w, h, confidence, class_probs)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backbone (simplified - use any CNN)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;backbone&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Detection head
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Each grid cell outputs: B boxes × (5 + num_classes)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# 5 = (x, y, w, h, confidence)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;output_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;detection_head&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (B, 3, H, W) images
        
        Returns: (B, grid_size, grid_size, num_boxes, 5+num_classes)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Extract features
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backbone&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, 512, grid_size, grid_size)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Predict detections
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detection_head&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Reshape to (B, grid, grid, boxes, 5+classes)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;permute&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, grid, grid, boxes, ...)
&lt;/span&gt;        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;detector&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSingleStageDetector&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single-stage detector architecture:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Grid size: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Boxes per cell: 3&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Classes: 10&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Total predictions: 13×13×3 = 507 boxes per image&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;416&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;416&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Batch of 2, 416×416 images
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;detector&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Output shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 13, 13, 3, 15)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dimensions: (batch, grid_y, grid_x, boxes, 5+classes)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Each box prediction has:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - 4 coordinates (x, y, w, h)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - 1 confidence score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - 10 class probabilities&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single forward pass produces all detections - very fast!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Phát hiện đối tượng gắn bó mật thiết với phân loại ảnh thông qua mạng trích xuất đặc trưng tích chập. Các mạng xương sống (&lt;em&gt;backbone&lt;/em&gt; như ResNet, VGG, MobileNet) thường là mạng phân loại được điều chỉnh bằng cách bỏ các tầng phân loại cuối và gắn thêm đầu phát hiện. Những đặc trưng học được cho bài toán phân loại — như cạnh, kết cấu và bộ phận đối tượng — chuyển giao tự nhiên sang phát hiện đối tượng vì cả hai tác vụ đều cần nhận diện hình dáng đối tượng. Tuy nhiên, phát hiện đối tượng còn đòi hỏi định vị chính xác, xử lý nhiều đối tượng ở nhiều tỷ lệ kích thước và phân biệt đối tượng với nền. Vì vậy, bộ phân loại tiền huấn luyện trên ImageNet là điểm khởi đầu phù hợp, nhưng cần bổ sung các thành phần kiến trúc như FPN (cho đa tỷ lệ) và RPN (cho đề xuất vùng).&lt;/p&gt;

&lt;p&gt;So sánh với phân đoạn ngữ nghĩa (&lt;em&gt;semantic segmentation&lt;/em&gt;) giúp thấy rõ các mức độ phân tích ảnh khác nhau. Phân loại gán một nhãn cho toàn bộ ảnh; phát hiện gán nhãn cùng hộp bao cho từng đối tượng; phân đoạn ngữ nghĩa gán nhãn cho từng pixel để xác định chính xác đường biên; còn phân đoạn thể hiện (&lt;em&gt;instance segmentation&lt;/em&gt;) kết hợp cả hai để tạo mặt nạ ở mức pixel cho từng thể hiện riêng lẻ. Lộ trình từ mức ảnh đến mức pixel phản ánh sự đánh đổi giữa độ chi tiết thông tin và chi phí tính toán. Phát hiện đối tượng nằm ở điểm cân bằng: cung cấp vị trí đối tượng mà không đòi hỏi chi phí gán nhãn và suy luận ở cấp pixel.&lt;/p&gt;

&lt;p&gt;Mối liên hệ giữa phát hiện đối tượng và cơ chế &lt;em&gt;attention&lt;/em&gt; ngày càng rõ nét trong các kiến trúc hiện đại. DETR (&lt;em&gt;Detection Transformer&lt;/em&gt;) sử dụng Transformer để coi phát hiện đối tượng như bài toán dự đoán tập hợp (&lt;em&gt;set prediction&lt;/em&gt;), dự đoán song song tất cả các đối tượng mà không cần hộp neo hay NMS. Cơ chế &lt;em&gt;attention&lt;/em&gt; học cách tập trung vào vị trí và phạm vi của từng đối tượng, cho phép huấn luyện đầu–cuối gọn gàng thay cho quy trình nhiều bước thủ công của các bộ phát hiện cổ điển.&lt;/p&gt;

&lt;p&gt;Quá trình phát triển từ R-CNN sang Fast R-CNN rồi Faster R-CNN là ví dụ điển hình về việc tối ưu hóa từng nút thắt tính toán. R-CNN chạy CNN riêng lẻ cho từng vùng đề xuất (khoảng 2000 lượt lan truyền xuôi mỗi ảnh, rất chậm). Fast R-CNN trích xuất đặc trưng một lần cho toàn ảnh rồi dùng RoI pooling để lấy đặc trưng cho từng đề xuất, giảm xuống còn một lượt lan truyền xuôi. Faster R-CNN đưa luôn bước sinh đề xuất vào trong mạng qua RPN, tạo thành hệ thống khả vi và huấn luyện đầu–cuối. Mỗi bước cải tiến đều xử lý một điểm nghẽn cụ thể trong khi vẫn giữ hoặc nâng cao độ chính xác.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1311.2524&quot;&gt;“Rich feature hierarchies for accurate object detection and semantic segmentation” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ross Girshick, Jeff Donahue, Trevor Darrell, Jitendra Malik&lt;br /&gt;
R-CNN đưa CNN vào bài toán phát hiện đối tượng thông qua đề xuất vùng: dùng thuật toán &lt;em&gt;selective search&lt;/em&gt; sinh khoảng 2000 vùng đề xuất mỗi ảnh, đưa từng vùng qua AlexNet để trích xuất đặc trưng, rồi phân loại bằng SVM và tinh chỉnh hộp bao bằng hồi quy. Dù tốn nhiều chi phí tính toán, R-CNN đạt bước tiến lớn so với các phương pháp đặc trưng thủ công, khẳng định hiệu quả của học chuyển giao từ ImageNet sang phát hiện đối tượng và mở đường cho họ mô hình phát hiện dựa trên vùng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1504.08083&quot;&gt;“Fast R-CNN” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ross Girshick&lt;br /&gt;
Fast R-CNN khắc phục nút thắt tốc độ của R-CNN bằng cách chia sẻ tính toán tích chập giữa các vùng đề xuất thông qua lớp &lt;em&gt;RoI (Region of Interest) pooling&lt;/em&gt;. Ảnh chỉ cần đi qua CNN một lần để tạo bản đồ đặc trưng dùng chung, sau đó RoI pooling trích ra vector đặc trưng kích thước cố định cho từng đề xuất. Nhờ vậy, số lượt lan truyền xuôi giảm từ 2000 xuống còn 1 (nhanh hơn khoảng 10 lần), đồng thời độ chính xác tăng nhờ huấn luyện chung bộ trích đặc trưng, phân loại và hồi quy hộp bao với hàm mất mát đa tác vụ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1506.01497&quot;&gt;“Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun&lt;br /&gt;
Faster R-CNN thay thế &lt;em&gt;selective search&lt;/em&gt; bằng Mạng đề xuất vùng (RPN), giúp toàn bộ hệ thống khả vi và huấn luyện đầu–cuối. RPN dùng các lớp tích chập để dự đoán điểm &lt;em&gt;objectness&lt;/em&gt; và độ lệch hộp bao tại mọi vị trí trên bản đồ đặc trưng, đồng thời chia sẻ đặc trưng với phần phát hiện, đạt tốc độ gần thời gian thực (5 FPS). Cơ chế hộp neo được giới thiệu trong bài báo này trở thành chuẩn mực cho nhiều bộ phát hiện sau đó.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1506.02640&quot;&gt;“You Only Look Once: Unified, Real-Time Object Detection” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi&lt;br /&gt;
YOLO đặt bài toán phát hiện đối tượng thành bài toán hồi quy trực tiếp từ pixel ảnh sang tọa độ hộp bao và xác suất lớp trong một lượt lan truyền xuôi duy nhất, đạt tốc độ thời gian thực (45 FPS). Bằng cách chia ảnh thành lưới và để mỗi ô dự đoán trực tiếp, YOLO loại bỏ hoàn toàn giai đoạn đề xuất vùng. Tuy độ chính xác ban đầu thấp hơn Faster R-CNN (nhất là với đối tượng nhỏ), tốc độ của YOLO mở ra khả năng ứng dụng trong xe tự lái và robot, đặt nền móng cho dòng bộ phát hiện một giai đoạn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1612.03144&quot;&gt;“Feature Pyramid Networks for Object Detection” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Tsung-Yi Lin, Piotr Dollár, Ross Girshick, Kaiming He, Bharath Hariharan, Serge Belongie&lt;br /&gt;
FPN giải quyết bài toán phát hiện đa tỷ lệ bằng cách xây dựng kim tự tháp đặc trưng giàu ngữ nghĩa ở mọi độ phân giải, kết hợp đặc trưng tầng thấp (độ phân giải không gian cao nhưng ngữ nghĩa yếu) với đặc trưng tầng cao (độ phân giải thấp nhưng ngữ nghĩa mạnh) qua nhánh từ trên xuống (&lt;em&gt;top-down&lt;/em&gt;) và các kết nối ngang. Nhờ đó, mô hình phát hiện tốt cả đối tượng lớn lẫn đối tượng nhỏ. Mẫu kiến trúc kết hợp hai chiều &lt;em&gt;bottom-up&lt;/em&gt; và &lt;em&gt;top-down&lt;/em&gt; này cũng được áp dụng rộng rãi cho phân đoạn ảnh và các tác vụ dự đoán dày đặc khác.&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;Bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;p&gt;Thiết kế hộp neo ảnh hưởng đáng kể đến độ chính xác nhưng thường bị bỏ qua. Hộp neo cần phản ánh tỷ lệ khung hình và kích thước đặc trưng của đối tượng trong tập dữ liệu: chẳng hạn, với người đi bộ (cao, hẹp) nên dùng tỷ lệ 1:3 hoặc 1:4; với ô tô (rộng hơn) nên dùng 2:1 hoặc 3:2. Có thể dùng phân cụm &lt;em&gt;k-means&lt;/em&gt; trên các hộp bao trong tập huấn luyện để chọn kích thước hộp neo phù hợp. Quá nhiều hộp neo gây tốn tính toán mà không tăng độ chính xác, còn quá ít dễ bỏ sót các dạng đối tượng quan trọng. Thông thường, YOLO và Faster R-CNN dùng 9 hộp neo (3 tỷ lệ kích thước × 3 tỷ lệ khung hình) tại mỗi vị trí.&lt;/p&gt;

&lt;p&gt;Việc chọn ngưỡng NMS quyết định sự đánh đổi giữa &lt;em&gt;precision&lt;/em&gt; và &lt;em&gt;recall&lt;/em&gt;. Ngưỡng IoU thấp (ví dụ 0.3) loại bỏ nhiều hộp chồng lấn hơn, giảm dự đoán trùng lặp nhưng có thể vô tình xóa nhầm đối tượng nằm sát nhau. Ngưỡng cao (ví dụ 0.7) giữ lại nhiều hộp hơn, phù hợp với cảnh đông đúc nhưng dễ để lọt dự đoán trùng. Vì vậy, nên chọn ngưỡng cao hơn cho cảnh đông và ngưỡng thấp hơn cho cảnh thưa.&lt;/p&gt;

&lt;p&gt;Mất cân bằng lớp là vấn đề lớn trong phát hiện đối tượng: phần lớn hộp neo rơi vào nền, tạo tỷ lệ chênh lệch giữa nền và đối tượng thường từ 1000:1 trở lên. Nếu không xử lý, mô hình dễ rơi vào lời giải tầm thường là dự đoán toàn bộ là nền (đạt độ chính xác tổng thể tới 99.9% nhưng vô dụng). Các kỹ thuật khắc phục phổ biến gồm &lt;em&gt;hard negative mining&lt;/em&gt; (tập trung huấn luyện trên các mẫu nền khó, bỏ qua mẫu dễ), &lt;em&gt;focal loss&lt;/em&gt; (giảm trọng số của các mẫu phân loại dễ) và lấy mẫu cân bằng giữa mẫu đối tượng và mẫu nền trong mỗi batch.&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;p&gt;Phát hiện đối tượng mở rộng phân loại ảnh sang định vị và nhận dạng nhiều đối tượng trong cùng một ảnh, kết hợp đề xuất vùng, phân loại và hồi quy hộp bao. Bộ phát hiện hai giai đoạn tách bước sinh đề xuất (qua RPN) khỏi bước phân loại và tinh chỉnh, ưu tiên độ chính xác nhờ tập trung tính toán vào vùng tiềm năng. Bộ phát hiện một giai đoạn dự đoán trực tiếp trên lưới trong một lượt lan truyền xuôi, ưu tiên tốc độ thời gian thực với mức giảm nhẹ về độ chính xác. IoU đánh giá độ chính xác định vị; một phát hiện thường được tính là đúng khi IoU đạt ngưỡng (phổ biến là 0.5) và đúng lớp. Hộp neo cho phép mạng dự đoán độ lệch tương đối thay vì tọa độ tuyệt đối, giúp huấn luyện ổn định hơn. Kim tự tháp đặc trưng (FPN) hỗ trợ phát hiện đa tỷ lệ bằng cách kết hợp thông tin ngữ nghĩa tầng cao với độ phân giải không gian tầng thấp. NMS loại bỏ các hộp trùng lặp bằng cách giữ hộp có độ tin cậy cao nhất và ức chế các hộp chồng lấn, trong khi hàm mất mát đa tác vụ cân bằng đồng thời giữa phân loại và định vị.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=svn9-xV7wjk&quot;&gt;How YOLO Object Detection Works&lt;/a&gt; — DeepBean, tiếng Anh. Giúp đối chiếu cấu trúc tensor trong đoạn mã cài đặt với đầu ra của một bộ phát hiện thực tế.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 11&lt;/td&gt;
          &lt;td&gt;Detection and Segmentation](https://www.youtube.com/watch?v=nDPWywWRIRo) — Stanford University School of Engineering, tiếng Anh. Giải thích các thành phần mất mát (phân loại, hộp bao, &lt;em&gt;objectness&lt;/em&gt;) cần cộng gộp khi cài đặt.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pDdP0TFzsoQ&quot;&gt;PyTorch Tutorial 14 - Convolutional Neural Network (CNN)&lt;/a&gt; — Patrick Loeber, tiếng Anh. Hướng dẫn cài đặt mạng xương sống tích chập trong PyTorch trước khi gắn đầu phát hiện.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>17-01-01 Lý thuyết Phát hiện Đối tượng</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter17/17_01_01_Object_Detection_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter17/17_01_01_Object_Detection_Theory</id>
   <content type="html">&lt;p&gt;Phát hiện đối tượng không đơn thuần là ghép bài toán phân loại với bài toán hồi quy 4 tọa độ: khi một bức ảnh có thể chứa 0, 3 hoặc 47 vật thể với đủ kích thước từ chú kiến nhỏ xíu đến chiếc xe buýt choán gần hết khung hình, mạng nơ-ron sẽ phải dự đoán bao nhiêu hộp bao? Bài lý thuyết này giải mã trọn bộ công cụ hình học giúp máy tính trả lời câu hỏi đó: &lt;strong&gt;IoU&lt;/strong&gt;, &lt;strong&gt;Anchor Boxes&lt;/strong&gt;, &lt;strong&gt;hồi quy độ lệch log-scale&lt;/strong&gt;, &lt;strong&gt;NMS&lt;/strong&gt; và thước đo chuẩn vàng &lt;strong&gt;mAP&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cơ-sở-toán-học-của-phát-hiện-đối-tượng&quot;&gt;Kiến thức cần nhớ: Cơ sở toán học của Phát hiện Đối tượng&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Intersection over Union (IoU) và các biến thể GIoU/CIoU:&lt;/strong&gt; Thước đo bất biến tỷ lệ giữa hộp dự đoán \(B_p\) và hộp thật \(B_{gt}\), làm nền tảng cho cả gán nhãn huấn luyện lẫn hàm mất mát hộp bao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tham số hóa hộp bao theo Anchor (Bounding Box Regression):&lt;/strong&gt; Dự đoán độ lệch tương đối \((t_x, t_y, t_w, t_h)\) chuẩn hóa theo kích thước hộp neo và lấy logarit cho chiều rộng/cao để bất biến tỷ lệ và giữ kích thước luôn dương.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mất mát đa tác vụ và Focal Loss:&lt;/strong&gt; Cân bằng giữa loss phân loại (xử lý mất cân bằng cực độ nền/vật thể bằng Focal Loss) và Smooth L1 / IoU loss cho tọa độ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Non-Maximum Suppression (NMS) và Mean Average Precision (mAP):&lt;/strong&gt; Hậu xử lý lọc hộp trùng lặp và tính diện tích dưới đường cong Precision–Recall ở các ngưỡng IoU (mAP@0.5, mAP@0.5:0.95).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-iou-của-hai-hộp-bao-và-một-bước-lọc-non-maximum-suppression-nms&quot;&gt;Giải thích: Tính tay IoU của hai hộp bao và một bước lọc Non-Maximum Suppression (NMS)&lt;/h3&gt;

&lt;p&gt;Xét hộp nhãn thật \(B_{gt} = [x_1, y_1, x_2, y_2] = [10, 10, 50, 50]\) và hai hộp dự đoán cho lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ô tô&lt;/code&gt;: hộp A \(= [20, 20, 60, 60]\) (điểm tin cậy \(0{,}92\)) và hộp B \(= [18, 18, 56, 56]\) (điểm tin cậy \(0{,}75\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính IoU giữa hộp A và hộp thật \(B_{gt}\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Diện tích \(B_{gt}\): \((50-10)\times(50-10) = 1{,}600\); diện tích A: \((60-20)\times(60-20) = 1{,}600\).&lt;/li&gt;
      &lt;li&gt;Vùng giao: \([\max(10,20),\max(10,20),\min(50,60),\min(50,60)] = [20, 20, 50, 50]\), diện tích giao \(= 30 \times 30 = 900\).&lt;/li&gt;
      &lt;li&gt;Diện tích hợp: \(1{,}600 + 1{,}600 - 900 = 2{,}300\).&lt;/li&gt;
      &lt;li&gt;\(\text{IoU}(A, B_{gt}) = \frac{900}{2{,}300} \approx 0{,}3913\) (chưa đạt ngưỡng \(0{,}50\) nên bị tính là False Positive ở mAP@0.5!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chạy NMS với ngưỡng \(\tau_{\text{NMS}} = 0{,}5\) giữa A và B:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Chọn hộp có điểm cao nhất trước là A (\(0{,}92\)). Tính vùng giao giữa A và B: \([20, 20, 56, 56]\) có diện tích \(36 \times 36 = 1{,}296\).&lt;/li&gt;
      &lt;li&gt;Diện tích B là \(38 \times 38 = 1{,}444\), hợp \(A \cup B = 1{,}600 + 1{,}444 - 1{,}296 = 1{,}748\).&lt;/li&gt;
      &lt;li&gt;\(\text{IoU}(A, B) = \frac{1{,}296}{1{,}748} \approx 0{,}7414 &amp;gt; 0{,}5\) → &lt;strong&gt;loại bỏ hộp B&lt;/strong&gt; vì trùng lặp với A!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;phát-hiện-đối-tượng-định-vị-và-nhận-dạng&quot;&gt;Phát hiện Đối tượng: Định vị và Nhận dạng&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Detected-with-YOLO--Schreibtisch-mit-Objekten.jpg/800px-Detected-with-YOLO--Schreibtisch-mit-Objekten.jpg&quot; alt=&quot;Object Detection Example&quot; /&gt;
&lt;em&gt;Hình ảnh: Phát hiện đối tượng với YOLO — nhận dạng và định vị đồng thời nhiều vật thể. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Phát hiện đối tượng (&lt;em&gt;object detection&lt;/em&gt;) mở rộng bài toán phân loại ảnh từ câu hỏi “trong ảnh có đối tượng gì?” sang “có những đối tượng nào và chúng nằm ở đâu?”. Sự mở rộng tưởng như nhỏ này thực chất đòi hỏi giải đồng thời nhiều bài toán con liên kết với nhau: đề xuất các vùng có khả năng chứa đối tượng (&lt;em&gt;region proposal&lt;/em&gt;), phân loại nội dung trong từng vùng (&lt;em&gt;recognition&lt;/em&gt;), tinh chỉnh biên giới hạn (&lt;em&gt;localization&lt;/em&gt;), và xử lý nhiều đối tượng thuộc nhiều lớp ở các tỷ lệ kích thước khác nhau (&lt;em&gt;multi-scale, multi-class detection&lt;/em&gt;). Việc phối hợp các thành phần này trong khi vẫn đảm bảo tốc độ thời gian thực khiến phát hiện đối tượng trở thành một bài toán nhiều thách thức trong thị giác máy tính.&lt;/p&gt;

&lt;p&gt;Quá trình phát triển của các phương pháp phát hiện đối tượng phản ánh bước chuyển từ thị giác máy tính cổ điển sang học sâu. Các phương pháp cổ điển dùng đặc trưng thiết kế thủ công (SIFT, HOG) kết hợp cửa sổ trượt (&lt;em&gt;sliding window&lt;/em&gt;) quét qua mọi vị trí và tỷ lệ có thể, rồi phân loại từng cửa sổ bằng bộ phân loại như SVM. Cách này tiêu tốn nhiều tài nguyên tính toán (phải đánh giá hàng triệu cửa sổ trên mỗi ảnh) và bị giới hạn bởi chất lượng đặc trưng thủ công. Học sâu khắc phục hạn chế đó bằng đặc trưng học trực tiếp từ dữ liệu và các kiến trúc huấn luyện đầu–cuối, cải thiện đáng kể cả độ chính xác lẫn tốc độ.&lt;/p&gt;

&lt;p&gt;Phát hiện đối tượng hiện đại gồm hai hướng kiến trúc chính. Bộ phát hiện hai giai đoạn (&lt;em&gt;two-stage detector&lt;/em&gt;) như R-CNN, Fast R-CNN và Faster R-CNN trước tiên đề xuất các vùng có khả năng chứa đối tượng, sau đó mới phân loại và tinh chỉnh hộp bao cho các vùng đó. Việc tách riêng bước đề xuất vùng và bước nhận dạng giúp tập trung năng lực tính toán vào các vùng tiềm năng và đạt độ chính xác cao. Bộ phát hiện một giai đoạn (&lt;em&gt;single-stage detector&lt;/em&gt;) như YOLO và SSD dự đoán trực tiếp hộp bao cùng xác suất lớp tại các vị trí trên lưới đều, bỏ qua giai đoạn đề xuất để đạt tốc độ thời gian thực, đánh đổi bằng độ chính xác thấp hơn một chút đối với các đối tượng nhỏ.&lt;/p&gt;

&lt;p&gt;Để hiểu rõ cơ chế hoạt động của các hệ thống phát hiện đối tượng, cần nắm bốn thành phần kỹ thuật cốt lõi. Mạng đề xuất vùng (&lt;em&gt;Region Proposal Network&lt;/em&gt;, RPN) học cách sinh đề xuất thay cho thuật toán thủ công, giúp toàn bộ quy trình khả vi. Hộp neo (&lt;em&gt;anchor box&lt;/em&gt;) xử lý các đối tượng có kích thước và tỷ lệ khung hình khác nhau thông qua các hộp tham chiếu định sẵn. Ức chế không cực đại (&lt;em&gt;non-maximum suppression&lt;/em&gt;, NMS) loại bỏ các phát hiện trùng lặp khi mô hình sinh ra nhiều hộp chồng lấn cho cùng một đối tượng. Mạng kim tự tháp đặc trưng (&lt;em&gt;Feature Pyramid Network&lt;/em&gt;, FPN) hỗ trợ phát hiện đa tỷ lệ bằng cách xây dựng kim tự tháp đặc trưng giàu thông tin ngữ nghĩa ở mọi độ phân giải. Khi kết hợp lại, các thành phần này cho phép phát hiện và định vị hàng chục đối tượng thuộc nhiều lớp chỉ trong vài mili giây, ứng dụng trong xe tự lái, phân tích ảnh y khoa và thực tế tăng cường.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Phát hiện đối tượng cần mô tả chặt chẽ đầu ra cần dự đoán và thước đo đánh giá. Mỗi đối tượng được biểu diễn bằng bộ \((\text{class}, x, y, w, h)\), gồm nhãn lớp và hộp bao (tọa độ tâm \(x, y\) cùng chiều rộng \(w\) và chiều cao \(h\)). Với ảnh có \(N\) đối tượng, nhãn thực tế (&lt;em&gt;ground truth&lt;/em&gt;) là tập hợp \(\{(\text{class}_i, x_i, y_i, w_i, h_i)\}_{i=1}^N\). Bộ phát hiện phải dự đoán tập hợp này trong điều kiện số lượng \(N\) thay đổi tùy theo từng ảnh.&lt;/p&gt;

&lt;h3 id=&quot;giao-trên-hợp-intersection-over-union-iou&quot;&gt;Giao trên Hợp (Intersection over Union, IoU)&lt;/h3&gt;

&lt;p&gt;Chất lượng định vị được đo bằng chỉ số Giao trên Hợp (IoU) giữa hộp dự đoán và hộp nhãn thực tế:&lt;/p&gt;

\[\text{IoU}(\text{box}_{\text{pred}}, \text{box}_{\text{gt}}) = \frac{\text{Area}(\text{box}_{\text{pred}} \cap \text{box}_{\text{gt}})}{\text{Area}(\text{box}_{\text{pred}} \cup \text{box}_{\text{gt}})}\]

&lt;p&gt;IoU nhận giá trị từ 0 (không chồng lấn) đến 1 (trùng khít hoàn toàn). Thông thường, một phát hiện được xem là đúng nếu \(\text{IoU} \geq 0.5\) và nhãn lớp dự đoán khớp với nhãn thực tế. Ngưỡng này cân bằng giữa yêu cầu định vị chính xác và độ dung sai hợp lý cho vị trí hộp bao.&lt;/p&gt;

&lt;h3 id=&quot;hồi-quy-hộp-bao-bounding-box-regression&quot;&gt;Hồi quy hộp bao (Bounding Box Regression)&lt;/h3&gt;

&lt;p&gt;Thay vì dự đoán trực tiếp tọa độ tuyệt đối, các bộ phát hiện hiện đại dự đoán độ lệch so với hộp neo (hộp tham chiếu định sẵn). Cho hộp neo \((\hat{x}, \hat{y}, \hat{w}, \hat{h})\) và hộp nhãn thực tế \((\bar{x}, \bar{y}, \bar{w}, \bar{h})\), mục tiêu hồi quy được tham số hóa như sau:&lt;/p&gt;

\[t_x = \frac{\bar{x} - \hat{x}}{\hat{w}}, \quad t_y = \frac{\bar{y} - \hat{y}}{\hat{h}}\]

\[t_w = \log\frac{\bar{w}}{\hat{w}}, \quad t_h = \log\frac{\bar{h}}{\hat{h}}\]

&lt;p&gt;Mạng dự đoán bộ giá trị \((t_x, t_y, t_w, t_h)\), sau đó giải mã ngược về tọa độ tuyệt đối:&lt;/p&gt;

\[x = \hat{x} + \hat{w} \cdot t_x, \quad y = \hat{y} + \hat{h} \cdot t_y\]

\[w = \hat{w} \cdot \exp(t_w), \quad h = \hat{h} \cdot \exp(t_h)\]

&lt;p&gt;Cách tham số hóa này dễ học hơn dự đoán tọa độ trực tiếp vì các độ lệch thường có giá trị nhỏ và cùng thang đo, trong khi tọa độ tuyệt đối biến thiên trên toàn ảnh với thang đo rất khác nhau giữa đối tượng nhỏ và lớn.&lt;/p&gt;

&lt;h3 id=&quot;hàm-mất-mát-đa-tác-vụ-multi-task-loss&quot;&gt;Hàm mất mát đa tác vụ (Multi-Task Loss)&lt;/h3&gt;

&lt;p&gt;Bộ phát hiện tối ưu đồng thời hàm mất mát phân loại và hàm mất mát định vị:&lt;/p&gt;

\[\mathcal{L} = \mathcal{L}_{\text{cls}} + \lambda \mathcal{L}_{\text{box}}\]

&lt;p&gt;trong đó \(\mathcal{L}_{\text{cls}}\) là hàm mất mát phân loại (cross-entropy) và \(\mathcal{L}_{\text{box}}\) là hàm mất mát hồi quy hộp bao (smooth L1 hoặc hàm mất mát dựa trên IoU). Hệ số \(\lambda\) cân bằng hai mục tiêu: nếu \(\lambda\) quá lớn, mô hình ưu tiên định vị mà giảm chất lượng phân loại; nếu quá nhỏ, mô hình phân loại tốt nhưng hộp bao kém chính xác.&lt;/p&gt;

&lt;p&gt;Trong Faster R-CNN, hàm mất mát phân loại dùng cross-entropy trên tất cả các lớp đối tượng cộng thêm lớp nền:&lt;/p&gt;

\[\mathcal{L}_{\text{cls}} = -\log p_{\text{class}}\]

&lt;p&gt;trong đó \(\text{class}\) là nhãn lớp thực tế (hoặc lớp nền nếu IoU &amp;lt; 0.5 với mọi hộp nhãn thực tế).&lt;/p&gt;

&lt;p&gt;Hàm mất mát hồi quy hộp bao là smooth L1:&lt;/p&gt;

\[\mathcal{L}_{\text{box}} = \sum_{i \in \{x,y,w,h\}} \text{smooth}_{L1}(t_i - \hat{t}_i)\]

\[\text{smooth}_{L1}(x) = \begin{cases} 0.5x^2 &amp;amp; \text{if } |x| &amp;lt; 1 \\ |x| - 0.5 &amp;amp; \text{otherwise} \end{cases}\]

&lt;p&gt;Smooth L1 ít nhạy với các điểm ngoại lai hơn L2 (chuyển từ bậc hai sang tuyến tính khi sai số lớn) đồng thời khả vi tại mọi điểm (khác với L1 thuần túy).&lt;/p&gt;

&lt;h3 id=&quot;mạng-đề-xuất-vùng-region-proposal-network-rpn&quot;&gt;Mạng đề xuất vùng (Region Proposal Network, RPN)&lt;/h3&gt;

&lt;p&gt;Faster R-CNN đưa ra RPN — một mạng tích chập hoàn toàn dùng để dự đoán các vùng đề xuất chứa đối tượng. Tại mỗi vị trí trên bản đồ đặc trưng, RPN dự đoán:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Điểm &lt;em&gt;objectness&lt;/em&gt;: \(k\) hộp neo × 2 giá trị (có đối tượng hay là nền).&lt;/li&gt;
  &lt;li&gt;Độ tinh chỉnh hộp bao: \(k\) hộp neo × 4 tọa độ.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Với bản đồ đặc trưng kích thước \(H \times W\) và \(k=9\) hộp neo tại mỗi vị trí, đầu ra của RPN gồm:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Điểm &lt;em&gt;objectness&lt;/em&gt;: \(H \times W \times 9 \times 2\) giá trị.&lt;/li&gt;
  &lt;li&gt;Độ lệch hộp bao: \(H \times W \times 9 \times 4\) giá trị.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tổng cộng có \(HW \times 9\) đề xuất. Thuật toán NMS lọc lại còn khoảng 2000 đề xuất có điểm &lt;em&gt;objectness&lt;/em&gt; cao nhất để đưa vào đầu phát hiện.&lt;/p&gt;

&lt;p&gt;Hàm mất mát của RPN kết hợp cả phân loại (&lt;em&gt;objectness&lt;/em&gt;) và hồi quy hộp bao:&lt;/p&gt;

\[\mathcal{L}_{\text{RPN}} = \frac{1}{N_{\text{cls}}}\sum_i \mathcal{L}_{\text{cls}}(p_i, p_i^*) + \frac{\lambda}{N_{\text{box}}}\sum_i p_i^* \mathcal{L}_{\text{box}}(t_i, t_i^*)\]

&lt;p&gt;trong đó \(p_i^* = 1\) nếu hộp neo \(i\) chồng lấn với hộp nhãn thực tế với IoU &amp;gt; 0.7 (mẫu dương), \(p_i^* = 0\) nếu IoU &amp;lt; 0.3 (mẫu âm), và các trường hợp nằm giữa hai ngưỡng này bị bỏ qua để tránh gây nhiễu cho quá trình huấn luyện.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và trực giác&lt;/h2&gt;

&lt;p&gt;Giả sử bạn cần tìm và nhận diện tất cả mọi người trong một bức ảnh đông đúc. Cách làm tự nhiên thường gồm ba bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Quét nhanh&lt;/strong&gt; các vùng có khả năng chứa người (dựa trên hình dáng đầu, thân).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xem xét kỹ&lt;/strong&gt; từng vùng tiềm năng (đây thực sự là người hay là tượng? là ai?).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tinh chỉnh&lt;/strong&gt; biên giới hạn (hộp bao của từng người bắt đầu và kết thúc chính xác ở đâu?).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Quy trình này phản ánh trực tiếp cơ chế của bộ phát hiện hai giai đoạn. RPN thực hiện bước quét nhanh, đề xuất khoảng 2000 vùng có khả năng chứa đối tượng (người, xe, chó, v.v.). Đầu phát hiện kiểm tra kỹ từng đề xuất để phân loại nội dung và tinh chỉnh hộp bao, sau đó NMS loại bỏ các hộp trùng lặp cho cùng một đối tượng.&lt;/p&gt;

&lt;p&gt;Xét ví dụ phát hiện xe trên đường phố. Một khung hình có thể chứa:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;3 chiếc xe ở các khoảng cách khác nhau (tương ứng với kích thước khác nhau).&lt;/li&gt;
  &lt;li&gt;2 người đi bộ.&lt;/li&gt;
  &lt;li&gt;1 biển báo giao thông.&lt;/li&gt;
  &lt;li&gt;Nền phức tạp (nhà cửa, cây cối).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bộ phát hiện một giai đoạn như YOLO chia ảnh thành một lưới (chẳng hạn 13×13). Mỗi ô lưới dự đoán:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nhiều hộp bao (ví dụ 3 hộp với các tỷ lệ khung hình khác nhau: cao, rộng, vuông).&lt;/li&gt;
  &lt;li&gt;Xác suất lớp cho từng hộp.&lt;/li&gt;
  &lt;li&gt;Điểm tin cậy (&lt;em&gt;confidence&lt;/em&gt;) phản ánh khả năng có đối tượng tại ô đó.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tại ô lưới (5, 8) nằm gần một chiếc xe, mô hình có thể dự đoán:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Hộp 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;class=car&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;confidence=0.95&lt;/code&gt;, tọa độ lệch so với tâm ô.&lt;/li&gt;
  &lt;li&gt;Hộp 2: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;class=background&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;confidence=0.05&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;Hộp 3: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;class=background&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;confidence=0.02&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sau khi xử lý toàn bộ 13×13 ô, ta thu được 13×13×3 = 507 dự đoán, phần lớn là nền với điểm tin cậy gần 0. NMS chỉ giữ lại các hộp có độ tin cậy cao và không chồng lấn:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Xe 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;confidence=0.95&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;box=[120, 200, 60, 40]&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Xe 2: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;confidence=0.89&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;box=[300, 180, 80, 50]&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Xe 3: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;confidence=0.76&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;box=[450, 220, 40, 25]&lt;/code&gt; (xe ở xa nên kích thước nhỏ hơn)&lt;/li&gt;
  &lt;li&gt;Người 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;confidence=0.92&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;box=[200, 150, 30, 80]&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Như vậy, bộ phát hiện đã đồng thời nhận dạng lớp và định vị vị trí từng đối tượng bằng hộp bao.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=svn9-xV7wjk&quot;&gt;How YOLO Object Detection Works&lt;/a&gt; — DeepBean, tiếng Anh. Minh họa cách một lượt lan truyền xuôi dự đoán trực tiếp các hộp bao, bám sát thiết kế lý thuyết trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 11&lt;/td&gt;
          &lt;td&gt;Detection and Segmentation](https://www.youtube.com/watch?v=nDPWywWRIRo) — Stanford University School of Engineering, tiếng Anh. Trình bày IoU và cách gán hộp dự đoán với nhãn thực tế — phần toán học chi tiết mà video ngắn chưa đi sâu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Ôn lại các đặc trưng tích chập làm nền tảng cho cả hai video trên.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>17 Ứng dụng Thị giác Máy tính</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter17/17_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter17/17_00_Introduction</id>
   <content type="html">&lt;p&gt;Một chiếc xe tự lái lao đi với vận tốc 60 km/h trên phố đông không thể chỉ biết rằng “trong khung hình này có người đi bộ và đèn giao thông” — nó buộc phải biết &lt;em&gt;chính xác&lt;/em&gt; người đi bộ đang ở tọa độ nào, có bao nhiêu chiếc xe máy đang cắt ngang và ranh giới vỉa hè nằm đến từng điểm ảnh nào. Bước nhảy từ phân loại ảnh (Image Classification) sang &lt;strong&gt;Phát hiện Đối tượng (Object Detection)&lt;/strong&gt; và &lt;strong&gt;Phân đoạn (Segmentation)&lt;/strong&gt; mở ra thế giới thị giác máy tính ứng dụng thực thụ.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-thị-giác-máy-tính-ứng-dụng&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Thị giác Máy tính ứng dụng&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thang đo hình học và đánh giá (IoU, NMS, mAP):&lt;/strong&gt; Đo độ chồng lấn giữa hộp dự đoán với nhãn thật (IoU), loại bỏ các hộp trùng lặp (NMS), và tổng hợp độ chính xác đa lớp đa ngưỡng (mAP).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phát hiện hai giai đoạn vs. một giai đoạn:&lt;/strong&gt; So sánh độ chính xác tinh xảo của họ R-CNN (đề xuất vùng RPN + tinh chỉnh hộp) với tốc độ thời gian thực của họ YOLO/SSD (dự đoán trực tiếp trên lưới).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân đoạn ngữ nghĩa và phân đoạn thực thể (Semantic &amp;amp; Instance Segmentation):&lt;/strong&gt; Đi xa hơn hộp chữ nhật để gán nhãn đến từng điểm ảnh (U-Net, Mask R-CNN).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thế hệ thị giác theo Prompt và Từ vựng mở (2022–2026):&lt;/strong&gt; Chuyển dịch sang DETR thời gian thực, Segment Anything (SAM/SAM 2) và phát hiện theo văn bản tự do (Grounding DINO).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-phân-biệt-4-cấp-độ-bài-toán-thị-giác-trên-cùng-một-bức-ảnh-đường-phố-640-times-480&quot;&gt;Giải thích: Phân biệt 4 cấp độ bài toán thị giác trên cùng một bức ảnh đường phố \(640 \times 480\)&lt;/h3&gt;

&lt;p&gt;Giả sử một bức ảnh đường phố kích thước \(640 \times 480 = 307{,}200\) điểm ảnh chứa 2 chiếc ô tô và 3 người đi bộ:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phân loại ảnh (Classification):&lt;/strong&gt; Đầu ra chỉ là &lt;strong&gt;1 nhãn&lt;/strong&gt; (ví dụ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;đường phố&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phát hiện đối tượng (Object Detection):&lt;/strong&gt; Đầu ra là &lt;strong&gt;5 bộ&lt;/strong&gt; \((x_1, y_1, x_2, y_2, \text{lớp}, \text{điểm tin cậy})\) — tổng cộng \(5 \times 6 = 30\) con số mô tả vị trí và danh tính từng đối tượng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân đoạn ngữ nghĩa (Semantic Segmentation):&lt;/strong&gt; Đầu ra là một ma trận \(640 \times 480\) gán mỗi trong \(307{,}200\) pixel vào lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;xe&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;người&lt;/code&gt; hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nền&lt;/code&gt; (hai chiếc xe đứng sát nhau bị gộp thành một mảng màu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;xe&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân đoạn thực thể (Instance Segmentation):&lt;/strong&gt; Tách riêng mặt nạ nhị phân cho từng đối tượng (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;xe_1&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;xe_2&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;người_1&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;người_2&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;người_3&lt;/code&gt;), kết hợp cả năng lực đếm số lượng lẫn đường viền chính xác từng pixel.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chương này áp dụng học sâu vào các tác vụ thị giác máy tính phổ biến: phân loại ảnh (&lt;em&gt;image classification&lt;/em&gt;), phát hiện đối tượng (&lt;em&gt;object detection&lt;/em&gt; — YOLO, Faster R-CNN), phân đoạn ngữ nghĩa (&lt;em&gt;semantic segmentation&lt;/em&gt; — U-Net, DeepLab), phân đoạn thể hiện (&lt;em&gt;instance segmentation&lt;/em&gt; — Mask R-CNN), ước lượng tư thế (&lt;em&gt;pose estimation&lt;/em&gt;) và sinh ảnh. Nội dung bao gồm kiến trúc mô hình, tập dữ liệu, chỉ số đánh giá và chi tiết cài đặt cho các ứng dụng thực tế.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau các bộ phát hiện cổ điển, xem thêm bài &lt;strong&gt;17-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về SAM/SAM 2, RT-DETR và Grounding DINO từ vựng mở.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Lecture 11&lt;/td&gt;
          &lt;td&gt;Detection and Segmentation](https://www.youtube.com/watch?v=nDPWywWRIRo) — Stanford University School of Engineering, tiếng Anh. Bài giảng CS231n bao quát hai chủ đề chính của chương là phát hiện đối tượng và phân đoạn ảnh.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=svn9-xV7wjk&quot;&gt;How YOLO Object Detection Works&lt;/a&gt; — DeepBean, tiếng Anh. Giải thích cơ chế của YOLO, bộ phát hiện một giai đoạn sẽ được phân tích kỹ hơn trong các bài sau.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, tiếng Anh. Ôn lại mạng tích chập làm xương sống (&lt;em&gt;backbone&lt;/em&gt;) cho các bộ phát hiện đối tượng.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>16-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter16/16_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter16/16_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Nếu năm 2020 SimCLR vẫn còn là câu chuyện nghiên cứu cần batch size 4.096 và phải tinh chỉnh lại cho từng tác vụ, thì giai đoạn 2023–2026 đã chứng kiến bước trưởng thành vượt bậc: &lt;strong&gt;DINOv2&lt;/strong&gt; cho ra đặc trưng thị giác đóng băng dùng thẳng cho ước lượng độ sâu lẫn phân đoạn, &lt;strong&gt;SigLIP&lt;/strong&gt; thay thế Softmax toàn cục bằng hàm sigmoid song song cực gọn, còn &lt;strong&gt;I-JEPA&lt;/strong&gt; của Yann LeCun dự đoán trực tiếp trong không gian biểu diễn thay vì vẽ lại từng điểm ảnh.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-hướng-đột-phá-của-học-tự-giám-sát-hiện-đại-20222026&quot;&gt;Kiến thức cần nhớ: Ba hướng đột phá của Học Tự giám sát hiện đại (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;DINOv2 và xương sống thị giác phổ dụng:&lt;/strong&gt; Kết hợp chưng cất tự thân cấp ảnh + cấp patch (iBOT) cùng quy trình lọc dữ liệu tự động LVD-142M để tạo ra bộ đặc trưng đóng băng xuất sắc cho cả phân loại, phân đoạn lẫn ước lượng độ sâu 3D.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SigLIP / SigLIP 2 (Sigmoid Contrastive Loss):&lt;/strong&gt; Thay bài toán Softmax phụ thuộc toàn batch của CLIP bằng phân loại nhị phân độc lập trên từng cặp ảnh–văn bản, loại bỏ nút cổ chai đồng bộ hóa GPU và mở rộng dễ dàng ở mọi batch size.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;I-JEPA / V-JEPA (Joint-Embedding Predictive Architecture):&lt;/strong&gt; Dự đoán biểu diễn ẩn của vùng bị che thay vì tái tạo pixel thô, loại bỏ chi tiết nhiễu không liên quan ngữ nghĩa (như vị trí từng chiếc lá rung trong gió).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hội tụ với hệ sinh thái đa phương thức:&lt;/strong&gt; Các bộ mã hóa SSL hiện đại (SigLIP, DINOv2) chính là “đôi mắt” mặc định được cắm trực tiếp vào các mô hình ngôn ngữ thị giác (VLM) thế hệ mới.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-tính-toán-của-softmax-clip-vs-sigmoid-siglip-trên-một-batch-b--4-cặp-ảnhvăn-bản&quot;&gt;Giải thích: So sánh tính toán của Softmax CLIP vs. Sigmoid SigLIP trên một batch \(B = 4\) cặp ảnh–văn bản&lt;/h3&gt;

&lt;p&gt;Xét ma trận độ tương đồng \(4 \times 4\) giữa 4 ảnh và 4 chú thích văn bản (đường chéo chính là 4 cặp dương \(y_{ij} = +1\), 12 ô ngoài đường chéo là cặp âm \(y_{ij} = -1\)). Giả sử ô dương \((1,1)\) có điểm \(z_{11} = +3{,}0\) (sau hệ số thang \(t\) và bias \(b\)) và một ô âm \((1,2)\) có \(z_{12} = -2{,}0\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Với CLIP (Softmax Cross-Entropy):&lt;/strong&gt; Muốn tính xác suất cho ô \((1,1)\), GPU phải tập hợp (all-gather) điểm tương đồng với &lt;strong&gt;toàn bộ&lt;/strong&gt; \(B\) văn bản trên mọi GPU để tính mẫu số \(\sum_{j=1}^B e^{z_{1j}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Với SigLIP (Pairwise Sigmoid Loss):&lt;/strong&gt; Mỗi ô \((i, j)\) tính độc lập bằng công thức \(\ell_{ij} = \ln(1 + e^{-y_{ij} z_{ij}})\):
    &lt;ul&gt;
      &lt;li&gt;Ô dương \((1,1)\) (\(y = +1, z = +3{,}0\)): \(\ell_{11} = \ln(1 + e^{-3{,}0}) \approx \ln(1{,}0498) \approx 0{,}0486\).&lt;/li&gt;
      &lt;li&gt;Ô âm \((1,2)\) (\(y = -1, z = -2{,}0\)): \(\ell_{12} = \ln(1 + e^{-(-1)(-2{,}0)}) = \ln(1 + e^{-2{,}0}) \approx \ln(1{,}1353) \approx 0{,}1269\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ưu thế hệ thống:&lt;/strong&gt; Vì không cần mẫu số chuẩn hóa toàn cục, SigLIP cho phép tính chia khối (chunked) giữa các GPU với bộ nhớ cực nhỏ và hoạt động ổn định ngay cả ở batch size nhỏ lẫn cực lớn (hàng chục nghìn cặp).&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-học-tự-giám-sát-sau-simclr--dinov2-siglip-và-jepa&quot;&gt;Tùy chọn: Học tự giám sát sau SimCLR — DINOv2, SigLIP và JEPA&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết học đối chiếu / MLM hay bản phác thảo SimCLR trong chương. Nội dung cập nhật các phương pháp học tự giám sát (SSL) cho &lt;strong&gt;thị giác và đa phương thức&lt;/strong&gt; được dùng rộng rãi từ sau năm 2022.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Các bài trước trong chương đã giới thiệu SimCLR, CLIP và MAE. Trong giai đoạn 2023–2025, các hệ thống thực tế chuyển dần sang &lt;strong&gt;mô hình thầy–trò mạnh hơn&lt;/strong&gt;, &lt;strong&gt;hàm mất mát sigmoid cho cặp ảnh–văn bản&lt;/strong&gt;, và mục tiêu &lt;strong&gt;dự đoán trong không gian biểu diễn ẩn&lt;/strong&gt; (JEPA).&lt;/p&gt;

&lt;h2 id=&quot;1-dinov2-mạng-xương-sống-đóng-băng-dùng-trực-tiếp&quot;&gt;1. DINOv2: Mạng xương sống đóng băng dùng trực tiếp&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.07193&quot;&gt;Oquab et al., 2023&lt;/a&gt; kết hợp cơ chế thầy–trò (&lt;em&gt;student–teacher&lt;/em&gt;) kiểu DINO/iBOT với quy trình chọn lọc dữ liệu quy mô lớn. Đặc trưng từ ViT-g có thể dùng trực tiếp cho truy xuất ảnh, ước lượng độ sâu và phân đoạn mà &lt;strong&gt;không&lt;/strong&gt; cần tinh chỉnh theo từng tác vụ trong nhiều bài toán thử nghiệm. Cách tiếp cận này xem học tự giám sát như phương pháp xây dựng &lt;strong&gt;bộ mã hóa nền tảng&lt;/strong&gt;, thay vì chỉ dừng ở một tác vụ tiền huấn luyện đơn lẻ.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-cụ-thể&quot;&gt;2. Ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;siglip-và-siglip-2&quot;&gt;SigLIP và SigLIP 2&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.15343&quot;&gt;Zhai et al., 2023&lt;/a&gt; thay hàm mất mát softmax của CLIP (vốn đòi hỏi batch mẫu âm lớn) bằng hàm mất mát &lt;strong&gt;sigmoid&lt;/strong&gt; tính trên từng cặp:&lt;/p&gt;

\[\mathcal{L} = -\frac{1}{B}\sum_{i,j}\log\sigma\big(y_{ij}\, t\, x_i^\top y_j\big),\]

&lt;p&gt;trong đó \(y_{ij}=\pm 1\) cho biết cặp \((i, j)\) có khớp nhau hay không. Nhiều mô hình thị giác–ngôn ngữ mở (như PaliGemma và các VLM giai đoạn 2024–2025) sử dụng nhánh mã hóa thị giác SigLIP làm thành phần khởi đầu.&lt;/p&gt;

&lt;h3 id=&quot;i-jepa-và-dự-đoán-trong-không-gian-biểu-diễn&quot;&gt;I-JEPA và dự đoán trong không gian biểu diễn&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2301.08243&quot;&gt;Assran et al., 2023&lt;/a&gt; (I-JEPA) dự đoán &lt;strong&gt;vector nhúng&lt;/strong&gt; (&lt;em&gt;embedding&lt;/em&gt;) của các mảng ảnh (&lt;em&gt;patch&lt;/em&gt;) bị che thay vì tái tạo trực tiếp giá trị pixel như MAE (đã nhắc ở bài tùy chọn Chương 12). Hướng nghiên cứu JEPA của Yann LeCun đặt giả thuyết rằng học tự giám sát nên mô hình hóa cấu trúc và biến đổi trong không gian ẩn thay vì giải mã chi tiết từng pixel RGB.&lt;/p&gt;

&lt;h3 id=&quot;những-nền-tảng-vẫn-giữ-nguyên-giá-trị&quot;&gt;Những nền tảng vẫn giữ nguyên giá trị&lt;/h3&gt;

&lt;p&gt;MLM và cơ chế ghép cặp ảnh–văn bản kiểu CLIP vẫn là nền tảng trong NLP và mô hình đa phương thức, còn SimCLR vẫn là bước dẫn nhập cơ bản để hiểu cơ chế học đối chiếu.&lt;/p&gt;

&lt;h2 id=&quot;3-phần-mềm-phổ-biến&quot;&gt;3. Phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/dinov2&quot;&gt;facebookresearch/dinov2&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Trọng số SigLIP trong OpenCLIP trên Hugging Face Hub.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/jepa&quot;&gt;facebookresearch/jepa&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.07193&quot;&gt;DINOv2 (Oquab et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.15343&quot;&gt;SigLIP (Zhai et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2301.08243&quot;&gt;I-JEPA (Assran et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-bài-này-bổ-sung-gì-cho-ghi-chú-cốt-lõi&quot;&gt;5. Bài này bổ sung gì cho ghi chú cốt lõi&lt;/h2&gt;

&lt;p&gt;Phần suy diễn NT-Xent và công thức MLM của BERT trong các bài cốt lõi vẫn giữ nguyên giá trị. Bài này bổ sung các &lt;strong&gt;mô hình tiền huấn luyện giai đoạn 2023–2025&lt;/strong&gt; (DINOv2, SigLIP, JEPA) thường được tải về sử dụng trực tiếp thay vì huấn luyện SimCLR từ đầu.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=csEgtSh7jV4&quot;&gt;DINOv2 from Meta AI - Finally a Foundational Model in Computer Vision?&lt;/a&gt; — AI Papers Academy, tiếng Anh. Giới thiệu DINOv2, mạng xương sống thị giác đóng băng có thể dùng cho nhiều tác vụ mà không cần tinh chỉnh toàn bộ.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=h3ij3F3cPIk&quot;&gt;DINO: Emerging Properties in Self-Supervised Vision Transformers (Facebook AI Research Explained)&lt;/a&gt; — Yannic Kilcher, tiếng Anh. Trình bày DINO, nền tảng tiền thân mà DINOv2 mở rộng.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Contrastive Learning with SimCLR&lt;/td&gt;
          &lt;td&gt;Deep Learning Animated](https://www.youtube.com/watch?v=UqJauYELn6c) — Deepia, tiếng Anh. Minh họa mục tiêu học đối chiếu, tiền đề của nhiều mô hình thị giác tự giám sát hiện đại.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>16-01 Học Tự giám sát</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter16/16_01_Self_Supervised_Learning/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter16/16_01_Self_Supervised_Learning</id>
   <content type="html">&lt;p&gt;Trong thế giới không nhãn, mối nguy lớn nhất luôn rình rập mọi thuật toán học biểu diễn là &lt;strong&gt;sụp đổ biểu diễn (Representation Collapse)&lt;/strong&gt;: nếu bộ mã hóa ánh xạ &lt;em&gt;mọi&lt;/em&gt; bức ảnh về đúng một vector hằng số \(\mathbf{z} = (0, 0, \dots, 0)\), thì mọi cặp ảnh giống nhau đều có khoảng cách bằng 0! Bài học này giải phẫu cơ chế toán học của &lt;strong&gt;InfoNCE&lt;/strong&gt;, &lt;strong&gt;Masked Prediction&lt;/strong&gt; và &lt;strong&gt;BYOL/DINO&lt;/strong&gt; — ba con đường thông minh giúp học sâu thoát khỏi bẫy sụp đổ để tạo ra những bộ biểu diễn còn mạnh hơn cả học có giám sát.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cơ-chế-toán-học-ngăn-sụp-đổ-biểu-diễn-trong-ssl&quot;&gt;Kiến thức cần nhớ: Cơ chế toán học ngăn sụp đổ biểu diễn trong SSL&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mất mát InfoNCE (NT-Xent) và nhiệt độ \(\tau\):&lt;/strong&gt; Xây dựng bài toán phân loại \((2N-1)\) lớp bằng độ tương đồng cosin chia nhiệt độ \(\tau\), tạo đồng thời lực hút (cặp dương) và lực đẩy (cặp âm) chống sụp đổ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Liên hệ với thông tin tương hỗ (Mutual Information):&lt;/strong&gt; Chứng minh cực tiểu hóa InfoNCE tương đương cực đại hóa cận dưới của thông tin tương hỗ \(I(\mathbf{v}_1; \mathbf{v}_2)\) giữa hai góc nhìn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dự đoán phần bị che (BERT / MAE):&lt;/strong&gt; Khai thác sự dư thừa ngữ cảnh trong chuỗi văn bản hoặc mảng ảnh; phần mất mát chỉ tính trên các vị trí bị che giúp mô hình học cấu trúc toàn cục.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phá đối xứng không cần cặp âm (BYOL / SimSiam / DINO):&lt;/strong&gt; Dùng mạng đích cập nhật trượt (EMA), đầu dự đoán (predictor), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stop-gradient&lt;/code&gt; và căn giữa (centering) để học biểu diễn giàu thông tin mà không cần batch size khổng lồ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-hàm-mất-mát-infonce-nt-xent-cho-một-cặp-dương-và-hai-mẫu-âm&quot;&gt;Giải thích: Tính tay hàm mất mát InfoNCE (NT-Xent) cho một cặp dương và hai mẫu âm&lt;/h3&gt;

&lt;p&gt;Xét một vector truy vấn \(\mathbf{z}_i\) (đã chuẩn hóa đơn vị \(\|\mathbf{z}\|_2 = 1\)) với cặp dương \(\mathbf{z}_j\) và hai mẫu âm \(\mathbf{z}_{k_1}, \mathbf{z}_{k_2}\). Giả sử độ tương đồng cosin lần lượt là:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(s(i, j) = 0{,}80\) (cặp dương)&lt;/li&gt;
  &lt;li&gt;\(s(i, k_1) = 0{,}20\), \(s(i, k_2) = -0{,}20\) (hai mẫu âm)
Chọn tham số nhiệt độ \(\tau = 0{,}2\).&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chia nhiệt độ \(\tau\) để tạo logit:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Cặp dương: \(0{,}80 / 0{,}2 = 4{,}0\).&lt;/li&gt;
      &lt;li&gt;Hai mẫu âm: \(0{,}20 / 0{,}2 = 1{,}0\) và \(-0{,}20 / 0{,}2 = -1{,}0\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính hàm mũ và xác suất Softmax của cặp dương:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(e^{4{,}0} \approx 54{,}60\), \(e^{1{,}0} \approx 2{,}72\), \(e^{-1{,}0} \approx 0{,}37\).&lt;/li&gt;
      &lt;li&gt;Tổng mẫu số: \(54{,}60 + 2{,}72 + 0{,}37 = 57{,}69\).&lt;/li&gt;
      &lt;li&gt;Xác suất nhận đúng cặp dương: \(p = \frac{54{,}60}{57{,}69} \approx 0{,}9464\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính InfoNCE loss:&lt;/strong&gt; \(\mathcal{L}_i = -\ln(0{,}9464) \approx 0{,}055\).
&lt;em&gt;Thử nghiệm tư duy:&lt;/em&gt; Nếu tăng \(\tau = 1{,}0\), các logit co lại thành \(0{,}8; 0{,}2; -0{,}2\) và \(p\) tụt xuống \(0{,}526\) (\(\mathcal{L}_i = 0{,}642\)). Nhiệt độ \(\tau\) nhỏ giúp khuếch đại gradient đặc biệt mạnh lên những &lt;strong&gt;mẫu âm khó (hard negatives)&lt;/strong&gt; có độ tương đồng gần cặp dương!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;học-tự-giám-sát-học-từ-chính-dữ-liệu&quot;&gt;Học Tự giám sát: Học từ Chính Dữ liệu&lt;/h1&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Học tự giám sát (&lt;em&gt;self-supervised learning&lt;/em&gt;) là một hướng tiếp cận khác trong việc khai thác dữ liệu chưa gán nhãn: tín hiệu giám sát được tạo tự động từ chính dữ liệu thay vì dựa vào nhãn thủ công tốn kém do con người thực hiện. Ý tưởng cốt lõi là bản thân dữ liệu đã chứa cấu trúc và mối quan hệ nội tại có thể dùng làm tín hiệu học: ảnh có cấu trúc không gian cho phép dự đoán một phần từ các phần còn lại; văn bản có cấu trúc tuần tự cho phép dự đoán từ bị che dựa trên ngữ cảnh; video có tính liên tục theo thời gian giúp dự đoán thứ tự các khung hình. Bằng cách xây dựng các tác vụ dự đoán khai thác những cấu trúc này, ta có thể huấn luyện mạng nơ-ron trên các tập dữ liệu chưa gán nhãn quy mô lớn và thu được biểu diễn chuyển giao hiệu quả sang các tác vụ có giám sát ở giai đoạn sau (&lt;em&gt;downstream tasks&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Sự khác biệt giữa học tự giám sát và học không giám sát (&lt;em&gt;unsupervised learning&lt;/em&gt;) tuy tinh tế nhưng quan trọng. Học không giám sát truyền thống (như phân cụm hay PCA) tìm kiếm cấu trúc trong dữ liệu mà không dùng cấu trúc đó cho bài toán dự đoán. Học tự giám sát xây dựng các tác vụ dự đoán có giám sát với nhãn được sinh tự động từ cấu trúc dữ liệu, biến dữ liệu chưa gán nhãn thành bài toán học có giám sát thông qua việc thiết kế tác vụ phù hợp. Mô hình ngôn ngữ che dấu (&lt;em&gt;masked language modeling&lt;/em&gt;, MLM) trong BERT — dự đoán từ bị che dựa trên ngữ cảnh — thực chất là học có giám sát, trong đó nhãn (các từ gốc) đến từ chính văn bản chứ không phải từ người gán nhãn.&lt;/p&gt;

&lt;p&gt;Học tự giám sát hiện đại đạt hiệu quả cao, đặc biệt trong xử lý ngôn ngữ tự nhiên (NLP), nơi tiền huấn luyện trên kho văn bản lớn với các mục tiêu tự giám sát (mô hình ngôn ngữ che dấu, dự đoán câu tiếp theo) rồi tinh chỉnh trên tác vụ có giám sát đã trở thành quy trình phổ biến. BERT, GPT và các mô hình tương tự học được biểu diễn ngôn ngữ phong phú từ văn bản chưa gán nhãn, sau đó chuyển giao sang nhiều tác vụ khác nhau. Trong thị giác máy tính, các phương pháp học đối chiếu như SimCLR và MoCo học biểu diễn ảnh bằng cách phân biệt các phiên bản tăng cường (&lt;em&gt;augmentation&lt;/em&gt;) của cùng một ảnh với các ảnh khác, đạt chất lượng biểu diễn cạnh tranh với tiền huấn luyện có giám sát.&lt;/p&gt;

&lt;p&gt;Để nắm vững học tự giám sát, cần hiểu rõ các tác vụ tiền huấn luyện (&lt;em&gt;pretext tasks&lt;/em&gt;) — tức các mục tiêu giám sát tự động dùng khi tiền huấn luyện — và loại biểu diễn mà chúng tạo ra. Một tác vụ tiền huấn luyện tốt cần đáp ứng ba tiêu chí: (1) giải được chỉ từ dữ liệu mà không cần nhãn; (2) đòi hỏi mô hình hiểu cấu trúc ngữ nghĩa để giải tốt; và (3) tạo ra biểu diễn hữu ích cho các tác vụ hạ nguồn. Khó khăn chính nằm ở việc thiết kế tác vụ sao cho mô hình buộc phải học các đặc trưng tổng quát, thay vì dựa vào những “lối tắt” nông trong dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;h3 id=&quot;học-đối-chiếu-contrastive-learning&quot;&gt;Học đối chiếu (Contrastive Learning)&lt;/h3&gt;

&lt;p&gt;Các phương pháp đối chiếu học bằng cách phân biệt các cặp tương tự (mẫu dương) với các cặp không tương tự (mẫu âm). Cho mẫu neo (&lt;em&gt;anchor&lt;/em&gt;) \(\mathbf{x}\), mẫu dương \(\mathbf{x}^+\) (phiên bản tăng cường của cùng một ảnh), và tập mẫu âm \(\{\mathbf{x}_i^-\}\) (các ảnh khác):&lt;/p&gt;

\[\mathcal{L}_{\text{contrastive}} = -\log \frac{\exp(\text{sim}(f(\mathbf{x}), f(\mathbf{x}^+))/\tau)}{\exp(\text{sim}(f(\mathbf{x}), f(\mathbf{x}^+))/\tau) + \sum_i \exp(\text{sim}(f(\mathbf{x}), f(\mathbf{x}_i^-))/\tau)}\]

&lt;p&gt;trong đó \(f\) là bộ mã hóa (&lt;em&gt;encoder&lt;/em&gt;), \(\text{sim}\) là độ tương tự (thường là độ tương tự cosine), và \(\tau\) là tham số nhiệt độ (&lt;em&gt;temperature&lt;/em&gt;). Hàm mất mát NT-Xent (&lt;em&gt;normalized temperature-scaled cross-entropy&lt;/em&gt;) thúc đẩy biểu diễn của các phiên bản tăng cường từ cùng một ảnh nằm gần nhau, đồng thời đẩy biểu diễn của các ảnh khác ra xa nhau.&lt;/p&gt;

&lt;h3 id=&quot;dự-đoán-phần-bị-che-masked-prediction&quot;&gt;Dự đoán phần bị che (Masked Prediction)&lt;/h3&gt;

&lt;p&gt;BERT che ngẫu nhiên 15% số token và dự đoán lại chúng từ ngữ cảnh xung quanh:&lt;/p&gt;

\[\mathcal{L}_{\text{MLM}} = -\mathbb{E}_{\mathbf{x}}\left[\sum_{i \in \mathcal{M}} \log p(x_i | \mathbf{x}_{\backslash \mathcal{M}})\right]\]

&lt;p&gt;trong đó \(\mathcal{M}\) là tập các vị trí bị che. Mô hình phải khai thác ngữ cảnh hai chiều để dự đoán các token bị che, qua đó học được cấu trúc và ngữ nghĩa của ngôn ngữ.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và trực giác&lt;/h2&gt;

&lt;p&gt;Xét bài toán học biểu diễn hình ảnh từ tập ảnh chưa gán nhãn. Từ một bức ảnh con mèo, ta tạo hai phiên bản tăng cường: một phiên bản cắt ngẫu nhiên kết hợp biến đổi màu sắc, phiên bản kia cắt ở vùng khác và xoay nhẹ. Đây là một cặp dương — hai góc nhìn khác nhau của cùng một đối tượng, nên cần có biểu diễn gần nhau.&lt;/p&gt;

&lt;p&gt;Các ảnh chó, xe cộ và cây cối đóng vai trò mẫu âm. Học đối chiếu kéo biểu diễn của hai phiên bản ảnh mèo lại gần nhau trong không gian đặc trưng, đồng thời đẩy chúng ra xa biểu diễn của chó, xe và cây. Sau khi huấn luyện trên hàng triệu ảnh, các biểu diễn sẽ gom cụm theo nội dung ngữ nghĩa: các ảnh mèo nằm gần nhau, các ảnh chó nằm gần nhau; ngoài ra, mèo và chó nằm gần nhau hơn (cùng là động vật) so với xe cộ.&lt;/p&gt;

&lt;p&gt;Những biểu diễn này có thể chuyển giao trực tiếp sang bài toán phân loại: dù chưa từng sử dụng nhãn trong giai đoạn tiền huấn luyện, bộ mã hóa đã học được cách trích xuất đặc trưng giúp phân biệt đối tượng, hỗ trợ hiệu quả cho giai đoạn phân loại có giám sát khi số lượng nhãn bị hạn chế.&lt;/p&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimCLR&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Simplified SimCLR for contrastive learning&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;base_encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;projection_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Encoder (e.g., ResNet)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;base_encoder&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Projection head
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Maps encoder output to space where contrastive loss is computed
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;projection&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;projection_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;projection&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normalize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# L2 normalize
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;nt_xent_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temperature&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    NT-Xent loss for contrastive learning
    
    z1, z2: (batch, dim) representations of augmented pairs
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Concatenate augmentations
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2*batch, dim)
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Compute similarity matrix
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temperature&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2*batch, 2*batch)
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Positive pairs: (i, i+batch) and (i+batch, i)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;pos_sim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Mask out self-similarity
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# NT-Xent loss
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos_sim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Self-supervised learning enables learning from unlabeled data!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Học tự giám sát gắn chặt với học chuyển giao (&lt;em&gt;transfer learning&lt;/em&gt;) như một chiến lược tiền huấn luyện. Thay vì tiền huấn luyện có giám sát trên ImageNet, ta có thể tiền huấn luyện tự giám sát trên dữ liệu ảnh chưa gán nhãn, và trong nhiều trường hợp thu được biểu diễn chuyển giao ngang bằng hoặc tốt hơn.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1911.05722&quot;&gt;“Momentum Contrast for Unsupervised Visual Representation Learning” (2020)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Kaiming He, Haoqi Fan, Yuxin Wu, Saining Xie, Ross Girshick&lt;br /&gt;
MoCo duy trì một hàng đợi lớn các mẫu âm thông qua bộ mã hóa cập nhật theo động lượng (&lt;em&gt;momentum encoder&lt;/em&gt;), giúp học đối chiếu ổn định và đạt chất lượng biểu diễn cạnh tranh với tiền huấn luyện có giám sát.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2002.05709&quot;&gt;“A Simple Framework for Contrastive Learning of Visual Representations” (2020)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ting Chen, Simon Kornblith, Mohammad Norouzi, Geoffrey Hinton&lt;br /&gt;
SimCLR cho thấy khung học đối chiếu đơn giản kết hợp phép tăng cường dữ liệu mạnh và kích thước batch lớn có thể tạo ra biểu diễn chất lượng cao, ngang bằng hoặc vượt nhiều phương pháp tiền huấn luyện có giám sát.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;“BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Mục tiêu mô hình ngôn ngữ che dấu của BERT là một dạng học tự giám sát tiêu biểu, tạo tín hiệu giám sát trực tiếp từ văn bản gốc.&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h2&gt;

&lt;p&gt;Học tự giám sát tạo tín hiệu giám sát tự động từ cấu trúc nội tại của dữ liệu, cho phép huấn luyện trên các tập dữ liệu chưa gán nhãn quy mô lớn thông qua các tác vụ tiền huấn luyện như dự đoán phần bị che hoặc học đối chiếu. Các phương pháp đối chiếu phân biệt các phiên bản tăng cường của cùng một mẫu với các mẫu khác, giúp biểu diễn vừa bất biến trước phép tăng cường vừa giữ được thông tin ngữ nghĩa. Các tác vụ dự đoán phần bị che như MLM của BERT yêu cầu khôi phục phần thiếu từ ngữ cảnh, buộc mô hình nắm bắt cấu trúc dữ liệu. Tiền huấn luyện tự giám sát thường đạt hiệu quả ngang bằng hoặc tốt hơn tiền huấn luyện có giám sát trong học chuyển giao, vì biểu diễn không bị ràng buộc vào một tập nhãn cố định.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Contrastive Learning with SimCLR&lt;/td&gt;
          &lt;td&gt;Deep Learning Animated](https://www.youtube.com/watch?v=UqJauYELn6c) — Deepia, tiếng Anh. Giải thích trực quan hàm mất mát NT-Xent trên hai phiên bản tăng cường của cùng một ảnh.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=h3ij3F3cPIk&quot;&gt;DINO: Emerging Properties in Self-Supervised Vision Transformers (Facebook AI Research Explained)&lt;/a&gt; — Yannic Kilcher, tiếng Anh. Phân tích cơ chế tự chưng cất và khả năng phân đoạn tự phát sinh của DINO.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is cross-entropy?&lt;/td&gt;
          &lt;td&gt;Compression is Intelligence Part 2](https://www.youtube.com/watch?v=GlYgs6v2YfU) — 3Blue1Brown, tiếng Anh. Giải thích hàm cross-entropy, nền tảng cho tác vụ dự đoán phần bị che kiểu BERT song song với NT-Xent.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>16 Học Tự giám sát</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter16/16_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter16/16_00_Introduction</id>
   <content type="html">&lt;p&gt;Hãy nghĩ về cách một đứa trẻ hai tuổi hiểu thế giới: không có ai giơ từng chiếc cốc, con mèo hay cái cây lên kèm tấm thẻ ghi nhãn ImageNet để dạy bé hàng triệu lần; bé tự quan sát vật rơi, đoán xem món đồ bị che khuất trông như thế nào, và nhận ra cùng một chiếc cốc dù xoay góc nào vẫn là nó. &lt;strong&gt;Học Tự giám sát (Self-Supervised Learning — SSL)&lt;/strong&gt; mang chính năng lực đó vào học sâu: biến những phần ẩn giấu hoặc góc nhìn khác nhau của chính dữ liệu chưa gắn nhãn thành nguồn tín hiệu giám sát vô tận.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-học-tự-giám-sát&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Học Tự giám sát&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thiết kế tác vụ tiền đề (Pretext Tasks):&lt;/strong&gt; Tự tạo cặp đầu vào–nhãn từ dữ liệu thô (dự đoán từ bị che, ghép mảnh ảnh, kéo gần hai biến thể tăng cường của cùng một ảnh) mà không tốn chi phí gắn nhãn thủ công.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học đối chiếu (Contrastive Learning — SimCLR, MoCo, InfoNCE):&lt;/strong&gt; Kéo các góc nhìn khác nhau của cùng một mẫu (cặp dương) lại gần nhau và đẩy các mẫu khác (cặp âm) ra xa trên siêu cầu đơn vị.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dự đoán phần bị che và Chưng cất tự thân (MAE, BERT, DINO):&lt;/strong&gt; Học biểu diễn mà không cần cặp âm bằng cách khôi phục phần dữ liệu bị ẩn hoặc khớp đầu ra giữa mạng học sinh và mạng thầy EMA.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá chất lượng biểu diễn:&lt;/strong&gt; Dùng &lt;em&gt;Linear Probing&lt;/em&gt; (đóng băng bộ mã hóa), &lt;em&gt;k-NN&lt;/em&gt; và khả năng chuyển giao sang phát hiện/phân đoạn để đo sức mạnh thực sự của đặc trưng tự học.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tại-sao-tăng-cường-dữ-liệu-data-augmentation-quyết-định-sự-quan-trọng-của-học-đối-chiếu&quot;&gt;Giải thích: Tại sao tăng cường dữ liệu (Data Augmentation) quyết định sự quan trọng của học đối chiếu?&lt;/h3&gt;

&lt;p&gt;Giả sử bạn muốn dạy mạng hiểu khái niệm “con mèo” bằng hai góc nhìn (views) tạo ra từ cùng một bức ảnh mèo \(\mathbf{x}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nếu chỉ dịch ảnh đi 1 pixel:&lt;/strong&gt; Hai ảnh giống hệt nhau về biểu đồ màu sắc (color histogram). Mạng sẽ học “đường tắt” (shortcut): chỉ cần so màu nền là nhận ra cùng một ảnh, đạt loss đối chiếu \(\approx 0\) nhưng hoàn toàn không hiểu hình dáng con mèo!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nếu kết hợp Cắt ngẫu nhiên (Random Resized Crop) + Đảo màu mạnh (Color Jitter) + Làm mờ:&lt;/strong&gt; Ảnh 1 có thể là khuôn mặt mèo ngả tông xanh, ảnh 2 là thân mèo ngả tông ấm. Mọi đường tắt màu sắc bị triệt tiêu, buộc bộ mã hóa chỉ còn một cách duy nhất để kéo hai vector lại gần nhau: &lt;strong&gt;học đúng ngữ nghĩa hình học của con mèo&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy tắc định lượng trong SimCLR:&lt;/strong&gt; Khi bỏ Color Jitter trên ImageNet, độ chính xác Linear Probe của SimCLR sụt mạnh hơn \(20\) điểm phần trăm — minh chứng kinh điển rằng tập phép biến đổi tăng cường chính là cách ta định nghĩa &lt;em&gt;bất biến ngữ nghĩa&lt;/em&gt; cho mô hình.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Học tự giám sát (&lt;em&gt;self-supervised learning&lt;/em&gt;) huấn luyện mô hình bằng các nhãn được tạo tự động từ chính dữ liệu, không cần gán nhãn thủ công. Cách tiếp cận này đã thay đổi cách tiền huấn luyện trong xử lý ngôn ngữ tự nhiên (mô hình ngôn ngữ che dấu) và thị giác máy tính (học đối chiếu). Chương này trình bày học đối chiếu (&lt;em&gt;contrastive learning&lt;/em&gt;), SimCLR, CLIP, MAE và các hướng tiếp cận tự giám sát hiện đại.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau SimCLR, CLIP và MAE, xem thêm bài &lt;strong&gt;16-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về DINOv2, SigLIP và học tự giám sát dự đoán theo hướng JEPA.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước&lt;/strong&gt; [Contrastive Learning with SimCLR&lt;/td&gt;
          &lt;td&gt;Deep Learning Animated](https://www.youtube.com/watch?v=UqJauYELn6c) — Deepia, tiếng Anh. Trình bày cách học đối chiếu tạo tác vụ tiền huấn luyện từ phép tăng cường dữ liệu, bám sát ý chính của chương.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=h3ij3F3cPIk&quot;&gt;DINO: Emerging Properties in Self-Supervised Vision Transformers (Facebook AI Research Explained)&lt;/a&gt; — Yannic Kilcher, tiếng Anh. Giới thiệu cơ chế tự chưng cất của DINO, nền tảng trực tiếp cho phần cập nhật về DINOv2.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Minh họa tác vụ dự đoán token tiếp theo trong ngôn ngữ, đặt cạnh các tác vụ tự giám sát trong thị giác máy tính.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Khi mô hình nền lớn lên tới 7 tỷ, 70 tỷ hay hàng trăm tỷ tham số, việc “mở khóa toàn bộ mạng để tinh chỉnh” theo kiểu cổ điển trở nên xa xỉ tới mức chỉ vài phòng thí nghiệm lớn mới đủ GPU. Bước ngoặt mang tên &lt;strong&gt;PEFT (Parameter-Efficient Fine-Tuning)&lt;/strong&gt; — với hai ngôi sao &lt;strong&gt;LoRA&lt;/strong&gt; và &lt;strong&gt;QLoRA&lt;/strong&gt; — đã dân chủ hóa hoàn toàn học chuyển giao, giúp bạn tinh chỉnh một mô hình khổng lồ ngay trên một chiếc GPU tiêu dùng mà chất lượng vẫn tiệm cận tinh chỉnh toàn phần.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-học-chuyển-giao-hiện-đại-peft-20222026&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Học Chuyển giao hiện đại (PEFT 2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Giả thuyết hạng thấp nội tại (Intrinsic Low-Rank) của LoRA:&lt;/strong&gt; Thay vì cập nhật ma trận đầy đủ \(\Delta W \in \mathbb{R}^{d \times k}\), phân tích \(\Delta W = \frac{\alpha}{r} B A\) với \(B \in \mathbb{R}^{d \times r}, A \in \mathbb{R}^{r \times k}\) (\(r \ll \min(d, k)\)) và khởi tạo \(B = 0\) để lúc đầu không làm xáo trộn mô hình gốc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;QLoRA (Quantized LoRA):&lt;/strong&gt; Đóng băng xương sống ở định dạng 4-bit NormalFloat (NF4) kết hợp lượng tử hóa kép (double quantization) và chỉ giữ trạng thái bộ tối ưu Adam cho các ma trận LoRA nhỏ bé ở BF16.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Triển khai không tăng độ trễ (Weight Merging):&lt;/strong&gt; Sau khi huấn luyện xong, cộng gộp trực tiếp \(W_{\text{mới}} = W_0 + \frac{\alpha}{r} B A\) để suy luận nhanh y hệt mô hình gốc, hoặc hoán đổi nóng nhiều adapter LoRA theo từng người dùng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mở rộng sang Thị giác &amp;amp; Đa phương thức:&lt;/strong&gt; Áp dụng LoRA cho lớp chiếu Attention của CLIP, Stable Diffusion/Flux (học phong cách/nhân vật chỉ từ vài chục ảnh) và mô hình ngôn ngữ thị giác (VLM).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-số-tham-số-và-độ-giảm-vram-của-lora--qlora-trên-một-ma-trận-4096-times-4096&quot;&gt;Giải thích: Tính tay số tham số và độ giảm VRAM của LoRA &amp;amp; QLoRA trên một ma trận \(4096 \times 4096\)&lt;/h3&gt;

&lt;p&gt;Xét một ma trận trọng số chiếu tuyến tính \(W_0 \in \mathbb{R}^{4096 \times 4096}\) trong Transformer (\(16{,}777{,}216\) tham số).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;So sánh số tham số huấn luyện khi gắn LoRA hạng \(r = 16\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Ma trận \(A \in \mathbb{R}^{16 \times 4096}\): \(65{,}536\) tham số; ma trận \(B \in \mathbb{R}^{4096 \times 16}\): \(65{,}536\) tham số.&lt;/li&gt;
      &lt;li&gt;Tổng tham số LoRA: \(131{,}072\) tham số — chỉ bằng \(\frac{131{,}072}{16{,}777{,}216} = \frac{1}{128} \approx 0{,}78\%\) so với tinh chỉnh đầy đủ!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh bộ nhớ lưu trọng số + trạng thái Adam (mô hình 7 tỷ tham số):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Full Fine-Tuning (FP16 trọng số + FP32 bản sao + Adam \(m, v\)):&lt;/strong&gt; \(7\text{B} \times (2 + 4 + 4 + 4)\text{ byte} \approx 98\text{ GB VRAM}\) (chưa kể kích hoạt).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;QLoRA (4-bit NF4 cho xương sống + Adam chỉ cho \(0{,}8\%\) tham số LoRA):&lt;/strong&gt; Xương sống tốn \(7\text{B} \times 0{,}5\text{ byte} = 3{,}5\text{ GB}\), toàn bộ trọng số &amp;amp; trạng thái Adam của LoRA tốn chưa tới \(0{,}8\text{ GB}\) — tổng cộng dưới \(5\text{ GB}\) cho phần trọng số/optimizer, vừa vặn trên một GPU 16–24 GB!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-học-chuyển-giao-theo-hướng-peft--lora-qlora-và-adapter&quot;&gt;Tùy chọn: Học chuyển giao theo hướng PEFT — LoRA, QLoRA và Adapter&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết so sánh trích xuất đặc trưng với tinh chỉnh toàn phần. Các bài chính xuất phát từ ResNet và BERT; bài này trình bày cách tiếp cận mặc định giai đoạn 2022–2026 cho các mô hình &lt;strong&gt;hàng tỷ tham số&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Tinh chỉnh toàn phần cập nhật mọi tham số \(\theta\). Tinh chỉnh tiết kiệm tham số (PEFT) đóng băng \(\theta\) và chỉ học một phần bổ sung \(\Delta\) có kích thước nhỏ:&lt;/p&gt;

\[W&apos; = W + \frac{\alpha}{r} BA, \quad B\in\mathbb{R}^{d\times r},\; A\in\mathbb{R}^{r\times k},\; r\ll \min(d,k).\]

&lt;p&gt;Đây chính là công thức của &lt;a href=&quot;https://arxiv.org/abs/2106.09685&quot;&gt;LoRA (Hu et al., 2021/2022)&lt;/a&gt;. Về bản chất vẫn là &lt;em&gt;học chuyển giao&lt;/em&gt;: đặc trưng tiền huấn luyện được thích nghi cho tác vụ đích, nhưng bị ràng buộc trong một không gian con hạng thấp.&lt;/p&gt;

&lt;h2 id=&quot;1-qlora-và-chuyển-giao-trên-mô-hình-lượng-tử-hóa&quot;&gt;1. QLoRA và chuyển giao trên mô hình lượng tử hóa&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.14314&quot;&gt;Dettmers et al., 2023&lt;/a&gt; giữ nguyên bộ trọng số nền ở định dạng lượng tử hóa 4-bit (NF4) và chỉ huấn luyện các ma trận LoRA ở độ chính xác 16-bit, giúp tinh chỉnh mô hình 65B trên một GPU 48 GB. Sự kết hợp giữa &lt;a href=&quot;https://github.com/TimDettmers/bitsandbytes&quot;&gt;bitsandbytes&lt;/a&gt; và &lt;a href=&quot;https://github.com/huggingface/peft&quot;&gt;Hugging Face PEFT&lt;/a&gt; đã biến QLoRA thành lựa chọn phổ biến trong khoa học dữ liệu ứng dụng.&lt;/p&gt;

&lt;h2 id=&quot;2-một-số-ứng-dụng-tiêu-biểu&quot;&gt;2. Một số ứng dụng tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;adapter-theo-miền-và-theo-chỉ-dẫn&quot;&gt;Adapter theo miền và theo chỉ dẫn&lt;/h3&gt;

&lt;p&gt;Thay vì lưu một bản sao mô hình hoàn chỉnh cho từng khách hàng hay lĩnh vực, hệ thống chỉ cần triển khai &lt;strong&gt;một mô hình nền kết hợp nhiều adapter LoRA&lt;/strong&gt; (pháp lý, y tế, SQL). Các nền tảng phục vụ suy luận như vLLM hay SGLang hỗ trợ hoán đổi adapter linh hoạt theo từng yêu cầu.&lt;/p&gt;

&lt;h3 id=&quot;peft-trong-thị-giác-và-đa-phương-thức&quot;&gt;PEFT trong thị giác và đa phương thức&lt;/h3&gt;

&lt;p&gt;Áp dụng LoRA lên các tầng attention của U-Net hoặc DiT (như DreamBooth-LoRA, SDXL LoRA) cho phép học thêm một phong cách hoặc đối tượng mới chỉ từ khoảng 10 ảnh — sử dụng cùng công thức hạng thấp như LoRA ngôn ngữ nhưng đặt trên các tensor thị giác.&lt;/p&gt;

&lt;h3 id=&quot;khi-nào-không-nên-dùng-lora&quot;&gt;Khi nào &lt;em&gt;không&lt;/em&gt; nên dùng LoRA&lt;/h3&gt;

&lt;p&gt;Với mạng CNN cỡ nhỏ, mô hình dữ liệu bảng huấn luyện từ đầu hoặc trường hợp miền đích lệch mạnh nhưng có nhiều dữ liệu gán nhãn, tinh chỉnh toàn phần hoặc thay mới nhiều tầng vẫn phù hợp hơn — tương đồng với nguyên tắc chọn giữa trích xuất đặc trưng và tinh chỉnh trong bài lý thuyết.&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-mã-nguồn-phổ-biến&quot;&gt;3. Thư viện và mã nguồn phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/peft&quot;&gt;huggingface/peft&lt;/a&gt; — hỗ trợ LoRA, AdaLoRA, IA3 và prefix-tuning.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/TimDettmers/bitsandbytes&quot;&gt;bitsandbytes&lt;/a&gt; kết hợp &lt;a href=&quot;https://github.com/artidoro/qlora&quot;&gt;QLoRA&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/unslothai/unsloth&quot;&gt;unsloth&lt;/a&gt; — thư viện tăng tốc huấn luyện LoRA phổ biến trong giai đoạn 2024–2026.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-tài-liệu-tham-khảo-20222026&quot;&gt;4. Tài liệu tham khảo (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2106.09685&quot;&gt;LoRA (Hu et al., 2021)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.14314&quot;&gt;QLoRA (Dettmers et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2104.08691&quot;&gt;Prompt Tuning (Lester et al., 2021)&lt;/a&gt; — một hướng tiếp cận khác trong nhóm PEFT.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-phần-bổ-sung-so-với-nội-dung-cốt-lõi&quot;&gt;5. Phần bổ sung so với nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên hoàn thành phần thực hành tinh chỉnh ResNet/BERT trước. Bài này bổ sung cách tiếp cận chuyển giao &lt;strong&gt;hạng thấp và lượng tử hóa&lt;/strong&gt;, thay thế cho cách “mở băng vài tầng cuối” truyền thống khi làm việc với LLM.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [QLoRA: Efficient Finetuning of Quantized LLMs&lt;/td&gt;
          &lt;td&gt;Tim Dettmers](https://www.youtube.com/watch?v=fQirE9N5q_Y) — AMLD Intelligence Summit, tiếng Anh. Bài thuyết trình của chính tác giả Tim Dettmers về QLoRA, phương pháp tinh chỉnh hạng thấp trên mô hình lượng tử hóa được trình bày trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, tiếng Anh. Giải thích nền tảng số học độ chính xác thấp mà QLoRA dựa vào.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, tiếng Anh. Ôn lại tinh chỉnh truyền thống để thấy QLoRA thay đổi phương thức tính toán chứ không thay đổi mục tiêu chuyển giao.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15-98 Luyện phỏng vấn (tách đặc trưng và chuyển giao)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Trong các buổi phỏng vấn kỹ sư Machine Learning, câu hỏi về Transfer Learning hiếm khi dừng ở “hãy nêu định nghĩa fine-tuning” — người phỏng vấn muốn thấy bạn phản xạ thế nào khi dữ liệu bị lệch miền, khi chỉ có 200 mẫu gắn nhãn, hoặc khi cần quyết định giữa trích xuất đặc trưng đóng băng với tinh chỉnh toàn mạng. Bài luyện phỏng vấn này trang bị cho bạn khung trả lời chặt chẽ, có số liệu và lập luận kỹ thuật sắc bén.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-năng-lực-cốt-lõi-được-kiểm-tra-khi-phỏng-vấn-về-transfer-learning&quot;&gt;Kiến thức cần nhớ: Bốn năng lực cốt lõi được kiểm tra khi phỏng vấn về Transfer Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đánh đổi Bias–Variance giữa Linear Probe và Fine-Tuning:&lt;/strong&gt; Biết cách lập luận định lượng về số tham số tự do, nguy cơ quá khớp và khả năng thích nghi biểu diễn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán giới hạn của đặc trưng đóng băng:&lt;/strong&gt; Nhận diện rõ những bài toán miền xa (ảnh vệ tinh đa phổ, siêu âm y khoa, chữ viết cổ) hoặc tác vụ cần định vị tinh (segmentation) nơi tầng cuối ImageNet đã đánh mất thông tin vị trí.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bảo toàn cấu trúc không gian khi trích xuất đặc trưng:&lt;/strong&gt; Phân biệt khi nào dùng vector sau Global Average Pooling (phân loại) và khi nào phải giữ feature map 2D/kim tự tháp FPN (phát hiện vật thể, phân đoạn).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tư duy chi phí tính toán và lưu trữ:&lt;/strong&gt; So sánh bộ nhớ lưu nhiều bản sao checkpoint đầy đủ với việc chỉ lưu các đầu tuyến tính hoặc adapter LoRA siêu nhẹ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-toán-chi-phí-lưu-trữ-khi-phục-vụ-50-tác-vụ-đích-bằng-full-fine-tuning-vs-linear-probe--adapter&quot;&gt;Giải thích: Tính toán chi phí lưu trữ khi phục vụ 50 tác vụ đích bằng Full Fine-Tuning vs. Linear Probe / Adapter&lt;/h3&gt;

&lt;p&gt;Giả sử doanh nghiệp của bạn triển khai cùng một xương sống thị giác &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ViT-Large&lt;/code&gt; (\(304\text{ triệu}\) tham số, lưu FP16 tốn \(2\text{ byte/tham số}\)) cho \(50\) khách hàng với \(50\) bài toán phân loại \(10\) lớp khác nhau (chiều đặc trưng \(d = 1024\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Full Fine-Tuning cho từng khách hàng:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Mỗi bản sao mô hình: \(304 \times 10^6 \times 2\text{ byte} \approx 608\text{ MB}\).&lt;/li&gt;
      &lt;li&gt;Tổng lưu trữ cho 50 khách hàng: \(50 \times 608\text{ MB} = 30{,}4\text{ GB}\) (và rất tốn VRAM nếu nạp đồng thời).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đóng băng xương sống + 50 đầu Linear Probe:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;1 xương sống dùng chung: \(608\text{ MB}\).&lt;/li&gt;
      &lt;li&gt;Mỗi đầu phân loại &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(1024, 10)&lt;/code&gt;: \((1024 \times 10 + 10) \times 2\text{ byte} \approx 20{,}5\text{ KB}\).&lt;/li&gt;
      &lt;li&gt;Tổng 50 đầu: \(50 \times 20{,}5\text{ KB} \approx 1{,}025\text{ MB}\). Tổng cộng chỉ \(\sim 609\text{ MB}\) — &lt;strong&gt;tiết kiệm gần 50 lần bộ nhớ&lt;/strong&gt; và có thể gộp chung batch cho cả 50 khách hàng trên một GPU!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-luyện-phỏng-vấn--trích-xuất-đặc-trưng-và-học-chuyển-giao&quot;&gt;Tùy chọn: Luyện phỏng vấn — Trích xuất đặc trưng và Học chuyển giao&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết so sánh trích xuất đặc trưng với tinh chỉnh. Sau khi học xong các bài chính, bạn có thể luyện với các câu hỏi dưới đây rồi mở &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) để xem thêm các câu hỏi có lời giải về trích xuất đặc trưng CNN. Phần hình học kiến trúc CNN nằm ở &lt;strong&gt;04-98&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Chủ đề tương ứng trong sách (đọc trong bản PDF, không tóm tắt lại ở đây):&lt;/strong&gt; sử dụng CNN đã huấn luyện làm bộ trích xuất đặc trưng; so sánh thân mạng đóng băng với thân mạng cho phép tinh chỉnh.&lt;/p&gt;

&lt;p&gt;Trang tổng hợp: &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;câu-hỏi-luyện-tập-tự-soạn&quot;&gt;Câu hỏi luyện tập (tự soạn)&lt;/h2&gt;

&lt;h3 id=&quot;q1-linear-probe-so-với-tinh-chỉnh-khối-cuối&quot;&gt;Q1. Linear probe so với tinh chỉnh khối cuối&lt;/h3&gt;

&lt;p&gt;Bạn có 800 ảnh y khoa có nhãn và một mạng ResNet tiền huấn luyện trên ImageNet. Hãy so sánh hai phương án: (a) đóng băng toàn bộ thân mạng, chỉ huấn luyện một tầng đầu ra tuyến tính và (b) mở băng khối residual cuối cùng cùng tầng đầu ra. Phương án (b) mang lại thêm rủi ro gì mà (a) không có?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; So sánh số tham số cần huấn luyện với mức độ gần nhau về phân phối thống kê giữa miền nguồn và miền đích.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Phương án (a) (&lt;em&gt;linear probe&lt;/em&gt;) tốn ít chi phí, không làm hỏng các bộ lọc đã học và thường là mốc cơ sở vững chắc. Phương án (b) cho phép điều chỉnh các bộ lọc mức trung và cao cho phù hợp với tổn thương hoặc kết cấu chưa có trong ImageNet, nhưng với chỉ 800 ảnh rất dễ quá khớp và ghi đè các bộ lọc hữu ích (tinh chỉnh quá mức). Giải pháp cân bằng trong thực tế là đặt learning rate nhỏ trên thân mạng và lớn hơn trên tầng đầu ra, hoặc dùng adapter (xem bài tùy chọn hiện đại Chương 15) — nên nhắc đến như phần mở rộng sau khi đã trả lời đúng trọng tâm.&lt;/p&gt;

&lt;h3 id=&quot;q2-khi-nào-đặc-trưng-đóng-băng-không-phù-hợp&quot;&gt;Q2. Khi nào đặc trưng đóng băng không phù hợp&lt;/h3&gt;

&lt;p&gt;Hãy nêu một miền đích cụ thể mà đặc trưng đóng băng từ ImageNet hoạt động kém dù cả miền nguồn lẫn miền đích đều là ảnh, và chỉ rõ nguồn gốc của sự sai lệch.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Xét đến loại cảm biến, góc chụp hoặc bản chất nhãn — không chỉ lý do “tập dữ liệu nhỏ”.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Ví dụ điển hình gồm ảnh mô bệnh học độ phóng đại 40×, ảnh vệ tinh có kênh ngoài dải RGB, hoặc ảnh kiểm tra khuyết tật công nghiệp cận cảnh. Sự sai lệch nằm ở cả &lt;em&gt;thống kê mức thấp lẫn ngữ nghĩa&lt;/em&gt;, không chỉ ở kích thước mẫu. Trong các trường hợp này, tinh chỉnh sâu hơn vào thân mạng hoặc tiền huấn luyện trong miền bằng học tự giám sát (Chương 16) sẽ hiệu quả hơn việc chỉ gắn thêm mạng MLP sâu lên trên đặc trưng RGB đóng băng.&lt;/p&gt;

&lt;h3 id=&quot;q3-nên-giữ-cấu-trúc-nào-khi-trích-xuất-đặc-trưng&quot;&gt;Q3. Nên giữ cấu trúc nào khi trích xuất đặc trưng&lt;/h3&gt;

&lt;p&gt;Một đồng nghiệp “trích xuất đặc trưng” bằng cách lấy bản đồ đặc trưng \(7\times7\times2048\) của ResNet-50 rồi trải phẳng toàn bộ để huấn luyện SVM. Hãy nêu một lý do nên áp dụng &lt;em&gt;global average pooling&lt;/em&gt; (GAP) trước, và một loại tác vụ mà ta cần &lt;em&gt;giữ nguyên&lt;/em&gt; bản đồ không gian.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Cân nhắc giữa tính bất biến tịnh tiến và yêu cầu định vị không gian.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Áp dụng GAP rút gọn đặc trưng xuống vector \(2048\) chiều có tính bất biến tịnh tiến và kích thước phù hợp để huấn luyện SVM (tránh bùng nổ số chiều thành 100.352). Ngược lại, các bài toán phát hiện đối tượng (&lt;em&gt;detection&lt;/em&gt;), phân đoạn (&lt;em&gt;segmentation&lt;/em&gt;) hoặc định vị vị trí vật thể cần giữ nguyên tensor không gian (hoặc dùng kim tự tháp đặc trưng). “Trích xuất đặc trưng” không chỉ là chọn kích thước vector mà là chọn tính bất biến phù hợp với bài toán.&lt;/p&gt;

&lt;h3 id=&quot;q4-lệch-miền-trong-thực-tế-triển-khai&quot;&gt;Q4. Lệch miền trong thực tế triển khai&lt;/h3&gt;

&lt;p&gt;Tập huấn luyện gồm ảnh sản phẩm chụp trong studio, còn ảnh thực tế khi triển khai là ảnh chụp bằng điện thoại trong kho hàng. Bạn chỉ tinh chỉnh tầng đầu ra và đạt độ chính xác rất cao trên tập validation (vốn cũng là ảnh studio). Bạn thực sự mới đo được điều gì, và cần bổ sung thí nghiệm nào trước khi đưa vào sử dụng?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Phân biệt đánh giá trên tập validation cùng phân phối (&lt;em&gt;i.i.d.&lt;/em&gt;) với phân phối triển khai thực tế.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Kết quả đó mới chỉ đo chất lượng tầng đầu ra trong cùng miền studio chứ chưa kiểm chứng khả năng chuyển giao sang môi trường kho. Trước khi triển khai, cần thu thập và gán nhãn một tập kiểm tra nhỏ chụp trực tiếp trong kho để đo hiệu năng thực tế. Các phép tăng cường dữ liệu như biến đổi ánh sáng, màu sắc hay cắt khung có thể hỗ trợ thu hẹp khoảng cách nhưng không thể thay thế tập validation thuộc miền đích.&lt;/p&gt;

&lt;h2 id=&quot;ghi-công&quot;&gt;Ghi công&lt;/h2&gt;

&lt;p&gt;Kashani, S., và Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Bạn có thể tải bản PDF từ arXiv để xem toàn bộ bộ câu hỏi và lời giải. Các câu hỏi trên trang này được biên soạn riêng cho khóa học, không phải bản sao chép lại từ sách.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, tiếng Anh. Ôn lại các câu hỏi cốt lõi về trích xuất đặc trưng và tinh chỉnh.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qaDe0qQZ5AQ&quot;&gt;Pytorch Transfer Learning and Fine Tuning Tutorial&lt;/a&gt; — Aladdin Persson, tiếng Anh. Nắm rõ nhóm tham số nào nhận gradient trong từng chiến lược.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích vì sao các bộ lọc ở tầng sớm thường nên được giữ lại.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15-01 Nền tảng Học Chuyển giao</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_01_Transfer_Learning_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_01_Transfer_Learning_Fundamentals</id>
   <content type="html">&lt;p&gt;Trong thực tế công nghiệp, hơn 90% dự án học sâu thành công không bắt đầu bằng việc phát minh một kiến trúc mạng mới, mà bắt đầu bằng việc chọn đúng một mô hình nền (foundation/pretrained model) và biết cách tinh chỉnh nó thật khéo. Mục tổng quan nền tảng này hệ thống hóa ma trận quyết định kinh điển của Học Chuyển giao trước khi đi sâu vào lý thuyết (&lt;strong&gt;15-01-01&lt;/strong&gt;) và mã nguồn PyTorch (&lt;strong&gt;15-01-02&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ma-trận-quyết-định-4-tình-huống-trong-học-chuyển-giao&quot;&gt;Kiến thức cần nhớ: Ma trận quyết định 4 tình huống trong Học Chuyển giao&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Dữ liệu đích ít + Miền tương đồng nguồn:&lt;/strong&gt; Đóng băng toàn bộ xương sống, chỉ huấn luyện bộ phân loại tuyến tính (Linear Probing) hoặc dùng đặc trưng trích xuất cho SVM/Logistic Regression.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dữ liệu đích nhiều + Miền tương đồng nguồn:&lt;/strong&gt; Tinh chỉnh toàn bộ mạng (hoặc phần lớn các khối trên) với tốc độ học nhỏ để đạt độ chính xác tối đa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dữ liệu đích ít + Miền khác biệt nguồn:&lt;/strong&gt; Trích xuất đặc trưng từ các &lt;em&gt;tầng nông/giữa&lt;/em&gt; (nơi biểu diễn còn tổng quát) thay vì tầng cuối quá chuyên biệt cho nhãn nguồn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dữ liệu đích nhiều + Miền khác biệt nguồn:&lt;/strong&gt; Khởi tạo từ trọng số tiền huấn luyện (vẫn hội tụ nhanh hơn khởi tạo ngẫu nhiên) và mở khóa huấn luyện lại toàn bộ mạng.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-áp-dụng-ma-trận-quyết-định-và-ước-lượng-tốc-độ-học-phân-tầng-cho-2-bài-toán-thực-tế&quot;&gt;Giải thích: Áp dụng ma trận quyết định và ước lượng tốc độ học phân tầng cho 2 bài toán thực tế&lt;/h3&gt;

&lt;p&gt;Xét mô hình xương sống 4 giai đoạn (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stage1&lt;/code&gt; → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stage4&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;head&lt;/code&gt;) với tốc độ học cơ sở cho đầu phân loại \(\eta_0 = 10^{-3}\) và hệ số suy giảm theo tầng \(\gamma = 0{,}3\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tình huống A — Phân loại 12 giống chó địa phương (600 ảnh, rất giống ImageNet):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Đóng băng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stage1&lt;/code&gt;–&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stage4&lt;/code&gt; trong 5 epoch đầu, chỉ train &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;head&lt;/code&gt; với \(\eta_0 = 10^{-3}\).&lt;/li&gt;
      &lt;li&gt;Sau đó mở khóa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stage4&lt;/code&gt; với \(\eta_4 = \eta_0 \cdot \gamma = 3 \times 10^{-4}\) trong 5 epoch nữa.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tình huống B — Phân loại vết nứt bề mặt kim loại (25.000 ảnh, khác ImageNet):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Mở khóa toàn bộ mạng với tốc độ học phân tầng: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;head&lt;/code&gt; \(= 10^{-3}\), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stage4&lt;/code&gt; \(= 3 \times 10^{-4}\), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stage3&lt;/code&gt; \(= 9 \times 10^{-5}\), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stage2&lt;/code&gt; \(= 2{,}7 \times 10^{-5}\), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stage1&lt;/code&gt; \(= 8{,}1 \times 10^{-6}\).
Cách chia bậc số học này giúp các bộ lọc cạnh ở &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stage1&lt;/code&gt; dịch chuyển cực chậm và ổn định trong khi các tầng cao nhanh chóng thích nghi với kết cấu kim loại.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nội dung nền tảng về học chuyển giao gồm hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết&lt;/strong&gt; — khái niệm cốt lõi, các chiến lược chuyển giao, lý thuyết thích ứng miền và ví dụ minh họa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt&lt;/strong&gt; — so sánh trích xuất đặc trưng và tinh chỉnh trong PyTorch, bài báo nền tảng và các cạm bẫy thường gặp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, tiếng Anh. Phân biệt rõ chiến lược trích xuất đặc trưng và tinh chỉnh.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qaDe0qQZ5AQ&quot;&gt;Pytorch Transfer Learning and Fine Tuning Tutorial&lt;/a&gt; — Aladdin Persson, tiếng Anh. Minh họa cả hai chiến lược bằng mã PyTorch.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích các đặc trưng thị giác tầng sớm được tái sử dụng trong cả hai chiến lược.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15-01-02 Cài đặt Học Chuyển giao</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_01_02_Transfer_Learning_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_01_02_Transfer_Learning_Implementation</id>
   <content type="html">&lt;p&gt;Một trong những lỗi “âm thầm” phổ biến nhất khi dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torchvision.models&lt;/code&gt; là tải ResNet tiền huấn luyện về, đặt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;requires_grad = False&lt;/code&gt; cho xương sống… nhưng lại quên mất rằng các tầng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BatchNorm&lt;/code&gt; vẫn đang âm thầm cập nhật &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;running_mean&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;running_var&lt;/code&gt;, hoặc quên chuẩn hóa ảnh đầu vào theo đúng trung bình/độ lệch chuẩn của ImageNet! Bài thực hành này dẫn bạn từng bước cài đặt hoàn chỉnh quy trình Transfer Learning trong PyTorch — từ đóng băng tầng, thay đầu phân loại, thiết lập tốc độ học phân tầng đến chiến lược mở khóa dần (gradual unfreezing).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-chi-tiết-kỹ-thuật-bắt-buộc-khi-cài-đặt-transfer-learning&quot;&gt;Kiến thức cần nhớ: Bốn chi tiết kỹ thuật bắt buộc khi cài đặt Transfer Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Khớp tiền xử lý với trọng số tiền huấn luyện:&lt;/strong&gt; Luôn dùng đúng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weights.transforms()&lt;/code&gt; (chuẩn hóa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean=[0.485, 0.456, 0.406]&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;std=[0.229, 0.224, 0.225]&lt;/code&gt; và kích thước ảnh chuẩn) để đầu vào không bị lệch phân phối ngay từ tầng đầu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quản lý &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;requires_grad&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;optimizer&lt;/code&gt; parameter groups:&lt;/strong&gt; Chỉ truyền các tham số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;requires_grad=True&lt;/code&gt; vào bộ tối ưu, và gán từng nhóm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lr&lt;/code&gt; khác nhau (ví dụ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-4&lt;/code&gt; cho backbone, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-3&lt;/code&gt; cho head).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chiến lược hai pha (Warm-up Head → Unfreeze Backbone):&lt;/strong&gt; Huấn luyện riêng đầu phân loại vài epoch trước khi mở khóa xương sống để tránh gradient nhiễu ban đầu phá hỏng các bộ lọc tốt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm soát chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BatchNorm&lt;/code&gt; và Weight Decay:&lt;/strong&gt; Giữ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bn.eval()&lt;/code&gt; khi đóng băng xương sống hoặc khi batch size quá nhỏ, đồng thời tách weight decay hợp lý với AdamW.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-kiểm-tra-ảnh-hưởng-của-việc-quên-chuẩn-hóa-imagenet-lên-đầu-vào-tầng-đầu&quot;&gt;Giải thích: Kiểm tra ảnh hưởng của việc quên chuẩn hóa ImageNet lên đầu vào tầng đầu&lt;/h3&gt;

&lt;p&gt;Giả sử một điểm ảnh màu đỏ sáng có giá trị pixel gốc trong \([0, 1]\) là \(x_R = 0{,}85\). Xương sống ResNet-18 tiền huấn luyện trên ImageNet kỳ vọng kênh đỏ được chuẩn hóa bằng \(\mu_R = 0{,}485\) và \(\sigma_R = 0{,}229\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giá trị chuẩn hóa đúng:&lt;/strong&gt;
\(x_R^{\text{đúng}} = \frac{0{,}85 - 0{,}485}{0{,}229} = \frac{0{,}365}{0{,}229} \approx +1{,}594.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nếu quên chuẩn hóa (đưa thẳng \(0{,}85\) vào mạng):&lt;/strong&gt; Sai lệch đầu vào so với phân phối mà bộ lọc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv1&lt;/code&gt; đã học lên tới \(1{,}594 - 0{,}850 = 0{,}744\) độ lệch chuẩn!
Với một điểm ảnh tối \(x_R = 0{,}05\), giá trị đúng là \((0{,}05 - 0{,}485)/0{,}229 \approx -1{,}900\) (âm sâu), trong khi đưa thẳng \(0{,}05\) lại là số dương — làm sai lệch hoàn toàn ngưỡng kích hoạt ReLU ngay từ tầng tích chập đầu tiên.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-đoạn-mã&quot;&gt;4. Đoạn mã&lt;/h2&gt;

&lt;p&gt;Đoạn mã dưới đây cài đặt đầy đủ hai chiến lược học chuyển giao (trích xuất đặc trưng và tinh chỉnh với learning rate phân biệt theo tầng) trên ResNet-18 tiền huấn luyện ImageNet với một tập con 1000 ảnh của CIFAR-10:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.utils.data&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_split&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Học Chuyển giao: Tinh chỉnh ResNet Tiền huấn luyện cho Tập Dữ liệu Tùy chỉnh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tải ResNet18 tiền huấn luyện (nhỏ hơn ResNet50 để minh họa)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Tải Mô hình Tiền huấn luyện&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# weights=&apos;IMAGENET1K_V1&apos; tải trọng số tiền huấn luyện ImageNet
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;resnet18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;IMAGENET1K_V1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đã tải ResNet18 tiền huấn luyện trên ImageNet&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tầng đầu ra gốc: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (1000 lớp cho ImageNet)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Xem xét điều mô hình tiền huấn luyện đã học
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đặc trưng tiền huấn luyện:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Bộ lọc tầng 1: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (64, 3, 7, 7)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Đây là bộ phát hiện cạnh/texture học từ ImageNet&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 2. Thích ứng cho tác vụ mới
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Thích ứng cho Tác vụ Tùy chỉnh (10 Lớp)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Thay tầng fully-connected cuối cho tác vụ của ta
# Mọi thứ khác giữ trọng số tiền huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Tác vụ tùy chỉnh của ta có 10 lớp
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Lấy kích thước đầu vào tầng fc
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đặc trưng đầu vào FC gốc: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Thay tầng cuối cho &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; lớp...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tầng đầu ra mô hình mới: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (10 lớp cho tác vụ tùy chỉnh của ta)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo tập dữ liệu giả (trong thực tiễn, dùng dữ liệu thật của bạn)
# Ta sẽ mô phỏng với CIFAR-10 như tác vụ &quot;tùy chỉnh&quot;
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;3. Chuẩn bị Tập Dữ liệu Tùy chỉnh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;transform_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Compose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Resize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;224&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ResNet mong đợi 224×224 (CIFAR là 32×32)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ToTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normalize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.485&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.456&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.406&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.229&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.224&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.225&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Thống kê ImageNet
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Mô phỏng kịch bản dữ liệu hạn chế: chỉ dùng 1000 ảnh huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;full_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CIFAR10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Lấy tập con để mô phỏng dữ liệu hạn chế
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;limited_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;remaining&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;full_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;limited_size&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;random_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;full_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;limited_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;remaining&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CIFAR10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện với chỉ &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;limited_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; ảnh (mô phỏng dữ liệu hạn chế)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tập kiểm tra: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; ảnh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 3. Chiến lược Huấn luyện: Trích xuất Đặc trưng so với Tinh chỉnh
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;4. Chiến lược A: Trích xuất Đặc trưng (Đóng băng Tầng Tiền huấn luyện)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo bản sao mô hình cho trích xuất đặc trưng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;resnet18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;IMAGENET1K_V1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Đóng băng mọi tầng trừ FC cuối
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Mở băng tầng cuối
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;trainable_params_fe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tổng tham số: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tham số huấn luyện được: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainable_params_fe&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainable_params_fe&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Chỉ huấn luyện tầng phân loại cuối!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Optimizer cho trích xuất đặc trưng (chỉ tham số tầng fc)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer_fe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CrossEntropyLoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện mô hình trích xuất đặc trưng (5 epoch)...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_fe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward (tầng conv đóng băng, chỉ fc huấn luyện)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_fe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Train Acc = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Đánh giá
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_acc_fe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Độ chính xác Kiểm tra Trích xuất Đặc trưng: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_acc_fe&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 4. Chiến lược B: Tinh chỉnh
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;5. Chiến lược B: Tinh chỉnh (Cập nhật Mọi Tầng)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;resnet18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;IMAGENET1K_V1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Mọi tham số huấn luyện được
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainable_params_ft&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tham số huấn luyện được: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainable_params_ft&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (100%)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Dùng learning rate vi phân
# LR thấp hơn cho tầng tiền huấn luyện, cao hơn cho tầng mới
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer_ft&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0002&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0005&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cao nhất cho tầng mới
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Mặc định cho bất kỳ tham số nào không chỉ định
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dùng learning rate vi phân theo tầng:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tầng sớm: 0.0001 (hầu như không đổi)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tầng giữa: 0.0002&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tầng sâu: 0.0005&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tầng FC mới: 0.001 (thay đổi nhiều nhất)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện mô hình tinh chỉnh (5 epoch)...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_ft&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_ft&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Train Acc = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Đánh giá
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_acc_ft&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Độ chính xác Kiểm tra Tinh chỉnh: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_acc_ft&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# So sánh kết quả
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;So sánh Kết quả Học Chuyển giao&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trích xuất Đặc trưng: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_acc_fe&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% độ chính xác kiểm tra&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tinh chỉnh:           &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_acc_ft&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% độ chính xác kiểm tra&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cả hai vượt trội đáng kể so với huấn luyện từ đầu (~60% trên 1000 ảnh)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Học chuyển giao cho phép hiệu năng cạnh tranh với dữ liệu hạn chế!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Đoạn mã tiếp theo minh họa cách trích xuất bản đồ đặc trưng trung gian bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;forward_hook&lt;/code&gt; để phân tích biểu diễn đã học:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Phân tích Đặc trưng Chuyển giao&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trích xuất đặc trưng để phân tích
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;extract_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;layer4&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Trích xuất đặc trưng từ một tầng cụ thể.
    
    Điều này cho thấy biểu diễn mô hình dùng cho phân loại.
    Đặc trưng tiền huấn luyện nên có nghĩa ngay cả cho tác vụ tùy chỉnh.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;features_list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;labels_list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Đăng ký hook để bắt đầu ra tầng
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;features_hook&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;hook_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;features_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Lấy tầng
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;named_modules&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;handle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;register_forward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hook_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;features_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;labels_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;features_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;handle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;remove&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Nối tất cả batch
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trích xuất đặc trưng layer4 (tầng conv cuối trước FC)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;extract_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
    &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; 
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;layer4&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đã trích xuất đặc trưng từ layer4 (tầng conv cuối)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape đặc trưng: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1000, 512, 7, 7)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Global average pool để nhận vectơ 512 chiều
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_pooled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;features_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1000, 512)
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sau global average pooling: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_pooled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Các đặc trưng 512 chiều này mã hóa:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Mức thấp: cạnh, texture (từ ImageNet)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Mức trung: phần đối tượng, hình dạng (từ ImageNet)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Mức cao: mẫu chuyên chim (thích ứng trong tinh chỉnh)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đặc trưng tiền huấn luyện cung cấp điểm khởi đầu mạnh!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-các-khái-niệm-liên-quan&quot;&gt;5. Các khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Học chuyển giao có liên hệ gần với &lt;strong&gt;học đa tác vụ (&lt;em&gt;multi-task learning&lt;/em&gt;)&lt;/strong&gt;, trong đó một mô hình duy nhất được huấn luyện đồng thời trên nhiều tác vụ liên quan thay vì tuần tự. Học đa tác vụ dùng chung thân mạng ở các tầng sớm và giữa cùng các đầu ra riêng cho từng tác vụ; việc buộc một biểu diễn phục vụ đồng thời nhiều mục tiêu tạo ra cơ chế chính quy hóa tự nhiên giúp cải thiện khả năng tổng quát hóa.&lt;/p&gt;

&lt;p&gt;Học chuyển giao cũng liên hệ với &lt;strong&gt;meta-learning&lt;/strong&gt; (“học cách học”). Các thuật toán như MAML tìm một điểm khởi tạo sao cho chỉ cần vài bước cập nhật gradient là thích nghi tốt với tác vụ mới. Có thể xem học chuyển giao là trường hợp đơn giản của khung này, trong đó tiền huấn luyện đóng vai trò tạo khởi tạo ban đầu và tinh chỉnh là bước thích nghi.&lt;/p&gt;

&lt;p&gt;Trong xử lý ngôn ngữ tự nhiên (NLP), học chuyển giao đã phát triển qua nhiều giai đoạn: từ chuyển giao embedding từ tĩnh (Word2Vec, GloVe), sang biểu diễn ngữ cảnh (ELMo), đến tiền huấn luyện toàn bộ kiến trúc Transformer bằng masked language modeling rồi tinh chỉnh cho từng tác vụ (BERT), và tiếp đến là các mô hình ngôn ngữ lớn dòng GPT cho phép thích nghi vài mẫu (&lt;em&gt;few-shot&lt;/em&gt;) qua ngữ cảnh prompt mà không cần cập nhật trọng số.&lt;/p&gt;

&lt;p&gt;Từ góc nhìn &lt;strong&gt;curriculum learning&lt;/strong&gt;, học chuyển giao tương tự lộ trình học theo từng bước: học đặc trưng tổng quát trên tập lớn trước rồi mới chuyên biệt hóa sang bài toán đích. Điều này gợi ý chiến lược chuyển giao nhiều giai đoạn — ví dụ tiền huấn luyện trên ảnh tự nhiên (ImageNet), huấn luyện trung gian trên tập ảnh y khoa tổng quát, rồi mới tinh chỉnh trên bài toán chẩn đoán cụ thể.&lt;/p&gt;

&lt;p&gt;Cuối cùng, học chuyển giao giải quyết trực tiếp bài toán &lt;strong&gt;hiệu quả mẫu (&lt;em&gt;sample efficiency&lt;/em&gt;)&lt;/strong&gt;: chi phí học các đặc trưng nền tảng được phân bổ trên nhiều tác vụ về sau, giúp ứng dụng học sâu khả thi ở những lĩnh vực chi phí gán nhãn cao hoặc khó thu thập dữ liệu quy mô lớn.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1411.1792&quot;&gt;“How transferable are features in deep neural networks?” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Jason Yosinski, Jeff Clune, Yoshua Bengio, Hector Lipson&lt;br /&gt;
Bài báo khảo sát có hệ thống khả năng chuyển giao đặc trưng theo từng độ sâu tầng trên ImageNet. Kết quả chỉ ra các tầng sớm mang tính tổng quát cao và chuyển giao tốt, còn các tầng sâu chuyên biệt hơn cho tác vụ nguồn. Nhóm tác giả cũng ghi nhận hiện tượng các tầng liền kề đồng thích nghi (&lt;em&gt;co-adaptation&lt;/em&gt;), nên việc đóng băng ở giữa mạng có thể làm giảm hiệu năng so với tinh chỉnh toàn mạng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.cv-foundation.org/openaccess/content_cvpr_2014/papers/Oquab_Learning_and_Transferring_2014_CVPR_paper.pdf&quot;&gt;“Learning and Transferring Mid-Level Image Representations using Convolutional Neural Networks” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Maxime Oquab, Leon Bottou, Ivan Laptev, Josef Sivic&lt;br /&gt;
Bài báo chứng minh đặc trưng từ CNN tiền huấn luyện trên ImageNet chuyển giao hiệu quả sang nhiều bài toán thị giác khác như phát hiện đối tượng, phân loại cảnh và nhận diện chi tiết, vượt trội các đặc trưng thủ công và góp phần đưa học chuyển giao thành chuẩn mực trong thị giác máy tính.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;“BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova&lt;br /&gt;
Bài báo giới thiệu BERT và chứng minh mô hình &lt;em&gt;tiền huấn luyện rồi tinh chỉnh&lt;/em&gt; trên Transformer đạt kết quả cao trên 11 bài toán NLP khác nhau (hỏi đáp, suy diễn ngôn ngữ tự nhiên, nhận diện thực thể) chỉ bằng cách gắn thêm tầng đầu ra đơn giản cho từng tác vụ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://ieeexplore.ieee.org/document/5288526&quot;&gt;“A Survey on Transfer Learning” (2010)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Sinno Jialin Pan, Qiang Yang&lt;br /&gt;
Bài tổng quan hệ thống hóa các dạng học chuyển giao trong học máy gồm &lt;em&gt;inductive&lt;/em&gt;, &lt;em&gt;transductive&lt;/em&gt; và &lt;em&gt;unsupervised transfer&lt;/em&gt;, phân tích điều kiện để chuyển giao hiệu quả cũng như hiện tượng &lt;em&gt;chuyển giao tiêu cực (negative transfer)&lt;/em&gt; khi miền nguồn và miền đích lệch nhau quá lớn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1811.08883&quot;&gt;“Rethinking ImageNet Pre-training” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Kaiming He, Ross Girshick, Piotr Dollár&lt;br /&gt;
Bài báo chỉ ra rằng khi bài toán đích có đủ dữ liệu lớn (hàng chục nghìn ảnh trở lên) và thời gian huấn luyện đủ dài, huấn luyện từ đầu có thể đạt hiệu năng ngang bằng hoặc vượt tinh chỉnh từ ImageNet. Do đó, lợi thế lớn nhất của tiền huấn luyện nằm ở tốc độ hội tụ nhanh và cải thiện rõ rệt trong chế độ ít dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo&quot;&gt;Bẫy thường gặp và Mẹo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Không đồng bộ tiền xử lý với giai đoạn tiền huấn luyện&lt;/strong&gt; là sai sót phổ biến nhất. Nếu mô hình tiền huấn luyện trên ImageNet dùng chuẩn hóa RGB (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean=[0.485, 0.456, 0.406]&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;std=[0.229, 0.224, 0.225]&lt;/code&gt;), quá trình trích xuất đặc trưng hoặc tinh chỉnh phải áp dụng đúng kích thước và chuẩn hóa tương ứng để tránh lệch phân phối đầu vào.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đặt learning rate quá lớn khi tinh chỉnh&lt;/strong&gt; dễ phá vỡ các đặc trưng tiền huấn luyện trước khi kịp thích nghi. Quy tắc thực hành là giảm learning rate 10–100 lần so với huấn luyện từ đầu (ví dụ 0,0001–0,001), hoặc dùng learning rate phân biệt theo tầng (nhỏ ở tầng sớm, lớn hơn ở tầng sâu và tầng đầu ra mới).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quên chuyển sang chế độ đánh giá khi trích xuất đặc trưng&lt;/strong&gt; khiến batch normalization và dropout hoạt động theo chế độ huấn luyện, tạo ra đầu ra không nhất quán giữa các lần chạy. Luôn gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; kết hợp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.no_grad()&lt;/code&gt; khi trích xuất đặc trưng hoặc suy luận.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quên thảm họa theo độ dài chuỗi trong NLP:&lt;/strong&gt; BERT được tiền huấn luyện trên chuỗi tới 512 token; nếu chỉ tinh chỉnh trên văn bản rất ngắn (20–50 token), khả năng xử lý chuỗi dài có thể suy giảm. Cần bổ sung dữ liệu dài hơn nếu ứng dụng yêu cầu xử lý văn bản dài.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chiến lược mở băng dần (&lt;em&gt;gradual unfreezing&lt;/em&gt;) và learning rate chu kỳ:&lt;/strong&gt; bắt đầu bằng việc chỉ huấn luyện tầng đầu ra, sau đó mở băng dần từ tầng sâu ngược về tầng sớm kết hợp điều chỉnh learning rate giúp mô hình thích nghi êm hơn mà vẫn bảo toàn đặc trưng tổng quát. Khi miền đích khác nhiều so với miền nguồn, tinh chỉnh một phần (đóng băng các tầng sớm, tinh chỉnh tầng giữa và sâu) thường cân bằng tốt giữa độ ổn định và khả năng thích nghi.&lt;/p&gt;

&lt;h2 id=&quot;điểm-then-chốt&quot;&gt;Điểm then chốt&lt;/h2&gt;

&lt;p&gt;Học chuyển giao khai thác các mô hình tiền huấn luyện để đạt hiệu năng tốt khi dữ liệu đích còn hạn chế. Nhờ tính phân cấp của đặc trưng mạng sâu, ta có thể chọn trích xuất đặc trưng (đóng băng thân mạng, phù hợp khi dữ liệu rất ít) hoặc tinh chỉnh toàn bộ/một phần mạng với learning rate nhỏ hoặc phân biệt theo tầng (phù hợp khi có thêm dữ liệu hoặc cần thích nghi sâu hơn). Hiệu quả chuyển giao phụ thuộc vào chất lượng mô hình tiền huấn luyện và mức độ tương đồng giữa hai miền; đây đã trở thành quy trình khởi đầu tiêu chuẩn trong thị giác máy tính, xử lý ngôn ngữ tự nhiên và xử lý giọng nói.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qaDe0qQZ5AQ&quot;&gt;Pytorch Transfer Learning and Fine Tuning Tutorial&lt;/a&gt; — Aladdin Persson, tiếng Anh. Hướng dẫn tải mô hình tiền huấn luyện, thay tầng đầu ra và huấn luyện trong PyTorch.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, tiếng Anh. Giải thích logic chọn tầng đóng băng tương ứng với phần mã nguồn trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pDdP0TFzsoQ&quot;&gt;PyTorch Tutorial 14 - Convolutional Neural Network (CNN)&lt;/a&gt; — Patrick Loeber, tiếng Anh. Ôn lại cấu trúc các tầng trong mạng tích chập nền nếu tên mô-đun còn chưa quen thuộc.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15-01-01 Lý thuyết Học Chuyển giao</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_01_01_Transfer_Learning_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_01_01_Transfer_Learning_Theory</id>
   <content type="html">&lt;p&gt;Vì sao một mô hình học nhận diện chó, mèo và xe tải trên ImageNet lại có thể giúp phát hiện khối u trên phim X-quang phổi chính xác hơn hẳn một mô hình huấn luyện trực tiếp trên X-quang từ đầu? Câu trả lời không phải là phép màu, mà nằm trong &lt;strong&gt;Lý thuyết Thích ứng Miền (Domain Adaptation Theory)&lt;/strong&gt; của Ben-David và cộng sự: sai số trên miền đích bị chặn trên bởi ba đại lượng đo được rất cụ thể.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cơ-sở-lý-thuyết-của-học-chuyển-giao-và-thích-ứng-miền&quot;&gt;Kiến thức cần nhớ: Cơ sở lý thuyết của học chuyển giao và thích ứng miền&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Định lý cận tổng quát hóa miền đích (Ben-David Bound):&lt;/strong&gt; Ràng buộc sai số mục tiêu \(\epsilon_T(h) \le \epsilon_S(h) + \frac{1}{2} d_{\mathcal{H}\Delta\mathcal{H}}(\mathcal{D}_S, \mathcal{D}_T) + \lambda^*\), tách rõ sai số nguồn, khoảng cách phân phối miền và sai số lý tưởng chung.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tốc độ học phân tầng (Discriminative Learning Rates):&lt;/strong&gt; Vì gradient biến thiên mạnh ở tầng đầu phân loại mới khởi tạo ngẫu nhiên, ta gán \(\eta_{\text{head}} \gg \eta_{\text{backbone}}\) để không phá hủy biểu diễn tiền huấn luyện (tránh &lt;em&gt;catastrophic forgetting&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hành vi thống kê của Batch Normalization khi chuyển miền:&lt;/strong&gt; Phân biệt rõ chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval()&lt;/code&gt; (giữ trung bình/phương sai nguồn) và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train()&lt;/code&gt; (cập nhật thống kê miền đích) khi tinh chỉnh trên batch nhỏ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tách biệt Covariate Shift và Concept Shift:&lt;/strong&gt; Nhận biết miền đích khác miền nguồn ở phân phối đầu vào \(P(X)\) hay ở chính quy tắc gán nhãn \(P(Y\mid X)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-định-lượng-cận-sai-số-miền-đích-theo-bất-đẳng-thức-ben-david&quot;&gt;Giải thích: Định lượng cận sai số miền đích theo bất đẳng thức Ben-David&lt;/h3&gt;

&lt;p&gt;Giả sử ta chuyển giao một bộ phân loại ảnh y tế từ bệnh viện A (miền nguồn \(S\)) sang bệnh viện B (miền đích \(T\)) dùng máy chụp đời khác:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Sai số trên miền nguồn: \(\epsilon_S(h) = 0{,}04\) (\(4\%\)).&lt;/li&gt;
  &lt;li&gt;Khoảng cách phân kỳ hai miền: \(d_{\mathcal{H}\Delta\mathcal{H}}(\mathcal{D}_S, \mathcal{D}_T) = 0{,}16\).&lt;/li&gt;
  &lt;li&gt;Sai số kết hợp tối ưu không thể tránh khỏi: \(\lambda^* = 0{,}03\).&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính cận trên sai số miền đích trước khi thích ứng miền:&lt;/strong&gt;
\(\epsilon_T(h) \le 0{,}04 + \frac{1}{2}(0{,}16) + 0{,}03 = 0{,}04 + 0{,}08 + 0{,}03 = 0{,}15\;(15\%).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng chuẩn hóa độ tương phản và trích xuất đặc trưng bất biến miền&lt;/strong&gt; để giảm \(d_{\mathcal{H}\Delta\mathcal{H}}\) từ \(0{,}16\) xuống \(0{,}04\) (giữ nguyên \(\epsilon_S = 0{,}04, \lambda^* = 0{,}03\)):
\(\epsilon_T(h) \le 0{,}04 + \frac{1}{2}(0{,}04) + 0{,}03 = 0{,}09\;(9\%).\)
Con số này cho thấy bài học chiến lược: khi \(\epsilon_S\) đã rất thấp, cố gắng ép loss trên miền nguồn giảm thêm gần như vô ích; muốn thắng trên miền đích phải tập trung kéo giảm &lt;strong&gt;khoảng cách miền&lt;/strong&gt; \(d_{\mathcal{H}\Delta\mathcal{H}}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;học-chuyển-giao-tận-dụng-tri-thức-tiền-huấn-luyện&quot;&gt;Học Chuyển giao: Tận dụng tri thức tiền huấn luyện&lt;/h1&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Học chuyển giao (&lt;em&gt;transfer learning&lt;/em&gt;) là một trong những phương pháp thực tiễn quan trọng nhất của học sâu hiện đại, cho phép xây dựng mô hình có hiệu năng cao với lượng dữ liệu nhãn hạn chế bằng cách kế thừa tri thức học được từ một bài toán liên quan. Nguyên lý cốt lõi khá trực tiếp: thay vì khởi tạo trọng số ngẫu nhiên và huấn luyện từ đầu, ta xuất phát từ bộ trọng số đã được tiền huấn luyện trên một tập dữ liệu lớn, sau đó điều chỉnh cho bài toán mục tiêu. Nhờ vậy, học sâu trở nên khả thi ngay cả khi không có tập dữ liệu lớn hay nguồn lực tính toán dồi dào: bài toán ảnh y khoa có thể khởi đầu từ mạng tiền huấn luyện trên ImageNet, bài toán phân tích cảm xúc có thể tinh chỉnh từ BERT tiền huấn luyện trên kho văn bản web, và hệ thống nhận dạng giọng nói có thể tinh chỉnh từ Wav2Vec học trên dữ liệu âm thanh không nhãn.&lt;/p&gt;

&lt;p&gt;Học chuyển giao phát huy hiệu quả nhờ cấu trúc biểu diễn phân cấp của mạng nơ-ron sâu. Các tầng sớm học đặc trưng mức thấp mang tính tổng quát — biên cạnh, kết cấu bề mặt và hình khối cơ bản đối với ảnh; âm vị cơ bản đối với âm thanh; các mẫu từ phổ biến đối với văn bản. Những đặc trưng này khá tương đồng giữa nhiều bài toán khác nhau: mạng phân loại xe hơi và xe tải học bộ lọc phát hiện cạnh tương tự mạng phân loại chó và mèo. Các tầng giữa học đặc trưng mức trung như bộ phận đối tượng hoặc tổ hợp kết cấu, vẫn có tính tái sử dụng cao. Chỉ những tầng sâu nhất mới chuyên biệt mạnh cho nhãn cụ thể của bài toán nguồn.&lt;/p&gt;

&lt;p&gt;Nhờ tính tái sử dụng này, các tầng sớm và tầng giữa đã được tiền huấn luyện tạo thành điểm khởi đầu vững chắc cho bài toán đích. Ngay cả khi miền đích khác miền nguồn (chẳng hạn ảnh y khoa so với ảnh tự nhiên trong ImageNet), các đặc trưng thị giác cơ bản như biên cạnh và kết cấu vẫn còn giá trị, giúp mô hình tập trung dữ liệu đích hạn chế vào việc học các đặc trưng chuyên biệt ở tầng sâu hơn.&lt;/p&gt;

&lt;p&gt;Về mặt thực tế, học chuyển giao giúp giảm mạnh nhu cầu dữ liệu gán nhãn. Trong thị giác máy tính, nhiều bài toán phân loại ảnh chỉ cần vài trăm đến vài nghìn ảnh khi tận dụng mô hình tiền huấn luyện ImageNet thay vì hàng trăm nghìn ảnh nếu huấn luyện từ đầu. Trong xử lý ngôn ngữ tự nhiên, các mô hình như BERT tiền huấn luyện trên kho văn bản lớn có thể tinh chỉnh hiệu quả cho phân tích cảm xúc, nhận diện thực thể hay hỏi đáp chỉ với vài nghìn ví dụ gán nhãn, mở rộng phạm vi ứng dụng sang các lĩnh vực khó thu thập nhãn như chẩn đoán y khoa hay tài liệu kỹ thuật chuyên ngành.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, học chuyển giao không phải lúc nào cũng hiệu quả. Phương pháp này dựa trên giả định miền nguồn và miền đích chia sẻ một phần cấu trúc dữ liệu. Đặc trưng học từ ImageNet thường chuyển giao kém hơn sang dữ liệu có tính chất cảm biến hoặc phân phối khác biệt mạnh như ảnh radar, ảnh vệ tinh đa phổ hoặc đồ họa trừu tượng. Hai miền càng gần nhau thì hiệu quả chuyển giao càng cao — vì thế, nếu có sẵn mô hình tiền huấn luyện trên miền gần hơn (như ảnh X-quang ngực cho bài toán y khoa), nó thường ưu thế hơn mô hình tổng quát từ ImageNet.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Cơ sở toán học của học chuyển giao liên hệ trực tiếp với thích ứng miền (&lt;em&gt;domain adaptation&lt;/em&gt;), học đa tác vụ (&lt;em&gt;multi-task learning&lt;/em&gt;) và học cách học (&lt;em&gt;meta-learning&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Giả sử ta có miền nguồn với phân phối \(p_S(\mathbf{x}, y)\) và tập dữ liệu gán nhãn lớn \(\mathcal{D}_S = \{(\mathbf{x}_i^S, y_i^S)\}_{i=1}^{N_S}\), cùng miền đích với phân phối \(p_T(\mathbf{x}, y)\) và tập dữ liệu gán nhãn nhỏ \(\mathcal{D}_T = \{(\mathbf{x}_j^T, y_j^T)\}_{j=1}^{N_T}\) sao cho \(N_T \ll N_S\). Mục tiêu là học bộ dự đoán \(f_\theta(\mathbf{x})\) đạt hiệu năng tốt trên miền đích.&lt;/p&gt;

&lt;p&gt;Nếu chỉ tối thiểu hóa rủi ro thực nghiệm trực tiếp trên dữ liệu đích:&lt;/p&gt;

\[\theta^* = \arg\min_\theta \frac{1}{N_T}\sum_{j=1}^{N_T} \mathcal{L}(f_\theta(\mathbf{x}_j^T), y_j^T)\]

&lt;p&gt;khi \(N_T\) nhỏ, mô hình rất dễ quá khớp và tổng quát hóa kém.&lt;/p&gt;

&lt;p&gt;Học chuyển giao chia quá trình tối ưu thành hai giai đoạn:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Giai đoạn 1 (Tiền huấn luyện):&lt;/strong&gt; tối ưu trên miền nguồn&lt;/p&gt;

\[\theta_S^* = \arg\min_\theta \frac{1}{N_S}\sum_{i=1}^{N_S} \mathcal{L}(f_\theta(\mathbf{x}_i^S), y_i^S)\]

&lt;p&gt;&lt;strong&gt;Giai đoạn 2 (Tinh chỉnh):&lt;/strong&gt; khởi tạo từ \(\theta_S^*\) rồi tối ưu trên miền đích&lt;/p&gt;

\[\theta_T^* = \arg\min_\theta \frac{1}{N_T}\sum_{j=1}^{N_T} \mathcal{L}(f_\theta(\mathbf{x}_j^T), y_j^T), \quad \text{bắt đầu từ } \theta_0 = \theta_S^*\]

&lt;p&gt;Điểm khởi tạo \(\theta_0 = \theta_S^*\) đặt quá trình tối ưu gần vùng nghiệm tốt hơn so với khởi tạo ngẫu nhiên, giúp hội tụ nhanh và ít quá khớp hơn khi dữ liệu đích hạn chế.&lt;/p&gt;

&lt;p&gt;Phân rã mô hình thành \(f_\theta = h_{\theta_h} \circ g_{\theta_g}\), trong đó \(g_{\theta_g}\) là phần trích xuất đặc trưng (các tầng sớm và giữa) và \(h_{\theta_h}\) là tầng đầu ra chuyên biệt cho tác vụ. Ba chiến lược chuyển giao phổ biến là:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trích xuất đặc trưng (&lt;em&gt;feature extraction&lt;/em&gt;):&lt;/strong&gt; giữ cố định (đóng băng) \(\theta_g = \theta_g^S\) và chỉ huấn luyện \(\theta_h\) trên dữ liệu đích:&lt;/p&gt;

\[\theta_h^* = \arg\min_{\theta_h} \frac{1}{N_T}\sum_{j=1}^{N_T} \mathcal{L}(h_{\theta_h}(g_{\theta_g^S}(\mathbf{x}_j^T)), y_j^T)\]

&lt;p&gt;&lt;strong&gt;Tinh chỉnh toàn bộ tầng (&lt;em&gt;full fine-tuning&lt;/em&gt;):&lt;/strong&gt; khởi tạo \((\theta_g^S, \theta_h^{\text{random}})\) và cập nhật đồng thời cả hai phần trên dữ liệu đích:&lt;/p&gt;

\[(\theta_g^*, \theta_h^*) = \arg\min_{\theta_g, \theta_h} \frac{1}{N_T}\sum_{j=1}^{N_T} \mathcal{L}(h_{\theta_h}(g_{\theta_g}(\mathbf{x}_j^T)), y_j^T)\]

&lt;p&gt;&lt;strong&gt;Learning rate phân biệt theo tầng (&lt;em&gt;discriminative learning rates&lt;/em&gt;):&lt;/strong&gt; áp dụng mức learning rate khác nhau cho từng nhóm tầng:&lt;/p&gt;

\[\theta_g \leftarrow \theta_g - \eta_g \nabla_{\theta_g} \mathcal{L}, \quad \theta_h \leftarrow \theta_h - \eta_h \nabla_{\theta_h} \mathcal{L}\]

&lt;p&gt;thường chọn \(\eta_g &amp;lt; \eta_h\) để cập nhật nhẹ các tầng tiền huấn luyện và cập nhật nhanh hơn cho tầng đầu ra mới.&lt;/p&gt;

&lt;p&gt;Lựa chọn chiến lược phụ thuộc vào cỡ mẫu đích và mức độ tương đồng giữa hai miền. Với dữ liệu đích rất nhỏ (vài trăm mẫu) và miền tương đồng, trích xuất đặc trưng giúp hạn chế quá khớp; với dữ liệu cỡ trung bình (vài nghìn mẫu), tinh chỉnh với learning rate nhỏ giúp đặc trưng thích nghi tốt hơn mà tránh hiện tượng quên thảm họa (&lt;em&gt;catastrophic forgetting&lt;/em&gt;); còn khi dữ liệu đích rất lớn (hàng chục nghìn mẫu trở lên), tinh chỉnh toàn mạng hoặc thậm chí huấn luyện từ đầu đều là phương án khả thi.&lt;/p&gt;

&lt;h3 id=&quot;lý-thuyết-thích-ứng-miền&quot;&gt;Lý thuyết thích ứng miền&lt;/h3&gt;

&lt;p&gt;Trong lý thuyết thích ứng miền, với không gian giả thuyết \(\mathcal{H}\), sai số trên miền đích của một giả thuyết \(h \in \mathcal{H}\) được chặn trên bởi:&lt;/p&gt;

\[\epsilon_T(h) \leq \epsilon_S(h) + \frac{1}{2}d_{\mathcal{H}}(D_S, D_T) + \lambda\]

&lt;p&gt;trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\epsilon_S(h)\) là sai số trên miền nguồn (có thể làm nhỏ nhờ tập nguồn lớn).&lt;/li&gt;
  &lt;li&gt;\(d_{\mathcal{H}}(D_S, D_T)\) là khoảng cách phân phối giữa miền nguồn và miền đích (đo mức độ lệch miền).&lt;/li&gt;
  &lt;li&gt;\(\lambda\) là sai số của giả thuyết chung tối ưu trên cả hai miền.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cận trên này cho thấy ba điều kiện để chuyển giao hiệu quả: sai số trên miền nguồn thấp, độ lệch giữa hai miền nhỏ và tồn tại một giả thuyết hoạt động tốt trên cả hai miền. Khi \(d_{\mathcal{H}}\) lớn do hai miền quá khác biệt, cận trên trở nên lỏng và học chuyển giao không còn đảm bảo mang lại lợi ích.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;p&gt;Xét bài toán phân loại 20 loài chim với chỉ 500 ảnh gán nhãn (25 ảnh mỗi loài). Huấn luyện một mạng ResNet-50 (khoảng 25 triệu tham số) từ đầu trên 500 ảnh chắc chắn sẽ quá khớp nghiêm trọng.&lt;/p&gt;

&lt;p&gt;Thay vào đó, ta xuất phát từ ResNet-50 tiền huấn luyện trên ImageNet (1,2 triệu ảnh, 1000 lớp), vốn đã học sẵn hệ thống đặc trưng phân cấp:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tầng 1:&lt;/strong&gt; bộ lọc phát hiện cạnh (ngang, dọc, chéo, cong).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng 2:&lt;/strong&gt; kết cấu bề mặt (lông, mỏ, nền).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng 3:&lt;/strong&gt; bộ phận đối tượng (cánh, đầu, chân).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng 4:&lt;/strong&gt; cấu trúc đối tượng tổng thể (chim và các lớp ImageNet).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ta có hai phương án chính:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương án 1 — Trích xuất đặc trưng:&lt;/strong&gt; bỏ tầng phân loại 1000 lớp cuối, đóng băng toàn bộ các tầng tích chập, gắn tầng phân loại 20 lớp mới và chỉ huấn luyện tầng mới này trên 500 ảnh. Mỗi ảnh được biểu diễn bằng vector đặc trưng 2048 chiều đã học sẵn, giúp bài toán quy về học ánh xạ phân loại đơn giản cần ít dữ liệu hơn nhiều.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương án 2 — Tinh chỉnh:&lt;/strong&gt; thay tầng cuối bằng đầu 20 lớp khởi tạo ngẫu nhiên và huấn luyện toàn bộ mạng với learning rate nhỏ (ví dụ 0,0001 thay vì 0,1 như khi huấn luyện từ đầu). Bước học nhỏ giúp các tầng sớm hầu như giữ nguyên đặc trưng cạnh tổng quát, trong khi các tầng giữa và tầng sâu điều chỉnh dần để bám sát đặc trưng của 20 loài chim.&lt;/p&gt;

&lt;p&gt;Minh họa một bước cập nhật trọng số cụ thể ở tầng 3:&lt;/p&gt;

&lt;p&gt;Trọng số tiền huấn luyện: \(w_{\text{pre}} = 0.523\)&lt;br /&gt;
Gradient trên dữ liệu chim: \(\nabla w = 0.015\)&lt;br /&gt;
Trọng số sau cập nhật: \(w_{\text{fine}} = 0.523 - 0.0001 \times 0.015 = 0.5229985\)&lt;/p&gt;

&lt;p&gt;Những điều chỉnh rất nhỏ nhưng đồng loạt trên hàng nghìn trọng số giúp mạng chuyên biệt hóa dần cho bài toán mới mà không phá vỡ cấu trúc đặc trưng đã học từ ImageNet. Trong kịch bản minh họa 500 ảnh này, trích xuất đặc trưng có thể đạt quanh 85% độ chính xác và tinh chỉnh đạt quanh 92%, vượt xa mức khoảng 60% khi huấn luyện từ đầu.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, tiếng Anh. Giải thích trực tiếp câu hỏi trọng tâm của bài: nên đóng băng những tầng nào và tinh chỉnh những tầng nào.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, tiếng Anh. Làm rõ vì sao đặc trưng ở các tầng tích chập sớm dễ chuyển giao hơn các tầng sâu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa trực quan phân cấp đặc trưng trong CNN để xác định điểm cắt khi chuyển giao.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15 Học Chuyển giao</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter15/15_00_Introduction</id>
   <content type="html">&lt;p&gt;Một nghệ sĩ dương cầm lão luyện khi chuyển sang học đàn organ sẽ không bắt đầu lại từ bài tập đọc khóa Sol hay tập gõ nhịp cơ bản — đôi tay và đôi tai âm nhạc của họ đã mang sẵn hàng nghìn giờ tri thức chuyển giao. Trong học sâu cũng vậy: thay vì huấn luyện một mạng ResNet hay Transformer từ con số 0 trên 500 bức ảnh y khoa (vốn chắc chắn sẽ quá khớp), &lt;strong&gt;Học Chuyển giao (Transfer Learning)&lt;/strong&gt; cho phép ta kế thừa toàn bộ bộ lọc đặc trưng đã tôi luyện trên hàng triệu mẫu dữ liệu nguồn rồi tinh chỉnh nhẹ nhàng cho bài toán đích.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-học-chuyển-giao&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Học Chuyển giao&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân cấp biểu diễn (Hierarchical Features):&lt;/strong&gt; Các tầng đầu của mạng sâu học đặc trưng phổ quát (cạnh, góc, kết cấu, âm vị, cú pháp), còn các tầng cuối chuyên biệt hóa cho nhãn của tác vụ nguồn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hai chiến lược cốt lõi — Trích xuất đặc trưng (Linear Probing) vs. Tinh chỉnh (Fine-Tuning):&lt;/strong&gt; Quyết định đóng băng toàn bộ xương sống hay mở khóa từng khối với tốc độ học phân tầng tùy thuộc kích thước dữ liệu đích và độ tương đồng miền.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng cách miền (Domain Shift) và chuyển giao âm (Negative Transfer):&lt;/strong&gt; Nhận diện khi nào phân phối nguồn và đích lệch nhau quá xa khiến trọng số tiền huấn luyện phản tác dụng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tinh chỉnh hiệu quả tham số (PEFT / LoRA / QLoRA):&lt;/strong&gt; Bước tiến hiện đại cho phép thích ứng mô hình hàng chục tỷ tham số chỉ bằng cách cập nhật chưa tới \(1\%\) ma trận hạng thấp.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-số-tham-số-cần-học-huấn-luyện-từ-đầu-vs-linear-probe-vs-fine-tune-khối-cuối&quot;&gt;Giải thích: So sánh số tham số cần học: Huấn luyện từ đầu vs. Linear Probe vs. Fine-Tune khối cuối&lt;/h3&gt;

&lt;p&gt;Giả sử bạn có bài toán phân loại \(5\) loại bệnh lá cây với chỉ \(N = 400\) ảnh huấn luyện, sử dụng xương sống ResNet-18 (\(11{,}18\text{ triệu}\) tham số, đặc trưng cuối \(512\) chiều).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Huấn luyện từ đầu / Fine-tune toàn bộ:&lt;/strong&gt; Cần tối ưu \(11{,}18\text{ triệu}\) tham số trên \(400\) ảnh — tỷ lệ xấp xỉ \(27{,}950\text{ tham số/ảnh}\), nguy cơ ghi nhớ (overfitting) cực lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đóng băng xương sống (Linear Probing):&lt;/strong&gt; Chỉ thay tầng phân loại &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(512, 5)&lt;/code&gt;.
    &lt;ul&gt;
      &lt;li&gt;Số tham số huấn luyện: \(512 \times 5 + 5 = 2{,}565\) tham số (giảm &lt;strong&gt;4.358 lần&lt;/strong&gt;, tương đương \(6{,}4\text{ tham số/ảnh}\)!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mở khóa thêm khối tích chập cuối (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;layer4&lt;/code&gt;, khoảng \(8{,}39\text{ triệu}\) tham số) nhưng dùng learning rate nhỏ (\(10^{-4}\) so với \(10^{-3}\) ở đầu phân loại):&lt;/strong&gt; Phù hợp khi bạn có vài nghìn ảnh trở lên và muốn điều chỉnh các đặc trưng mức cao sát với kết cấu lá cây.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Học chuyển giao (&lt;em&gt;transfer learning&lt;/em&gt;) tận dụng tri thức từ các mô hình đã tiền huấn luyện để giải quyết bài toán mới khi dữ liệu có nhãn còn hạn chế. Thay vì huấn luyện từ đầu, ta tinh chỉnh (&lt;em&gt;fine-tune&lt;/em&gt;) các mô hình sẵn có hoặc sử dụng chúng làm bộ trích xuất đặc trưng. Chương này trình bày các chiến lược trích xuất đặc trưng, tinh chỉnh, thích ứng miền (&lt;em&gt;domain adaptation&lt;/em&gt;) và thực hành học chuyển giao với những mô hình phổ biến như ResNet, BERT và GPT.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần trích xuất đặc trưng và tinh chỉnh, xem &lt;strong&gt;15-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về LoRA, QLoRA và các adapter tiết kiệm tham số (PEFT) trên mô hình nền tảng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (luyện phỏng vấn):&lt;/strong&gt; Sau phần lý thuyết học chuyển giao, xem &lt;strong&gt;15-98 Luyện phỏng vấn&lt;/strong&gt; với các câu hỏi tự soạn về trích xuất đặc trưng và lệch miền; bộ câu hỏi kèm lời giải đầy đủ nằm trong &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, tiếng Anh. Giới thiệu trực quan quá trình tinh chỉnh một mạng đã tiền huấn luyện — nội dung trọng tâm của chương này.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qaDe0qQZ5AQ&quot;&gt;Pytorch Transfer Learning and Fine Tuning Tutorial&lt;/a&gt; — Aladdin Persson, tiếng Anh. Hướng dẫn cài đặt học chuyển giao và tinh chỉnh bằng PyTorch, sát với bài thực hành của chương.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, tiếng Anh. Ôn lại cấu trúc mạng tích chập thường được dùng làm mô hình nền cho học chuyển giao.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>14-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter14/14_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter14/14_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Liệu mô hình khuếch tán đã “khai tử” hoàn toàn GAN? Nếu bạn mở mã nguồn của Stable Diffusion XL Turbo, SDXL-Lightning hay hệ thống nén ảnh/video thế hệ mới, bạn sẽ ngạc nhiên khi thấy &lt;strong&gt;bộ phân biệt đối kháng (Discriminator)&lt;/strong&gt; vẫn đang âm thầm làm việc ở tuyến đầu! Bài cập nhật này giải thích sự chuyển mình của GAN giai đoạn 2022–2026: từ vị trí bộ sinh độc lập sang “vũ khí bí mật” cho tổng hợp khuôn mặt thời gian thực, GAN Inversion và chưng cất mô hình khuếch tán một bước.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-mặt-trận-hiện-đại-nơi-tư-duy-gan-vẫn-tỏa-sáng&quot;&gt;Kiến thức cần nhớ: Ba mặt trận hiện đại nơi tư duy GAN vẫn tỏa sáng&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;StyleGAN3 và bất biến dịch chuyển/xoay:&lt;/strong&gt; Loại bỏ hiện tượng “dính kết cấu” (texture sticking) bằng xử lý tín hiệu chống răng cưa, phục vụ chỉnh sửa khuôn mặt và nhân vật ảo thời gian thực.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GAN Inversion và chỉnh sửa ngữ nghĩa trong không gian \(\mathcal{W}+\):&lt;/strong&gt; Tìm ngược mã ẩn \(\mathbf{w}^*\) tái tạo chính xác một bức ảnh thật rồi trượt theo các hướng thuộc tính (tuổi tác, ánh sáng, biểu cảm).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GigaGAN và bộ sinh quy mô tỷ tham số:&lt;/strong&gt; Chứng minh GAN có thể mở rộng lên sinh ảnh từ văn bản với tốc độ dưới 0,2 giây/ảnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chưng cất đối kháng (ADD / DMD / SDXL-Turbo):&lt;/strong&gt; Dùng bộ phân biệt đối kháng ép mô hình khuếch tán sinh ảnh sắc nét chỉ trong &lt;strong&gt;1 đến 4 bước&lt;/strong&gt; thay vì 50 bước.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-độ-trễ-suy-luận-diffusion-50-bước-vs-diffusion-chưng-cất-gan-14-bước&quot;&gt;Giải thích: So sánh độ trễ suy luận: Diffusion 50 bước vs. Diffusion chưng cất GAN 1–4 bước&lt;/h3&gt;

&lt;p&gt;Giả sử một lượt suy luận mạng UNet/DiT trên ảnh \(1024 \times 1024\) tốn \(45\text{ ms}\) trên một GPU tầm trung, và bước giải mã VAE cuối cùng tốn \(25\text{ ms}\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Diffusion chuẩn (50 bước, có Classifier-Free Guidance chạy 2 nhánh/bước):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Thời gian khử nhiễu: \(50 \times 2 \times 45\text{ ms} = 4{,}500\text{ ms}\).&lt;/li&gt;
      &lt;li&gt;Tổng thời gian sinh 1 ảnh: \(4{,}500 + 25 = 4{,}525\text{ ms} \approx 4{,}53\text{ giây}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình chưng cất đối kháng (kiểu Adversarial Diffusion Distillation — 2 bước, không cần CFG):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Thời gian khử nhiễu: \(2 \times 45\text{ ms} = 90\text{ ms}\).&lt;/li&gt;
      &lt;li&gt;Tổng thời gian sinh 1 ảnh: \(90 + 25 = 115\text{ ms} \approx 0{,}115\text{ giây}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu quả tăng tốc:&lt;/strong&gt; \(4{,}525 / 115 \approx 39{,}3\times\) — biến trải nghiệm tạo ảnh từ “chờ gần 5 giây” thành &lt;strong&gt;tương tác tức thời theo từng nét vẽ&lt;/strong&gt;, nhờ chính hàm loss đối kháng của GAN đảm bảo độ sắc nét ngay ở bước 1–2!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-gan-sau-làn-sóng-khuếch-tán--khuôn-mặt-inversion-và-bộ-sinh-một-bước&quot;&gt;Tùy chọn: GAN sau làn sóng khuếch tán — Khuôn mặt, Inversion và Bộ sinh một bước&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần hàm mất mát GAN, lý thuyết DCGAN/StyleGAN hay các lưu ý huấn luyện trong chương. Nội dung tổng hợp những vai trò mà GAN vẫn đảm nhiệm tốt sau khi mô hình khuếch tán trở thành bộ lấy mẫu mặc định.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Công thức đối kháng cốt lõi:&lt;/p&gt;

\[\min_G \max_D \mathbb{E}_{x}[\log D(x)] + \mathbb{E}_{z}[\log(1-D(G(z)))]\]

&lt;p&gt;không thay đổi; điều thay đổi là phạm vi ứng dụng. Sinh ảnh từ văn bản mở hiện chủ yếu dựa trên khuếch tán và flow matching, còn &lt;strong&gt;GAN vẫn giữ ưu thế&lt;/strong&gt; khi cần sinh ảnh tức thì trong một bước, thực hiện ánh xạ ngược (&lt;em&gt;inversion&lt;/em&gt;) hoặc khai thác không gian khuôn mặt đã được nghiên cứu sâu.&lt;/p&gt;

&lt;h2 id=&quot;1-stylegan3-và-các-hệ-thống-tổng-hợp-khuôn-mặt-giai-đoạn-20222023&quot;&gt;1. StyleGAN3 và các hệ thống tổng hợp khuôn mặt giai đoạn 2022–2023&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2106.12423&quot;&gt;Karras et al., 2021&lt;/a&gt; (StyleGAN3, ứng dụng rộng rãi giai đoạn 2022–2024) khắc phục hiện tượng kết cấu bị dính vào tọa độ ảnh (&lt;em&gt;texture sticking&lt;/em&gt;) nhờ phép tích chập chống răng cưa (&lt;em&gt;alias-free&lt;/em&gt;). Trong thực tế công nghiệp, StyleGAN2/3 vẫn được dùng cho các tác vụ chỉnh sửa khuôn mặt, thay đổi tuổi tác và bảo toàn danh tính vì không gian ẩn &lt;strong&gt;W / W+&lt;/strong&gt; hỗ trợ ánh xạ ngược và điều chỉnh thuộc tính nhanh, ổn định hơn so với inversion trên mô hình khuếch tán.&lt;/p&gt;

&lt;h2 id=&quot;2-một-số-ứng-dụng-tiêu-biểu&quot;&gt;2. Một số ứng dụng tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;gigagan-và-gan-sinh-ảnh-từ-văn-bản-quy-mô-lớn&quot;&gt;GigaGAN và GAN sinh ảnh từ văn bản quy mô lớn&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.05511&quot;&gt;Kang et al., 2023&lt;/a&gt; (GigaGAN) chứng minh GAN vẫn có thể đạt chất lượng sinh ảnh từ văn bản tiệm cận mô hình khuếch tán chỉ với &lt;strong&gt;một lượt truyền xuôi&lt;/strong&gt;. Kết quả này cho thấy huấn luyện đối kháng vẫn có tiềm năng mở rộng quy mô, dù phần lớn hệ thống mã nguồn mở ưu tiên khuếch tán nhờ tính ổn định cao hơn.&lt;/p&gt;

&lt;h3 id=&quot;chưng-cất-mô-hình-gan-làm-thành-phần-huấn-luyện-cho-mô-hình-khuếch-tán-một-bước&quot;&gt;Chưng cất mô hình: GAN làm thành phần huấn luyện cho mô hình khuếch tán một bước&lt;/h3&gt;

&lt;p&gt;Nhiều bộ sinh một bước hoặc vài bước (như SD-Turbo, các phương pháp chưng cất kết hợp LCM-LoRA, họ UFOGen) bổ sung đầu &lt;strong&gt;đối kháng&lt;/strong&gt; giúp mô hình học sinh nhỏ khớp tốt với mô hình giáo viên khuếch tán nhiều bước. Ở đây, bộ phân biệt của Chương 14 đóng vai trò công cụ &lt;em&gt;chưng cất&lt;/em&gt;, không phải mô hình sinh độc lập.&lt;/p&gt;

&lt;h3 id=&quot;khi-nào-nên-chọn-gan-trong-giai-đoạn-hiện-nay&quot;&gt;Khi nào nên chọn GAN trong giai đoạn hiện nay&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Ứng dụng cần tốc độ thời gian thực như avatar, &lt;em&gt;talking-head&lt;/em&gt; hoặc đồ họa game (&lt;em&gt;sprite&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Bổ sung dữ liệu cân bằng lớp trên miền hẹp đã có sẵn mô hình StyleGAN phù hợp.&lt;/li&gt;
  &lt;li&gt;Không phải lựa chọn ưu tiên cho bài toán sinh ảnh từ văn bản tự do nhiều khái niệm mở.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;3-thư-viện-và-mã-nguồn-phổ-biến&quot;&gt;3. Thư viện và mã nguồn phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/NVlabs/stylegan3&quot;&gt;NVlabs/stylegan3&lt;/a&gt; và StyleGAN2-ADA.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/mingukkang/GigaGAN&quot;&gt;mingukkang/GigaGAN&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/diffusers&quot;&gt;diffusers&lt;/a&gt; — cung cấp một số checkpoint turbo sử dụng chưng cất đối kháng.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-tài-liệu-tham-khảo-20222026&quot;&gt;4. Tài liệu tham khảo (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2106.12423&quot;&gt;StyleGAN3 (Karras et al., 2021)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.05511&quot;&gt;GigaGAN (Kang et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2311.17042&quot;&gt;Adversarial Diffusion Distillation (Sauer et al., 2023)&lt;/a&gt; — nền tảng của SD-Turbo.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-phần-bổ-sung-so-với-nội-dung-cốt-lõi&quot;&gt;5. Phần bổ sung so với nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên tự huấn luyện mô hình GAN cơ bản và nắm rõ hiện tượng sụp đổ mode trước. Bài này chỉ giải thích vì sao StyleGAN và huấn luyện đối kháng vẫn tiếp tục hiện diện trong thực tế sản xuất ngay cả khi các hệ thống sinh ảnh tổng quát đã chuyển sang khuếch tán.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=4LNO8nLxF4Y&quot;&gt;AI generated faces - StyleGAN explained!&lt;/a&gt; — AI Bites, tiếng Anh. Giải thích kiến trúc StyleGAN tương ứng với phần ứng dụng tổng hợp khuôn mặt trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, tiếng Anh. Ôn lại cơ chế trò chơi hai người mà StyleGAN vẫn kế thừa.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TpMIssRdhco&quot;&gt;What are GANs (Generative Adversarial Networks)?&lt;/a&gt; — IBM Technology, tiếng Anh. Tóm tắt nhanh giúp đối chiếu điểm khác biệt giữa không gian phong cách của StyleGAN và GAN chuẩn.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>14-01 Mạng Sinh Đối kháng</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter14/14_01_GAN_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter14/14_01_GAN_Fundamentals</id>
   <content type="html">&lt;p&gt;Giữa ba đại gia mô hình sinh cổ điển — Autoregressive, VAE và GAN — GAN luôn là cái tên gây ấn tượng thị giác mạnh nhất ngay từ cái nhìn đầu tiên nhờ độ sắc nét vượt trội. Trang nền tảng này kết nối lý thuyết đối kháng (&lt;strong&gt;14-01-01&lt;/strong&gt;) với thực hành cài đặt PyTorch (&lt;strong&gt;14-01-02&lt;/strong&gt;), giúp bạn nắm chắc khi nào nên dùng GAN và cách đọc vị đường cong loss đầy biến động của nó.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-khung-tư-duy-cốt-lõi-về-mạng-sinh-đối-kháng&quot;&gt;Kiến thức cần nhớ: Khung tư duy cốt lõi về Mạng Sinh Đối kháng&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tư duy học hàm mất mát thay vì cố định hàm mất mát:&lt;/strong&gt; Bộ phân biệt \(D\) thực chất đóng vai trò một &lt;em&gt;hàm mất mát học được&lt;/em&gt; tự thích nghi theo từng lỗi tinh vi nhất của ảnh sinh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhịp độ cân bằng giữa \(G\) và \(D\):&lt;/strong&gt; Hiểu vì sao loss của \(D\) và \(G\) không giảm đơn điệu về 0 mà dao động quanh ngưỡng cân bằng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các biến thể nền tảng:&lt;/strong&gt; Từ Vanilla GAN, DCGAN (tích chập), Conditional GAN (sinh theo nhãn lớp) đến WGAN-GP (ổn định hình học).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tiêu chuẩn chẩn đoán trực quan:&lt;/strong&gt; Luôn theo dõi lưới ảnh từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fixed_noise&lt;/code&gt; song song với đường cong loss để phát hiện sớm hiện tượng sụp đổ mode.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-đọc-vị-3-kịch-bản-đường-cong-loss-của-d-và-g-khi-huấn-luyện-gan&quot;&gt;Giải thích: Đọc vị 3 kịch bản đường cong loss của \(D\) và \(G\) khi huấn luyện GAN&lt;/h3&gt;

&lt;p&gt;Nhớ rằng tại điểm cân bằng lý tưởng \(D(x) = D(G(z)) = 0{,}5\), ta có:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathcal{L}_D = -\ln(0{,}5) - \ln(0{,}5) = 2\ln 2 \approx 1{,}386\) (hoặc \(0{,}693\) nếu lấy trung bình hai phần).&lt;/li&gt;
  &lt;li&gt;\(\mathcal{L}_G = -\ln(0{,}5) = \ln 2 \approx 0{,}693\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Đối chiếu 3 dấu hiệu chẩn đoán thực tế trên bảng log:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;\(\mathcal{L}_D \to 0{,}01\), \(\mathcal{L}_G \to 5{,}0\):&lt;/strong&gt; Bộ phân biệt thắng áp đảo, gradient của \(G\) bị bão hòa — cần giảm learning rate của \(D\), thêm label smoothing hoặc kiểm tra lại chuẩn hóa dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;\(\mathcal{L}_D \approx 1{,}38\), \(\mathcal{L}_G \approx 0{,}70\) nhưng lưới ảnh lặp đúng 1 chữ số:&lt;/strong&gt; Dấu hiệu &lt;em&gt;mode collapse&lt;/em&gt; ẩn — \(G\) đang lừa được \(D\) bằng một mẫu an toàn duy nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;\(\mathcal{L}_D\) dao động quanh \(1{,}0\text{–}1{,}4\), \(\mathcal{L}_G\) quanh \(0{,}7\text{–}1{,}2\) và ảnh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fixed_noise&lt;/code&gt; sắc nét dần qua từng epoch:&lt;/strong&gt; Quá trình huấn luyện lành mạnh!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nội dung về Mạng Sinh Đối kháng gồm hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết&lt;/strong&gt; — công thức trò chơi minimax, cân bằng tối ưu và trực giác đối kháng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt&lt;/strong&gt; — vòng lặp huấn luyện PyTorch, các bài báo nền tảng và cạm bẫy thường gặp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, tiếng Anh. Tổng quan ngắn gọn trước khi đi vào phần lý thuyết và mã cài đặt.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Gib_kiXgnvA&quot;&gt;The Math Behind Generative Adversarial Networks Clearly Explained!&lt;/a&gt; — Normalized Nerd, tiếng Anh. Trình bày hàm giá trị minimax xuyên suốt cả hai bài học.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, tiếng Anh. Phần GAN trong bài giảng CS231n, bao gồm các chế độ thất bại thường gặp.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>14-01-02 Cài đặt GAN</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter14/14_01_02_GAN_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter14/14_01_02_GAN_Implementation</id>
   <content type="html">&lt;p&gt;Viết một mạng GAN trong PyTorch giống như điều khiển một chiếc xe đua không có phanh ABS: chỉ cần quên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.detach()&lt;/code&gt; ở một dòng hay chọn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;beta1=0.9&lt;/code&gt; mặc định của Adam thay vì &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.5&lt;/code&gt;, toàn bộ quá trình huấn luyện có thể vỡ vụn sau vài epoch. Bài thực hành này trình bày đầy đủ mã nguồn DCGAN/MLP-GAN trên MNIST kèm từng chi tiết kỹ thuật quan trọng giúp vòng lặp đối kháng vận hành trơn tru.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-kỹ-thuật-lập-trình-gan-ổn-định-trong-pytorch&quot;&gt;Kiến thức cần nhớ: Kỹ thuật lập trình GAN ổn định trong PyTorch&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa đầu vào về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[-1, 1]&lt;/code&gt; khớp với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tanh&lt;/code&gt;:&lt;/strong&gt; Đảm bảo thang giá trị của ảnh thật và đầu ra Generator đồng nhất để Discriminator không gian lận bằng cách phát hiện lệch biên độ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tách đồ thị gradient đúng cách (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.detach()&lt;/code&gt;):&lt;/strong&gt; Khi cập nhật Discriminator, bắt buộc tách &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fake_imgs.detach()&lt;/code&gt; để tiết kiệm bộ nhớ và tránh truyền nhầm gradient ngược vào Generator.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thủ thuật huấn luyện thực chiến (GAN Hacks):&lt;/strong&gt; Dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LeakyReLU(0.2)&lt;/code&gt; trong \(D\) để tránh chết nơ-ron, giảm momentum &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;betas=(0.5, 0.999)&lt;/code&gt; trong Adam, và áp dụng &lt;em&gt;one-sided label smoothing&lt;/em&gt; (nhãn thật \(0{,}9\) thay vì \(1{,}0\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giám sát huấn luyện bằng vector nhiễu cố định (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fixed_noise&lt;/code&gt;):&lt;/strong&gt; Lưu cố định một batch \(\mathbf{z}_{\text{fixed}}\) qua mọi epoch để quan sát trực tiếp sự tiến hóa của cùng các ảnh sinh theo thời gian.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-cập-nhật-discriminator-với-one-sided-label-smoothing&quot;&gt;Giải thích: Tính tay một bước cập nhật Discriminator với One-Sided Label Smoothing&lt;/h3&gt;

&lt;p&gt;Giả sử trên một mẫu thật \(x\) và một mẫu giả \(\tilde{x} = G(z)\), bộ phân biệt dự đoán xác suất \(D(x) = 0{,}95\) và \(D(\tilde{x}) = 0{,}20\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Không dùng label smoothing (nhãn thật \(y_{\text{real}} = 1{,}0\), nhãn giả \(y_{\text{fake}} = 0{,}0\)):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(\mathcal{L}_{\text{real}} = -\ln(0{,}95) \approx 0{,}0513\).&lt;/li&gt;
      &lt;li&gt;\(\mathcal{L}_{\text{fake}} = -\ln(1 - 0{,}20) = -\ln(0{,}80) \approx 0{,}2231\).&lt;/li&gt;
      &lt;li&gt;Gradient theo logit mẫu thật: \(D(x) - 1{,}0 = -0{,}05\) (vẫn tiếp tục đẩy \(D(x) \to 1{,}0\) làm \(D\) quá tự tin).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Có One-Sided Label Smoothing (nhãn thật \(y_{\text{real}} = 0{,}9\), nhãn giả giữ nguyên \(0{,}0\)):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Gradient theo logit mẫu thật: \(D(x) - 0{,}9 = 0{,}95 - 0{,}90 = +0{,}05\)!&lt;/li&gt;
      &lt;li&gt;Dấu dương này &lt;strong&gt;kéo nhẹ \(D(x)\) lùi từ \(0{,}95\) về quanh \(0{,}90\)&lt;/strong&gt;, ngăn bộ phân biệt rơi vào trạng thái bão hòa quá tự tin (\(D(x) \to 1\)) — nhờ đó giữ cho gradient chảy về Generator luôn khỏe mạnh.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-đoạn-mã&quot;&gt;4. Đoạn mã&lt;/h2&gt;

&lt;p&gt;Phần mã dưới đây cài đặt một mô hình GAN tích chập đơn giản (theo phong cách DCGAN) bằng PyTorch trên tập dữ liệu MNIST để minh họa vòng lặp huấn luyện luân phiên giữa bộ phân biệt và bộ sinh:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision.utils&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;make_grid&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Generator: ánh xạ nhiễu ngẫu nhiên sang dữ liệu giả.
    
    Kiến trúc theo mẫu phổ biến cho sinh ảnh:
    - Bắt đầu với độ phân giải không gian thấp nhưng nhiều kênh
    - Upsample dần về không gian trong khi giảm kênh
    - Tầng cuối xuất ảnh với kích thước đúng
    
    Với MNIST: nhiễu (100) → (256×7×7) → (128×14×14) → (1×28×28)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Chiếu và reshape nhiễu
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Tầng linear: 100 → 256*7*7, rồi reshape thành (256, 7, 7)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Upsample qua transposed convolution
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deconv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# 256×7×7 → 128×14×14
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ConvTranspose2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Ổn định huấn luyện
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# 128×14×14 → 1×28×28
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ConvTranspose2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Đầu ra trong [-1, 1] (ta sẽ chuẩn hóa dữ liệu thật để khớp)
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        z: (batch, latent_dim) nhiễu ngẫu nhiên
        Returns: (batch, 1, 28, 28) ảnh sinh
        
        Forward pass biến đổi nhiễu không cấu trúc thành ảnh có cấu trúc
        qua các phép biến đổi đã học. Sớm trong huấn luyện, đầu ra
        là nhiễu. Khi huấn luyện tiến triển, cấu trúc giống chữ số nổi lên.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reshape thành feature map
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;deconv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Discriminator: phân biệt thật với giả.
    
    Kiến trúc phản chiếu generator ngược lại:
    - Đầu vào: ảnh (1×28×28)
    - Tầng conv downsample dần trong khi tăng kênh
    - Cuối: đầu ra vô hướng (xác suất ảnh là thật)
    
    Dùng LeakyReLU thay vì ReLU để ngăn đơn vị chết, và không pooling
    (dùng stride để downsample) theo thực hành tốt nhất DCGAN.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# 1×28×28 → 64×14×14
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LeakyReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Độ dốc âm 0.2
&lt;/span&gt;            
            &lt;span class=&quot;c1&quot;&gt;# 64×14×14 → 128×7×7
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LeakyReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Flatten: 128×7×7 → 6272
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Phân loại cuối
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Xác suất là thật
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (batch, 1, 28, 28) ảnh
        Returns: (batch, 1) xác suất là thật
        
        Discriminator học đặc trưng phân cấp để phát hiện:
        - Tầng sớm: cạnh, texture (phân biệt texture giả với thật)
        - Tầng giữa: hình dạng, mẫu (phát hiện chữ số sai giải phẫu)  
        - Tầng muộn: đặc trưng tổng thể (nhận diện khác biệt thống kê tinh tế)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện GAN
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện Mạng Sinh Đối kháng trên MNIST&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Siêu tham số
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0002&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Adam beta1 (thấp hơn mặc định 0.9 cho ổn định GAN)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tải dữ liệu (chuẩn hóa về [-1, 1] để khớp tanh của generator)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Compose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ToTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normalize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Chuẩn hóa về [-1, 1]
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                          &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;drop_last&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Khởi tạo mạng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;generator&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;discriminator&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Optimizer (cả hai dùng Adam với β1=0.5 cho ổn định)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer_G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;betas&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer_D&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;betas&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Hàm mất mát (binary cross-entropy)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BCELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Nhãn cho thật và giả (dùng trong tính loss)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;real_label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;fake_label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tham số Generator: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tham số Discriminator: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; epoch...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Điều này minh họa động lực huấn luyện đối kháng:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vòng huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G_losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;D_losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;real_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;real_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# ==================== Huấn luyện Discriminator ====================
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Discriminator muốn tối đa hóa: log D(x) + log(1 - D(G(z)))
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Tương đương, tối thiểu hóa: -log D(x) - log(1 - D(G(z)))
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Huấn luyện trên dữ liệu thật: tối đa hóa log D(x)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Loss: -log D(x) (đảo dấu vì ta tối thiểu hóa)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;labels_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;full&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;real_label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;real_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_D_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Huấn luyện trên dữ liệu giả: tối đa hóa log(1 - D(G(z)))
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Loss: -log(1 - D(G(z)))
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;fake_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;full&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fake_label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Detach! Không backprop qua G
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss_D_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tổng loss discriminator
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss_D&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss_D_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss_D_fake&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# ==================== Huấn luyện Generator ====================
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Generator muốn tối thiểu hóa: -log D(G(z))
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Tương đương, tối đa hóa: log D(G(z)) (mục tiêu non-saturating)
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Sinh giả lại (không detach lần này — ta cần gradient qua G!)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;fake_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output_fake_for_G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Generator cố khiến discriminator xuất 1 (thật) cho giả của nó
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;labels_real_for_G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;full&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;real_label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_fake_for_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_real_for_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;loss_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Theo dõi loss
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Một lần mỗi epoch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;G_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;D_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# In tiến độ
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;if &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch [&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;]  &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;D_loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;G_loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;D(x): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;D(G(z)): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện Hoàn tất! Phân tích Kết quả&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh mẫu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Sinh 64 mẫu
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;z_sample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;fake_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đã sinh &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; chữ số MNIST giả&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape mẫu: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (64, 1, 28, 28)
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Kiểm tra ý kiến của discriminator về mẫu sinh
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Điểm discriminator cho mẫu sinh:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (lý tưởng ~0.5)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Std:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Nếu mean gần 0.5, generator đánh lừa thành công discriminator
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ✓ Generator đánh lừa thành công discriminator!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ✗ Discriminator vẫn dễ dàng phát hiện giả&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ~ Generator khá thuyết phục&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Minh họa nội suy không gian ẩn
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nội suy Không gian Ẩn trong GAN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Hai mã ẩn ngẫu nhiên
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Nội suy
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sinh &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; ảnh bằng cách nội suy mã ẩn:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Bước &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (t=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;): Shape ảnh sinh &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nội suy nên cho thấy biến hình mượt giữa các chữ số khác nhau.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Chất lượng nội suy chỉ ra cấu trúc không gian ẩn.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hiểu biết về Huấn luyện GAN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Quan sát then chốt từ huấn luyện:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Động lực đối kháng tạo chương trình học tự nhiên&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Cân bằng giữa D và G then chốt (không bên nào nên thống trị)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;3. Giá trị loss không chỉ ra trực tiếp chất lượng (kiểm tra mẫu!)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;4. Sụp đổ mode là nguy cơ liên tục (theo dõi đa dạng)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;5. Mẫu sinh có thể thực tế dù cân bằng không hoàn hảo&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-các-khái-niệm-liên-quan&quot;&gt;5. Các khái niệm liên quan&lt;/h2&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;So sánh giữa GAN và Variational Autoencoder (VAE) làm rõ hai hướng đánh đổi chính của mô hình hóa sinh. VAE biểu diễn tường minh phân phối dữ liệu qua biến ẩn $$p(\mathbf{x}) = \int p(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})p(\mathbf{z})d\mathbf{z}$$ và tối ưu cận dưới ELBO, cho quy trình huấn luyện ổn định cùng cơ sở xác suất chặt chẽ nhưng ảnh thường mờ hơn do hàm mất mát tái tạo. GAN mô hình hóa mật độ ẩn qua bộ sinh và dùng tín hiệu đối kháng từ bộ phân biệt, nhờ đó ảnh đầu ra thường sắc nét hơn nhưng thiếu hàm mật độ tường minh và khó giữ ổn định khi huấn luyện.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Về mặt lý thuyết, GAN gắn trực tiếp với lý thuyết trò chơi qua bài toán minimax hai người tổng bằng không. Tại điểm cân bằng Nash, không bên nào có thể cải thiện đơn phương, tương ứng với phân phối của bộ sinh khớp phân phối dữ liệu thật. Tuy nhiên, việc áp dụng hạ gradient cục bộ lên một trò chơi không lồi nhiều chiều không đảm bảo hội tụ tới cân bằng Nash, giải thích vì sao quá trình huấn luyện dễ dao động và thúc đẩy các thuật toán như &lt;em&gt;unrolled optimization&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;GAN cũng có liên hệ gần với bài toán mẫu đối kháng (&lt;em&gt;adversarial examples&lt;/em&gt;) và tính bền vững của bộ phân loại: thay vì thêm nhiễu nhỏ để đánh lừa bộ phân loại, bộ sinh tổng hợp toàn bộ mẫu đầu vào nhằm đánh lừa bộ phân biệt, còn bộ phân biệt học chống lại mẫu giả đó.&lt;/p&gt;

&lt;p&gt;Ngoài nhiệm vụ sinh mẫu, GAN còn hỗ trợ học bán giám sát (&lt;em&gt;semi-supervised learning&lt;/em&gt;). Khi mở rộng bộ phân biệt để vừa phân biệt thật/giả vừa phân loại nhãn trên phần dữ liệu có nhãn, mô hình có thể khai thác thêm tập dữ liệu lớn không nhãn nhằm cải thiện hiệu năng phân loại trong bối cảnh thiếu nhãn.&lt;/p&gt;

&lt;p&gt;Từ góc nhìn học tăng cường (RL), bộ sinh không nhận nhãn đầu ra trực tiếp mà học qua tín hiệu đánh giá từ bộ phân biệt — tương tự tác nhân học từ phần thưởng (&lt;em&gt;reward&lt;/em&gt;) trong các phương pháp policy gradient. Mối liên hệ này tạo tiền đề cho nhiều hướng kết hợp giữa huấn luyện đối kháng và học tăng cường.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1406.2661&quot;&gt;“Generative Adversarial Networks” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ian Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, Yoshua Bengio&lt;br /&gt;
Bài báo đề xuất khung GAN dưới dạng trò chơi minimax, chứng minh tại điểm cân bằng tối ưu bộ sinh khôi phục đúng phân phối dữ liệu và trình bày kết quả thực nghiệm ban đầu. Đóng góp lớn nhất là mở ra hướng mô hình hóa sinh qua cạnh tranh đối kháng thay vì tối đa hóa hàm hợp lý hay sai số tái tạo, đồng thời chỉ ra sớm các thách thức về độ ổn định và sụp đổ mode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1511.06434&quot;&gt;“Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Alec Radford, Luke Metz, Soumith Chintala&lt;br /&gt;
DCGAN đưa ra bộ quy tắc thiết kế kiến trúc giúp huấn luyện GAN tích chập ổn định hơn: thay pooling bằng tích chập có stride, dùng batch normalization ở cả hai mạng (trừ tầng đầu ra của bộ sinh và tầng đầu vào của bộ phân biệt), dùng ReLU (và tanh ở đầu ra) cho bộ sinh cùng LeakyReLU cho bộ phân biệt. Bài báo cũng cho thấy không gian ẩn của GAN hỗ trợ các phép toán vector mang ý nghĩa ngữ nghĩa trên ảnh khuôn mặt 64×64.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1606.03498&quot;&gt;“Improved Techniques for Training GANs” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Tim Salimans, Ian Goodfellow, Wojciech Zaremba, Vicki Cheung, Alec Radford, Xi Chen&lt;br /&gt;
Bài báo giới thiệu hàng loạt kỹ thuật cải thiện ổn định huấn luyện như &lt;em&gt;feature matching&lt;/em&gt;, &lt;em&gt;minibatch discrimination&lt;/em&gt; (chống sụp đổ mode), &lt;em&gt;historical averaging&lt;/em&gt;, &lt;em&gt;one-sided label smoothing&lt;/em&gt; (dùng 0,9 thay vì 1,0 cho nhãn thật) và &lt;em&gt;virtual batch normalization&lt;/em&gt;, đồng thời đề xuất chỉ số đánh giá tự động Inception Score.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1710.10196&quot;&gt;“Progressive Growing of GANs for Improved Quality, Stability, and Variation” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Tero Karras, Timo Aila, Samuli Laine, Jaakko Lehtinen (NVIDIA)&lt;br /&gt;
Bài báo đề xuất huấn luyện tăng dần độ phân giải (&lt;em&gt;progressive growing&lt;/em&gt;): bắt đầu từ ảnh 4×4 rồi bổ sung dần các tầng cho cả bộ sinh và bộ phân biệt qua các mức 8×8, 16×16 cho tới 1024×1024. Lộ trình học từ cấu trúc thô đến chi tiết tinh giúp ổn định quá trình huấn luyện và mở khóa khả năng tổng hợp ảnh độ phân giải cao.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1812.04948&quot;&gt;“A Style-Based Generator Architecture for Generative Adversarial Networks” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Tero Karras, Samuli Laine, Timo Aila (NVIDIA)&lt;br /&gt;
StyleGAN thiết kế lại bộ sinh bằng cách ánh xạ vector nhiễu qua một mạng trung gian sang không gian phong cách \(\mathcal{W}\), rồi điều biến từng mức độ phân giải thông qua &lt;em&gt;adaptive instance normalization&lt;/em&gt;. Kiến trúc này cho phép điều khiển độc lập các đặc trưng thô (tư thế, hình dạng khuôn mặt) với chi tiết tinh (tóc, bề mặt da), đồng thời đề xuất thước đo &lt;em&gt;perceptual path length&lt;/em&gt; để đánh giá độ tách nhân tố của không gian ẩn.&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo&quot;&gt;Bẫy thường gặp và Mẹo&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Sụp đổ mode (&lt;em&gt;mode collapse&lt;/em&gt;)&lt;/strong&gt; là vấn đề điển hình khi bộ sinh chỉ tập trung tạo một vài dạng mẫu dễ đánh lừa bộ phân biệt thay vì bao phủ toàn bộ phân phối (chẳng hạn chỉ sinh chữ số 1 và 7 trên MNIST). Để phát hiện, cần kiểm tra độ đa dạng trên số lượng mẫu đủ lớn chứ không chỉ xem chất lượng vài mẫu lẻ. Các hướng giảm thiểu gồm &lt;em&gt;minibatch discrimination&lt;/em&gt;, &lt;em&gt;unrolled optimization&lt;/em&gt; hoặc chuyển sang các hàm mất mát ổn định hơn như Wasserstein GAN.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bộ phân biệt áp đảo quá sớm&lt;/strong&gt; khiến \(D(G(\mathbf{z}))\) nhanh chóng tiến về 0 và làm suy biến gradient cho bộ sinh. Dấu hiệu nhận biết là \(D(\mathbf{x}_{\text{real}})\) luôn sát 1 còn \(D(G(\mathbf{z}))\) luôn sát 0. Cách xử lý gồm giảm tần suất cập nhật hoặc learning rate của bộ phân biệt, thêm nhiễu nhẹ vào đầu vào của bộ phân biệt ở giai đoạn đầu, hoặc dùng &lt;em&gt;one-sided label smoothing&lt;/em&gt; (đặt nhãn thật bằng 0,9 thay vì 1,0).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Batch normalization với batch size nhỏ&lt;/strong&gt; trong bộ phân biệt có thể gây bất ổn do thống kê batch có phương sai lớn. Nên dùng batch size đủ lớn (từ 32–64 trở lên) hoặc chuyển sang layer normalization, instance normalization hay virtual batch normalization.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đánh giá chất lượng GAN&lt;/strong&gt; không thể dựa vào log-hợp lý hay giá trị loss đơn thuần (loss của \(G\) và \(D\) dao động liên tục theo thế cân bằng giữa hai mạng). Nên kết hợp các chỉ số tự động như Inception Score, FID cùng với kiểm tra trực quan định kỳ trên lưới mẫu sinh ra để theo dõi cả độ sắc nét lẫn độ đa dạng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Spectral normalization&lt;/strong&gt; là kỹ thuật hiệu quả và ít tốn chi phí để ổn định bộ phân biệt bằng cách chuẩn hóa ma trận trọng số theo giá trị kỳ dị lớn nhất (ràng buộc hằng số Lipschitz), ngăn gradient bùng nổ và đã trở thành cấu hình tiêu chuẩn trong nhiều kiến trúc GAN hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;điểm-then-chốt&quot;&gt;Điểm then chốt&lt;/h2&gt;

&lt;p&gt;GAN tổng hợp dữ liệu bằng cơ chế cạnh tranh minimax giữa bộ sinh và bộ phân biệt, học ngầm cách lấy mẫu từ phân phối dữ liệu mà không cần biểu diễn mật độ tường minh. Quá trình huấn luyện luân phiên giữa hai mạng đòi hỏi cân bằng chặt chẽ để tránh tình trạng bộ phân biệt áp đảo hoặc sụp đổ mode. Dù khó huấn luyện và khó đánh giá hơn VAE, GAN tạo ra mẫu sắc nét và không gian ẩn giàu cấu trúc ngữ nghĩa, đồng thời chứng minh rằng huấn luyện đối kháng là một nguyên lý hiệu quả vượt ra ngoài phạm vi mô hình hóa sinh.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, tiếng Anh. Minh họa trực quan hai bước cập nhật luân phiên được cài đặt trong mã nguồn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TpMIssRdhco&quot;&gt;What are GANs (Generative Adversarial Networks)?&lt;/a&gt; — IBM Technology, tiếng Anh. Nhắc lại nhanh từng mạng tối ưu hàm mất mát nào.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Gib_kiXgnvA&quot;&gt;The Math Behind Generative Adversarial Networks Clearly Explained!&lt;/a&gt; — Normalized Nerd, tiếng Anh. Hỗ trợ đối chiếu dấu hàm mất mát giữa công thức lý thuyết và đoạn mã PyTorch.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>14-01-01 Lý thuyết GAN</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter14/14_01_01_GAN_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter14/14_01_01_GAN_Theory</id>
   <content type="html">&lt;p&gt;Nếu ở VAE bạn chỉ cần làm một hàm loss duy nhất giảm đều về 0 là yên tâm, thì ở GAN, loss của \(D\) giảm về 0 lại thường là &lt;em&gt;thảm họa&lt;/em&gt;! Vì sao một bộ phân biệt quá giỏi lại giết chết quá trình học của bộ sinh, và tại sao việc đổi phân kỳ Jensen–Shannon sang khoảng cách Wasserstein lại cứu sống được gradient? Bài lý thuyết này mổ xẻ cơ chế toán học đằng sau sự mong manh lẫn sức mạnh của GAN.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-lý-thuyết-trò-chơi-và-hình-học-phân-kỳ-của-gan&quot;&gt;Kiến thức cần nhớ: Lý thuyết trò chơi và hình học phân kỳ của GAN&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tối ưu hóa điểm yên ngựa (Saddle Point) thay vì cực tiểu:&lt;/strong&gt; Hiểu lý do hai mạng cập nhật đồng thời có thể quay vòng tròn mãi quanh điểm cân bằng thay vì hội tụ thẳng vào nó.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân kỳ Jensen–Shannon (JSD) và bẫy đa tạp không giao nhau:&lt;/strong&gt; Khi \(p_{\text{data}}\) và \(p_g\) nằm trên hai đa tạp thấp chiều không cắt nhau trong không gian ảnh, \(D_{\text{JS}} = \ln 2\) là hằng số, khiến gradient theo tham số của \(G\) triệt tiêu hoàn toàn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Wasserstein GAN (WGAN) và ràng buộc 1-Lipschitz:&lt;/strong&gt; Chuyển sang khoảng cách Earth Mover qua đối ngẫu Kantorovich–Rubinstein \(\sup_{\|f\|_L \le 1} \mathbb{E}_{p_{\text{data}}}[f] - \mathbb{E}_{p_g}[f]\) để tạo gradient mượt ngay cả khi hai phân phối tách rời.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa quang phổ (Spectral Normalization) và Gradient Penalty (WGAN-GP):&lt;/strong&gt; Các cơ chế hiện đại ép hàm phê bình (critic) thỏa mãn điều kiện Lipschitz mà không cần cắt cụt trọng số thô bạo.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-jsd-và-khoảng-cách-wasserstein-khi-hai-phân-phối-tách-rời-nhau&quot;&gt;Giải thích: So sánh JSD và khoảng cách Wasserstein khi hai phân phối tách rời nhau&lt;/h3&gt;

&lt;p&gt;Xét hai phân phối 1D đơn giản đặt tại hai điểm rời rạc: phân phối thật tập trung tại \(x = 0\) (\(p_{\text{data}} = \delta_0\)) và phân phối sinh tập trung tại \(x = \theta\) (\(p_g = \delta_\theta\) với \(\theta &amp;gt; 0\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính phân kỳ Jensen–Shannon \(D_{\text{JS}}(\delta_0 \| \delta_\theta)\):&lt;/strong&gt;
Với phân phối trung bình \(M = \tfrac{1}{2}\delta_0 + \tfrac{1}{2}\delta_\theta\):
    &lt;ul&gt;
      &lt;li&gt;Khi \(\theta \neq 0\): \(D_{\text{JS}} = \frac{1}{2}\ln\frac{1}{1/2} + \frac{1}{2}\ln\frac{1}{1/2} = \ln 2 \approx 0{,}693\) (hằng số cho mọi \(\theta &amp;gt; 0\)!).&lt;/li&gt;
      &lt;li&gt;Khi \(\theta = 0\): \(D_{\text{JS}} = 0\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Đạo hàm theo \(\theta\):&lt;/strong&gt; \(\frac{d}{d\theta}D_{\text{JS}} = 0\) tại mọi \(\theta &amp;gt; 0\) — không có tín hiệu kéo \(\theta\) về \(0\)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính khoảng cách Wasserstein-1 \(W_1(\delta_0, \delta_\theta)\):&lt;/strong&gt;
Chi phí di chuyển khối xác suất \(1\) từ \(\theta\) về \(0\) là \(W_1(\delta_0, \delta_\theta) = |\theta|\).
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Đạo hàm theo \(\theta\) (với \(\theta &amp;gt; 0\)):&lt;/strong&gt; \(\frac{d}{d\theta}W_1 = +1\) — một tín hiệu gradient sạch, ổn định và không đổi kéo \(\theta\) thẳng về \(0\) dù \(\theta = 10\) hay \(\theta = 0{,}01\)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;mạng-sinh-đối-kháng-học-qua-cạnh-tranh&quot;&gt;Mạng Sinh Đối kháng: Học qua cạnh tranh&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://developers.google.com/static/machine-learning/gan/images/gan_diagram.svg&quot; alt=&quot;GAN Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc GAN với Generator (bộ sinh) và Discriminator (bộ phân biệt). Nguồn: Google Developers&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Mạng Sinh Đối kháng (&lt;em&gt;Generative Adversarial Networks&lt;/em&gt; — GAN), do Ian Goodfellow và cộng sự đề xuất năm 2014, tiếp cận mô hình hóa sinh theo một cơ chế khác hẳn các phương pháp trước đó: huấn luyện hai mạng nơ-ron cạnh tranh với nhau. Bộ sinh (&lt;em&gt;generator&lt;/em&gt;) học cách tạo dữ liệu giả sao cho giống dữ liệu thật, còn bộ phân biệt (&lt;em&gt;discriminator&lt;/em&gt;) học cách phân tách dữ liệu thật với dữ liệu do bộ sinh tạo ra. Qua nhiều vòng lặp đối kháng, cả hai mạng cùng cải thiện, giúp bộ sinh tạo ra các mẫu ngày càng sát với phân phối dữ liệu thật.&lt;/p&gt;

&lt;p&gt;Điểm khác biệt của GAN thể hiện rõ khi đặt cạnh các phương pháp truyền thống. Những mô hình như Gaussian Mixture Model hay Hidden Markov Model đòi hỏi biểu thức xác suất tường minh với các giả định chặt về phân phối; Variational Autoencoder tuy dùng mạng nơ-ron nhưng vẫn cần mô hình hóa mật độ tường minh và suy diễn biến phân. GAN tránh hoàn toàn việc viết tường minh mật độ \(p(x)\) mà học ngầm cách lấy mẫu từ phân phối đó thông qua bộ sinh. Nhờ mô hình hóa mật độ ẩn, GAN có thể xử lý dữ liệu nhiều chiều phức tạp như ảnh tự nhiên mà không bị ràng buộc bởi dạng tham số của hàm mật độ.&lt;/p&gt;

&lt;p&gt;Khung huấn luyện đối kháng lấy cảm hứng từ trò chơi tổng bằng không (&lt;em&gt;zero-sum game&lt;/em&gt;) trong lý thuyết trò chơi: lợi thế của bên này là bất lợi của bên kia. Khi bộ phân biệt phát hiện ảnh giả chính xác hơn, nó cung cấp tín hiệu gradient chi tiết hơn để bộ sinh sửa lỗi; ngược lại, khi bộ sinh tạo ảnh tốt hơn, bộ phân biệt buộc phải học các đặc trưng tinh tế hơn. Tại điểm cân bằng lý thuyết — khi bộ phân biệt không thể phân biệt thật/giả tốt hơn đoán ngẫu nhiên — phân phối do bộ sinh tạo ra trùng khớp với phân phối dữ liệu thật.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, huấn luyện đồng thời hai mạng có mục tiêu đối nghịch khó hơn nhiều so với học giám sát thông thường. Hàm mất mát của mỗi mạng phụ thuộc vào tham số đang thay đổi liên tục của mạng kia, tạo thành một mục tiêu di động dễ dẫn đến dao động hoặc phân kỳ. Một hiện tượng phổ biến khác là sụp đổ mode (&lt;em&gt;mode collapse&lt;/em&gt;), khi bộ sinh chỉ tạo lặp đi lặp lại một vài dạng mẫu thay vì bao phủ toàn bộ sự đa dạng của dữ liệu. Ngoài ra, vì không có hàm mật độ tường minh, việc đánh giá định lượng chất lượng GAN cũng không đơn giản. Do đó, huấn luyện GAN ổn định thường đòi hỏi thiết kế kiến trúc, hàm mất mát và siêu tham số cẩn thận.&lt;/p&gt;

&lt;p&gt;Dù khó huấn luyện, GAN đã chứng minh hiệu quả rõ rệt trên nhiều bài toán như tổng hợp ảnh khuôn mặt, chuyển đổi miền ảnh (chẳng hạn ngựa thành ngựa vằn), siêu phân giải ảnh và tạo dữ liệu tổng hợp. Hiểu vững mô hình GAN gốc là nền tảng để tiếp cận các biến thể hiện đại nhằm cải thiện độ ổn định và khả năng kiểm soát đầu ra.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Cơ sở toán học của GAN được diễn đạt dưới dạng bài toán tối ưu minimax giữa bộ sinh và bộ phân biệt.&lt;/p&gt;

&lt;p&gt;Bộ sinh \(G\) là một mạng nơ-ron nhận vector nhiễu ngẫu nhiên \(\mathbf{z}\) lấy mẫu từ phân phối đơn giản (thường là \(\mathbf{z} \sim \mathcal{N}(0, I)\)) và ánh xạ sang dữ liệu giả:&lt;/p&gt;

\[\mathbf{x}_{\text{fake}} = G(\mathbf{z}; \theta_G)\]

&lt;p&gt;trong đó \(\theta_G\) là tham số của bộ sinh. Vector \(\mathbf{z}\) cung cấp nguồn biến thiên ngẫu nhiên để sinh các mẫu khác nhau.&lt;/p&gt;

&lt;p&gt;Bộ phân biệt \(D\) là một mạng nơ-ron nhận đầu vào \(\mathbf{x}\) (mẫu thật hoặc mẫu sinh từ \(G\)) và xuất xác suất mẫu đó thuộc dữ liệu thật:&lt;/p&gt;

\[D(\mathbf{x}; \theta_D) \in [0, 1]\]

&lt;p&gt;với \(\theta_D\) là tham số của bộ phân biệt. Thông thường \(D\) kết thúc bằng hàm kích hoạt sigmoid: \(D(\mathbf{x}) = \sigma(f_{\theta_D}(\mathbf{x}))\), trong đó \(f\) là phần trích xuất đặc trưng (như các tầng tích chập).&lt;/p&gt;

&lt;p&gt;Mục tiêu huấn luyện của trò chơi minimax được viết là:&lt;/p&gt;

\[\min_G \max_D V(D, G) = \mathbb{E}_{\mathbf{x} \sim p_{\text{data}}}[\log D(\mathbf{x})] + \mathbb{E}_{\mathbf{z} \sim p_z}[\log(1 - D(G(\mathbf{z})))]\]

&lt;p&gt;Ý nghĩa của từng thành phần:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Bộ phân biệt muốn &lt;strong&gt;tối đa hóa&lt;/strong&gt; \(V\): gán xác suất gần 1 cho dữ liệu thật (\(D(\mathbf{x}) \to 1\) nên \(\log D(\mathbf{x}) \to 0\)) và xác suất gần 0 cho dữ liệu giả (\(D(G(\mathbf{z})) \to 0\) nên \(\log(1 - D(G(\mathbf{z}))) \to 0\)).&lt;/li&gt;
  &lt;li&gt;Bộ sinh muốn &lt;strong&gt;tối thiểu hóa&lt;/strong&gt; \(V\), tức tối thiểu hóa \(\mathbb{E}_{\mathbf{z}}[\log(1 - D(G(\mathbf{z})))]\) để buộc bộ phân biệt gán xác suất cao cho mẫu giả.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trong thực tế, mục tiêu \(\min_G \log(1-D(G(\mathbf{z})))\) gặp vấn đề bão hòa gradient ở giai đoạn đầu huấn luyện: khi bộ sinh còn yếu, \(D(G(\mathbf{z})) \approx 0\) khiến đạo hàm của \(\log(1 - D(G(\mathbf{z})))\) rất nhỏ, làm bộ sinh học rất chậm. Để khắc phục, người ta dùng mục tiêu không bão hòa (&lt;em&gt;non-saturating&lt;/em&gt;): thay vì tối thiểu hóa \(\log(1-D(G(\mathbf{z})))\), bộ sinh tối đa hóa \(\log D(G(\mathbf{z}))\) (tương đương tối thiểu hóa \(-\log D(G(\mathbf{z}))\)), vốn có gradient mạnh hơn nhiều khi \(D(G(\mathbf{z}))\) còn nhỏ.&lt;/p&gt;

&lt;p&gt;Quá trình huấn luyện luân phiên giữa hai bước cập nhật:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cập nhật bộ phân biệt&lt;/strong&gt; (tối đa hóa \(V\) theo \(\theta_D\)):&lt;/p&gt;

\[\theta_D \leftarrow \theta_D + \eta_D \nabla_{\theta_D} \left[\frac{1}{m}\sum_{i=1}^m \log D(\mathbf{x}^{(i)}) + \log(1-D(G(\mathbf{z}^{(i)})))\right]\]

&lt;p&gt;&lt;strong&gt;Cập nhật bộ sinh&lt;/strong&gt; (tối đa hóa mục tiêu non-saturating theo \(\theta_G\)):&lt;/p&gt;

\[\theta_G \leftarrow \theta_G + \eta_G \nabla_{\theta_G} \left[\frac{1}{m}\sum_{i=1}^m \log D(G(\mathbf{z}^{(i)}))\right]\]

&lt;p&gt;Gradient cho bộ sinh phải lan truyền ngược qua bộ phân biệt: \(\nabla_{\theta_G} D(G(\mathbf{z}))\) phụ thuộc trực tiếp vào chất lượng phản hồi của \(D\). Nếu \(D\) quá mạnh và tách biệt hoàn toàn thật/giả, gradient suy biến về 0; ngược lại nếu \(D\) quá yếu, tín hiệu dẫn đường lại thiếu chính xác.&lt;/p&gt;

&lt;p&gt;Để giữ thế cân bằng, các chiến lược phổ biến gồm: cập nhật bộ phân biệt \(k\) bước cho mỗi bước cập nhật bộ sinh (thường \(k=1\) hoặc \(5\)), thêm nhiễu vào đầu vào bộ phân biệt ở giai đoạn đầu để làm chậm sự áp đảo của nó, hoặc dùng learning rate khác nhau giữa hai mạng (thường \(\eta_G &amp;lt; \eta_D\)).&lt;/p&gt;

&lt;p&gt;Tại điểm cân bằng lý thuyết khi \(p_G = p_{\text{data}}\), bộ phân biệt tối ưu đạt \(D^*(\mathbf{x}) = \frac{p_{\text{data}}(\mathbf{x})}{p_{\text{data}}(\mathbf{x}) + p_G(\mathbf{x})} = 0.5\) tại mọi điểm — không thể phân biệt thật/giả tốt hơn đoán ngẫu nhiên — và cả hai số hạng hàm mất mát đều bằng \(\log(0.5)\). Trong thực hành, đạt tới cân bằng ổn định là bài toán khó vì quỹ đạo tối ưu dễ dao động hoặc rơi vào sụp đổ mode; các kỹ thuật như &lt;em&gt;minibatch discrimination&lt;/em&gt;, &lt;em&gt;unrolled optimization&lt;/em&gt; và &lt;em&gt;spectral normalization&lt;/em&gt; được phát triển để kiểm soát động lực đối kháng này.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;p&gt;Một phép tương tự quen thuộc để hình dung cơ chế đối kháng là cuộc cạnh tranh giữa kẻ làm tiền giả (bộ sinh) và thanh tra ngân hàng (bộ phân biệt). Ban đầu, tờ tiền giả rất thô sơ nên thanh tra dễ dàng nhận ra (\(D \approx 0\)) và chỉ rõ sai lệch về màu sắc, chất liệu hay chi tiết bảo mật. Dựa trên phản hồi đó, kẻ làm giả cải tiến kỹ thuật; thanh tra lại phải kiểm tra sâu hơn như soi tia UV. Vòng lặp này tiếp diễn cho đến khi thanh tra không còn phân biệt được thật và giả tốt hơn mức 50/50 (\(D(\mathbf{x}) = 0.5\)).&lt;/p&gt;

&lt;p&gt;Quá trình huấn luyện GAN trên chữ số MNIST diễn tiến tương tự:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Vòng lặp 1–10 (bộ sinh còn yếu):&lt;/strong&gt; ảnh sinh ra gần như nhiễu, bộ phân biệt dễ dàng xuất giá trị gần 0 và cung cấp gradient mạnh hướng dẫn bộ sinh hình thành nét cơ bản và vị trí căn giữa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vòng lặp 100–500 (bộ sinh cải thiện dần):&lt;/strong&gt; ảnh bắt đầu mang hình dáng chữ số nhưng vẫn còn lỗi tỷ lệ hoặc nhiễu biên; bộ phân biệt học phát hiện những sai khác tinh hơn như độ cong nét chữ, đẩy bộ sinh tinh chỉnh theo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Từ vòng lặp 1000 trở đi (tiến gần cân bằng):&lt;/strong&gt; chữ số sinh ra rõ nét hơn, độ chính xác phân biệt thật/giả của \(D\) tiến gần 50% và các vector \(\mathbf{z}\) khác nhau ánh xạ sang các chữ số đa dạng.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Minh họa bằng con số cụ thể: giả sử với một mẫu giả, bộ phân biệt xuất \(D(G(\mathbf{z})) = 0.3\) (xác suất là thật 30%). Với mục tiêu không bão hòa, hàm mất mát của bộ sinh là \(-\log(0.3) = 1.20\) và gradient sẽ điều chỉnh \(\theta_G\) để kéo \(D(G(\mathbf{z}))\) tiến về 1. Đồng thời, nếu trên mẫu thật bộ phân biệt xuất \(D(\mathbf{x}_{\text{real}}) = 0.95\), hàm mất mát của bộ phân biệt là \(-\log(0.95) - \log(1-0.3) = 0.05 + 0.36 = 0.41\), thúc đẩy \(D\) tách biệt hai phân phối tốt hơn.&lt;/p&gt;

&lt;p&gt;Sụp đổ mode cũng dễ hình dung trên ví dụ này: nếu bộ sinh nhận thấy chỉ cần tạo chữ số “1” (cấu trúc đơn giản) đã đủ đánh lừa bộ phân biệt, nó có thể chỉ sinh lặp đi lặp lại chữ số “1” và bỏ qua các chữ số còn lại. Khi bộ phân biệt học cách nhận diện “1” giả, bộ sinh lại chuyển sang sụp đổ vào một chữ số khác thay vì bao phủ cả 10 lớp. Các kỹ thuật như &lt;em&gt;minibatch discrimination&lt;/em&gt; (cho phép bộ phân biệt quan sát độ đa dạng của cả batch) giúp giảm đáng kể tình trạng này.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=Gib_kiXgnvA&quot;&gt;The Math Behind Generative Adversarial Networks Clearly Explained!&lt;/a&gt; — Normalized Nerd, tiếng Anh. Giải thích chi tiết mục tiêu minimax và mối liên hệ giữa bộ phân biệt tối ưu với phân kỳ xác suất.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, tiếng Anh. Minh họa trực quan hai mạng cạnh tranh cùng mục tiêu toán học.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, tiếng Anh. Phân tích hiện tượng sụp đổ mode và bất ổn huấn luyện như hệ quả của cơ chế đối kháng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>14 Mạng Sinh Đối kháng (GAN)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter14/14_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter14/14_00_Introduction</id>
   <content type="html">&lt;p&gt;Câu chuyện về sự ra đời của GAN vào năm 2014 đã trở thành huyền thoại trong giới AI: tại một quán rượu ở Montreal, Ian Goodfellow tranh luận với đồng nghiệp về cách dạy máy tính tự sinh ảnh sắc nét mà không cần tính tích phân xác suất rườm rà, rồi về nhà viết ngay đoạn mã đầu tiên trong đêm — và nó chạy được ngay lần thử đầu tiên! Thay vì học hàm mật độ tường minh, &lt;strong&gt;Mạng Sinh Đối kháng (GAN)&lt;/strong&gt; đặt hai mạng nơ-ron vào một cuộc đua tiến hóa không khoan nhượng: một kẻ tạo ảnh giả ngày càng tinh vi và một giám định viên ngày càng sắc bén.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-mạng-sinh-đối-kháng-gan&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Mạng Sinh Đối kháng (GAN)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Trò chơi minimax hai người chơi:&lt;/strong&gt; Bộ sinh \(G\) và bộ phân biệt \(D\) tối ưu cùng một hàm giá trị \(V(D, G)\) theo hai chiều ngược nhau, hướng tới điểm cân bằng Nash nơi \(p_g = p_{\text{data}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Liên hệ với phân kỳ Jensen–Shannon và Wasserstein:&lt;/strong&gt; Chứng minh tại bộ phân biệt tối ưu \(D^*\), trò chơi GAN tối thiểu hóa \(2\,D_{\text{JS}}(p_{\text{data}} \| p_g) - \ln 4\), đồng thời giải thích lý do WGAN thay bằng khoảng cách Earth Mover.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc tích chập sâu (DCGAN) và ổn định huấn luyện:&lt;/strong&gt; Những quy tắc vàng về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BatchNorm&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LeakyReLU&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tanh&lt;/code&gt;, cân bằng bước học và tránh bão hòa gradient.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bệnh lý huấn luyện và tiến hóa hiện đại:&lt;/strong&gt; Chẩn đoán mode collapse, dao động không hội tụ, và cách các ý tưởng đối kháng sống tiếp trong StyleGAN, PatchGAN và chưng cất khuếch tán một bước.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-điểm-cân-bằng-nash-tối-ưu-của-bộ-phân-biệt-dx&quot;&gt;Giải thích: Tính điểm cân bằng Nash tối ưu của bộ phân biệt \(D^*(x)\)&lt;/h3&gt;

&lt;p&gt;Tại một điểm dữ liệu \(x\) bất kỳ, giả sử mật độ dữ liệu thật là \(p_{\text{data}}(x)\) và mật độ ảnh sinh là \(p_g(x)\). Bộ phân biệt tối ưu thỏa mãn:
\(D^*(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x) + p_g(x)}.\)&lt;/p&gt;

&lt;p&gt;Xét 3 giai đoạn huấn luyện tại cùng một điểm \(x\) có \(p_{\text{data}}(x) = 0{,}4\):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giai đoạn đầu&lt;/strong&gt; (\(G\) còn kém, \(p_g(x) = 0{,}05\)): \(D^*(x) = \frac{0{,}4}{0{,}4 + 0{,}05} \approx 0{,}889\) — bộ phân biệt rất tự tin đây là ảnh thật.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giai đoạn giữa&lt;/strong&gt; (\(p_g(x) = 0{,}20\)): \(D^*(x) = \frac{0{,}4}{0{,}4 + 0{,}2} = 0{,}667\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điểm cân bằng Nash lý tưởng&lt;/strong&gt; (\(p_g(x) = p_{\text{data}}(x) = 0{,}4\)): \(D^*(x) = \frac{0{,}4}{0{,}4 + 0{,}4} = 0{,}500\).
Khi đó hàm giá trị đạt \(V(D^*, G^*) = \ln(0{,}5) + \ln(0{,}5) = -\ln 4 \approx -1{,}3863\): giám định viên hoàn toàn “tung đồng xu” 50–50 vì ảnh giả đã khớp tuyệt đối với phân phối ảnh thật.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mạng Sinh Đối kháng (&lt;em&gt;Generative Adversarial Networks&lt;/em&gt; — GAN) đặt hai mạng nơ-ron vào thế cạnh tranh: bộ sinh (&lt;em&gt;generator&lt;/em&gt;) tạo ra dữ liệu tổng hợp và bộ phân biệt (&lt;em&gt;discriminator&lt;/em&gt;) tìm cách tách biệt dữ liệu thật với dữ liệu do bộ sinh tạo ra. Cơ chế huấn luyện đối kháng này cho phép tổng hợp ảnh có độ sắc nét cao. Chương này trình bày nguyên lý huấn luyện GAN, hàm mất mát, các kiến trúc tiêu biểu (DCGAN, StyleGAN), thách thức thường gặp khi huấn luyện và các ứng dụng thực tế.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần huấn luyện GAN, xem &lt;strong&gt;14-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về StyleGAN3, GigaGAN và những bài toán mà mô hình đối kháng vẫn giữ lợi thế so với khuếch tán.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, tiếng Anh. Giới thiệu trực quan trò chơi hai người giữa bộ sinh và bộ phân biệt — trọng tâm của chương này.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Gib_kiXgnvA&quot;&gt;The Math Behind Generative Adversarial Networks Clearly Explained!&lt;/a&gt; — Normalized Nerd, tiếng Anh. Phần nền tảng toán học minimax tương ứng với cơ chế trò chơi trên.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TpMIssRdhco&quot;&gt;What are GANs (Generative Adversarial Networks)?&lt;/a&gt; — IBM Technology, tiếng Anh. Tóm tắt nhanh vai trò của từng mạng trong kiến trúc GAN.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>13-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter13/13_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter13/13_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Có một sự thật thú vị ít người để ý: dù Stable Diffusion, Sora hay Veo nổi tiếng nhờ mô hình khuếch tán và Transformer, nhưng bức ảnh hay thước phim cuối cùng bạn nhìn thấy trên màn hình lại luôn được “vẽ ra” bởi một &lt;strong&gt;VAE&lt;/strong&gt;! Thay vì cạnh tranh trực tiếp với Diffusion về độ sắc nét, VAE hiện đại đã tìm thấy vị trí không thể thay thế trong vai trò bộ mã hóa – giải mã không gian ẩn cho ảnh độ phân giải cao, video 3D và các bộ sinh một bước.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-vai-trò-chiến-lược-của-vae-trong-hệ-sinh-thái-tạo-sinh-20222026&quot;&gt;Kiến thức cần nhớ: Vai trò chiến lược của VAE trong hệ sinh thái tạo sinh 2022–2026&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;KL-VAE + Perceptual/GAN Loss trong Stable Diffusion:&lt;/strong&gt; Kết hợp trọng số KL rất nhỏ (\(\sim 10^{-6}\)) với hàm mất mát cảm nhận (LPIPS) và bộ phân biệt PatchGAN để xóa bỏ nhược điểm ảnh mờ của VAE cổ điển.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Causal 3D VAE cho mô hình sinh video:&lt;/strong&gt; Mở rộng nén theo cả không gian lẫn thời gian (ví dụ \(4\times\) thời gian và \(8\times 8\) không gian) giúp nén 1 đoạn video thành chuỗi token gọn nhẹ cho DiT.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;VQ-VAE và mã hóa rời rạc (Discrete Tokenizers):&lt;/strong&gt; Ánh xạ vector ẩn vào sổ mã hữu hạn (codebook) để ghép nối trực tiếp ảnh/video với mô hình ngôn ngữ tự hồi quy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chưng cất khuếch tán và Consistency Models trong không gian ẩn:&lt;/strong&gt; Thực hiện sinh ảnh trong 1–4 bước ngay trên không gian ẩn của VAE, giảm độ trễ từ vài giây xuống dưới 100 mili-giây.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-hệ-số-nén-của-causal-3d-vae-trên-một-đoạn-video-ngắn&quot;&gt;Giải thích: Tính hệ số nén của Causal 3D VAE trên một đoạn video ngắn&lt;/h3&gt;

&lt;p&gt;Xét một đoạn video 4 giây ở tốc độ 24 khung hình/giây (\(T = 96\) khung hình), độ phân giải \(512 \times 512\) với 3 kênh màu RGB.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Số giá trị pixel thô:&lt;/strong&gt;
\(96 \times 512 \times 512 \times 3 = 75{,}497{,}472 \text{ giá trị (}\approx 75{,}5\text{ triệu số).}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Qua Causal 3D VAE&lt;/strong&gt; với hệ số nén \(4\times\) theo thời gian, \(8\times\) theo chiều cao, \(8\times\) theo chiều rộng và \(C_z = 16\) kênh ẩn:
    &lt;ul&gt;
      &lt;li&gt;Kích thước tensor ẩn: \((96/4) \times (512/8) \times (512/8) \times 16 = 24 \times 64 \times 64 \times 16 = 1{,}572{,}864\) giá trị.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tỷ lệ nén tổng thể:&lt;/strong&gt;
\(\frac{75{,}497{,}472}{1{,}572{,}864} = 48\times.\)
Quan trọng hơn, số vị trí không-thời gian giảm từ \(96 \times 512 \times 512\) xuống \(24 \times 64 \times 64 = 98{,}304\) (giảm \(256\times\)) — biến việc huấn luyện Diffusion Transformer trên video từ bất khả thi thành khả thi trên cụm GPU hiện đại.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-vae-trong-vai-trò-không-gian-ẩn-cho-khuếch-tán-video-và-nén&quot;&gt;Tùy chọn: VAE trong vai trò không gian ẩn cho khuếch tán, video và nén&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần ELBO, thủ thuật tái tham số hóa hay cài đặt VAE cốt lõi. Nội dung cho thấy cùng kiến trúc autoencoder biến phân đã trở thành &lt;strong&gt;bộ nén (codec)&lt;/strong&gt; chuẩn trong các hệ thống sinh giai đoạn 2022–2026 như thế nào.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Mục tiêu ELBO:&lt;/p&gt;

\[\mathcal{L}(\theta,\phi) = \mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)] - D_{\mathrm{KL}}(q_\phi(z|x)\,\|\,p(z))\]

&lt;p&gt;vẫn giữ nguyên vai trò nền tảng. Trong các hệ thống thực tế hiện nay, VAE ít được dùng để lấy mẫu trực tiếp từ \(z\sim\mathcal{N}(0,I)\) mà thường đóng vai trò nén dữ liệu sang không gian ẩn \(z\) cho một mô hình &lt;strong&gt;thứ hai&lt;/strong&gt; (khuếch tán hoặc Transformer) hoạt động hiệu quả hơn.&lt;/p&gt;

&lt;h2 id=&quot;1-vae-trong-stable-diffusion&quot;&gt;1. VAE trong Stable Diffusion&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;Rombach et al., 2022&lt;/a&gt; huấn luyện một autoencoder chính quy hóa KL (thường gọi là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AutoencoderKL&lt;/code&gt;) với đầu ra ẩn là một lưới không gian giảm kích thước thay vì vector 1D. Số hạng KL tương ứng trực tiếp với chính quy hóa trong Chương 13, còn mất mát cảm nhận và đối kháng giúp giữ độ sắc nét tái tạo cho mạng khử nhiễu hoạt động ở phía sau. Phần lớn các pipeline sinh ảnh từ văn bản mã nguồn mở (SD, SDXL và nhiều hệ thống thế hệ SD3) đều áp dụng thiết kế này.&lt;/p&gt;

&lt;h2 id=&quot;2-một-số-ứng-dụng-tiêu-biểu&quot;&gt;2. Một số ứng dụng tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;không-gian-ẩn-cho-video-và-dữ-liệu-3d&quot;&gt;Không gian ẩn cho video và dữ liệu 3D&lt;/h3&gt;

&lt;p&gt;Stable Video Diffusion và các mô hình sinh video sau này tái sử dụng VAE ảnh hoặc huấn luyện VAE &lt;strong&gt;không gian–thời gian&lt;/strong&gt; (dùng tích chập 3D hoặc tích chập nhân quả) để nén chuỗi khung hình thành ít token hơn trước khi đưa vào bộ khử nhiễu.&lt;/p&gt;

&lt;h3 id=&quot;mô-hình-nhất-quán-consistency-models-và-bộ-sinh-một-bước-trong-không-gian-ẩn&quot;&gt;Mô hình nhất quán (&lt;em&gt;consistency models&lt;/em&gt;) và bộ sinh một bước trong không gian ẩn&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.01469&quot;&gt;Song et al., 2023&lt;/a&gt; (consistency models) và Latent Consistency Models (LCM) chưng cất quá trình giải ODE khuếch tán ngay trong không gian ẩn của VAE. Trong các hệ thống này, VAE được giữ cố định và phần cải tiến tập trung vào bộ lấy mẫu — cho thấy VAE vẫn là thành phần cốt lõi ngay cả khi khuếch tán chiếm ưu thế.&lt;/p&gt;

&lt;h3 id=&quot;học-biểu-diễn&quot;&gt;Học biểu diễn&lt;/h3&gt;

&lt;p&gt;Hướng tách nhân tố bằng \(\beta\)-VAE không còn là tâm điểm như giai đoạn 2018, nhưng nút thắt &lt;strong&gt;biến phân&lt;/strong&gt; vẫn xuất hiện đều đặn trong các mô hình thế giới (&lt;em&gt;world models&lt;/em&gt; như DreamerV3, xem bài tùy chọn Chương 21) và bài toán nén dữ liệu học được.&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-mã-nguồn-phổ-biến&quot;&gt;3. Thư viện và mã nguồn phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/diffusers&quot;&gt;diffusers&lt;/a&gt; với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AutoencoderKL&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AutoencoderTiny&lt;/code&gt; (TAESD).&lt;/li&gt;
  &lt;li&gt;Các checkpoint VAE của Stability-AI trên Hugging Face Hub.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/openai/consistency_models&quot;&gt;openai/consistency_models&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-tài-liệu-tham-khảo-20222026&quot;&gt;4. Tài liệu tham khảo (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;Latent Diffusion Models (Rombach et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.01469&quot;&gt;Consistency Models (Song et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2403.03206&quot;&gt;SD3 (Esser et al., 2024)&lt;/a&gt; — tiếp tục kết hợp autoencoder ẩn với flow matching.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-phần-bổ-sung-so-với-nội-dung-cốt-lõi&quot;&gt;5. Phần bổ sung so với nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên tự suy ra ELBO và nắm vững thủ thuật tái tham số hóa trước. Bài này chỉ minh họa &lt;strong&gt;không gian ẩn \(z\) được khai thác ở đâu&lt;/strong&gt; trong các hệ thống giai đoạn 2022–2026 chứ không thay đổi cận dưới ELBO cơ bản.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=J87hffSMB60&quot;&gt;How does Stable Diffusion work? – Latent Diffusion Models EXPLAINED&lt;/a&gt; — AI Coffee Break with Letitia, tiếng Anh. Giải thích vai trò của VAE trong Stable Diffusion như phần trình bày của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, tiếng Anh. Ôn lại mục tiêu ELBO mà VAE vẫn tối ưu khi làm bộ nén cho khuếch tán.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But how do AI images and videos actually work?&lt;/td&gt;
          &lt;td&gt;Guest video by Welch Labs](https://www.youtube.com/watch?v=iv-5mZ_9CPY) — 3Blue1Brown, tiếng Anh. Minh họa cách mô hình khuếch tán thao tác trên không gian ẩn của VAE.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>13-01 Variational Autoencoder</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter13/13_01_VAE_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter13/13_01_VAE_Fundamentals</id>
   <content type="html">&lt;p&gt;Nếu Autoencoder là chiếc máy ảnh kỹ thuật số chỉ biết nén và giải nén lại đúng bức ảnh bạn chụp, thì Variational Autoencoder giống như một nhà điêu khắc nắm được toàn bộ giải phẫu học: chỉ cần một tọa độ ngẫu nhiên từ phân phối chuẩn, nó có thể tạc nên một tác phẩm mới chưa từng tồn tại. Mục tổng quan này kết nối trực giác xác suất, nền tảng lý thuyết ELBO và bài cài đặt PyTorch thành một mạch học thống nhất.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-mảnh-ghép-cốt-lõi-của-bài-học-vae&quot;&gt;Kiến thức cần nhớ: Bốn mảnh ghép cốt lõi của bài học VAE&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Sự khác biệt cấu trúc với Autoencoder:&lt;/strong&gt; Chuyển từ mã ẩn xác định \(\mathbf{z} = f(\mathbf{x})\) sang tham số phân phối \((\boldsymbol{\mu}(\mathbf{x}), \log\boldsymbol{\sigma}^2(\mathbf{x}))\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cân bằng sinh mẫu và tái tạo:&lt;/strong&gt; Nắm vững vai trò của hai số hạng trong ELBO và cách tham số \(\beta\) điều chỉnh sự đánh đổi giữa độ nét tái tạo và độ mượt không gian ẩn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Liên thông lý thuyết – thực hành:&lt;/strong&gt; Đi từ chứng minh ELBO &amp;amp; Reparameterization (&lt;strong&gt;13-01-01&lt;/strong&gt;) sang cài đặt PyTorch và trực quan hóa đa tạp 2D (&lt;strong&gt;13-01-02&lt;/strong&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lý do ảnh VAE thường hơi mờ:&lt;/strong&gt; Hiểu tác động của phân phối đầu ra độc lập theo pixel (factorized Gaussian/Bernoulli) lên chi tiết tần số cao, mở đường sang GAN và Diffusion.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-lấy-mẫu-sinh-ảnh-mới-từ-phân-phối-tiên-nghiệm-trên-vae-2-chiều&quot;&gt;Giải thích: Lấy mẫu sinh ảnh mới từ phân phối tiên nghiệm trên VAE 2 chiều&lt;/h3&gt;

&lt;p&gt;Sau khi huấn luyện xong VAE với không gian ẩn \(d = 2\), ta &lt;strong&gt;bỏ hoàn toàn bộ mã hóa&lt;/strong&gt; và chỉ giữ bộ giải mã \(p_\theta(\mathbf{x}\mid\mathbf{z})\). Để vẽ lưới \(3 \times 3\) ảnh đại diện cho toàn bộ phân phối chuẩn \(\mathcal{N}(\mathbf{0}, \mathbf{I}_2)\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Chọn 3 mức xác suất tích lũy đều nhau: \(p \in \{0{,}10;\; 0{,}50;\; 0{,}90\}\).&lt;/li&gt;
  &lt;li&gt;Tra hàm phân vị ngược (PPF) của phân phối chuẩn tắc \(\Phi^{-1}(p)\):
    &lt;ul&gt;
      &lt;li&gt;\(\Phi^{-1}(0{,}10) \approx -1{,}282\), \(\Phi^{-1}(0{,}50) = 0{,}000\), \(\Phi^{-1}(0{,}90) \approx +1{,}282\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Ghép thành 9 tọa độ \((z_1, z_2) \in \{-1{,}282, 0, +1{,}282\}^2\) và truyền qua bộ giải mã. Vì mọi điểm đều nằm trong vùng xác suất dày đặc mà phân kỳ KL đã kéo các đám mây huấn luyện về, cả 9 ô ảnh đều cho ra chữ số hợp lệ và biến hình liên tục theo hai trục!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nội dung về Variational Autoencoder gồm hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết&lt;/strong&gt; — mục tiêu ELBO, thủ thuật tái tham số hóa và trực giác không gian ẩn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt&lt;/strong&gt; — mã huấn luyện PyTorch, lấy mẫu, nội suy, bài báo nền tảng và các cạm bẫy thường gặp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, tiếng Anh. Tổng quan ngắn gọn trước khi đi vào phần lý thuyết và cài đặt chi tiết.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Trình bày cùng mô hình xác suất trong bối cảnh khóa học của MIT.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vPvnpC0PNVQ&quot;&gt;MaDL - Kullback-Leibler Divergence&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Giải thích số hạng phân kỳ KL giữ vai trò then chốt trong cả hai bài học.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>13-01-02 Cài đặt VAE</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter13/13_01_02_VAE_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter13/13_01_02_VAE_Implementation</id>
   <content type="html">&lt;p&gt;Chỉ một sai sót nhỏ về tỷ lệ cộng giữa hàm mất mát tái tạo (tính tổng trên \(784\) pixel) và phân kỳ KL (tính tổng trên \(20\) chiều ẩn) cũng đủ khiến VAE của bạn hoặc sụp đổ thành cục mờ, hoặc đánh mất hoàn toàn khả năng sinh ảnh mới. Trong bài cài đặt này, ta xây dựng trọn vẹn VAE trên MNIST bằng PyTorch — từ nhánh song song &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fc_mu&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fc_logvar&lt;/code&gt;, hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reparameterize&lt;/code&gt;, hàm mất mát ELBO cho đến kỹ thuật KL annealing và vẽ lưới ảnh sinh trong không gian ẩn 2D.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-các-thành-phần-kỹ-thuật-cốt-lõi-khi-lập-trình-vae&quot;&gt;Kiến thức cần nhớ: Các thành phần kỹ thuật cốt lõi khi lập trình VAE&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Dự đoán &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logvar&lt;/code&gt; thay vì &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;std&lt;/code&gt;:&lt;/strong&gt; Xuất ra \(\log(\sigma^2) \in (-\infty, +\infty)\) không bị ràng buộc dấu, rồi tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;std = torch.exp(0.5 * logvar)&lt;/code&gt; giúp ổn định số học và tránh đạo hàm nổ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cân bằng thang đo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reduction=&apos;sum&apos;&lt;/code&gt; trong hàm loss ELBO:&lt;/strong&gt; Cộng tổng BCE trên mọi pixel với tổng KL trên mọi chiều ẩn (rồi mới chia cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_size&lt;/code&gt;) — tránh bẫy dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reduction=&apos;mean&apos;&lt;/code&gt; làm suy yếu hệ số tái tạo đi \(784\) lần.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lấy mẫu mới và vẽ lưới đa tạp 2D:&lt;/strong&gt; Khi \(d = 2\), ánh xạ lưới phân vị hàm phân phối chuẩn ngược (PPF) qua bộ giải mã để nhìn thấy toàn bộ bản đồ chuyển dạng mượt mà giữa 10 chữ số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;KL Annealing và \(\beta\)-VAE:&lt;/strong&gt; Tăng dần trọng số \(\beta\) từ \(0 \to 1\) trong những epoch đầu để tránh posterior collapse, hoặc chọn \(\beta &amp;gt; 1\) để tách bạch các chiều thuộc tính.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-kiểm-tra-bẫy-reductionmean-vs-reductionsum-trong-hàm-loss-vae&quot;&gt;Giải thích: Kiểm tra bẫy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reduction=&apos;mean&apos;&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reduction=&apos;sum&apos;&lt;/code&gt; trong hàm loss VAE&lt;/h3&gt;

&lt;p&gt;Xét một ảnh MNIST (\(784\) pixel) với không gian ẩn \(d = 20\) chiều. Giả sử tại một bước huấn luyện, lỗi BCE trung bình mỗi pixel là \(0{,}25\) và phân kỳ KL trung bình mỗi chiều ẩn là \(0{,}50\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cách tính đúng chuẩn ELBO (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reduction=&apos;sum&apos;&lt;/code&gt; trên từng mẫu):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Tổng BCE tái tạo: \(784 \times 0{,}25 = 196{,}0\).&lt;/li&gt;
      &lt;li&gt;Tổng KL: \(20 \times 0{,}50 = 10{,}0\).&lt;/li&gt;
      &lt;li&gt;Tổng loss mỗi mẫu: \(196{,}0 + 10{,}0 = 206{,}0\) (tỷ lệ Tái tạo : KL = \(19{,}6 : 1\) — hợp lý vì 784 pixel chứa nhiều thông tin hơn 20 chiều ẩn).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bẫy thường gặp (dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;F.binary_cross_entropy(..., reduction=&apos;mean&apos;)&lt;/code&gt; cộng với tổng KL):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;BCE trung bình: \(0{,}25\).&lt;/li&gt;
      &lt;li&gt;Tổng KL: \(10{,}0\).&lt;/li&gt;
      &lt;li&gt;Tỷ lệ bị đảo ngược thành \(0{,}25 : 10{,}0 = 1 : 40\) — tương đương bạn vô tình chạy \(\beta\)-VAE với \(\beta = 784\)! Hậu quả: KL bị ép về \(0\) ngay lập tức và mọi ảnh sinh ra đều mờ nhạt giống hệt ảnh trung bình của tập dữ liệu.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-đoạn-mã&quot;&gt;4. Đoạn mã&lt;/h2&gt;

&lt;p&gt;Phần mã dưới đây cài đặt đầy đủ Variational Autoencoder bằng PyTorch trên tập MNIST, bao gồm bước tái tham số hóa, hàm mất mát ELBO, sinh mẫu và nội suy không gian ẩn:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VAE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Variational Autoencoder cho MNIST.
    
    Kiến trúc:
    - Encoder: ánh xạ ảnh sang tham số phân phối ẩn (μ, σ)
    - Sampler: reparameterization trick cho backpropagation qua lấy mẫu
    - Decoder: ánh xạ mã ẩn sang ảnh tái tạo
    
    Loss: ELBO = tái tạo + phân kỳ KL
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;VAE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Encoder: xuất tham số phân phối Gaussian
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Ta xuất cả μ và log(σ²) thay vì σ vì ổn định số
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# (σ phải dương, dễ đảm bảo hơn với exp(log σ²))
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tầng riêng cho mean và log-variance
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Cho phép encoder học cả hai độc lập
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc_mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc_logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Decoder: ánh xạ mã ẩn sang tái tạo
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Đầu ra trong [0,1] cho giá trị pixel
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Encode đầu vào sang tham số phân phối ẩn.
        
        Returns:
            mu: mean của q(z|x)
            logvar: log variance của q(z|x)
        
        Ta trả log variance thay vì variance/std vì ổn định số.
        Variance phải dương, nên ta đảm bảo bằng cách lũy thừa logvar.
        Ổn định hơn dự đoán trực tiếp σ rồi bình phương.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc_mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc_logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;reparameterize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Reparameterization trick: z = μ + σ⊙ε với ε ~ N(0,I)
        
        Đây là ĐỔI MỚI then chốt khiến VAE huấn luyện được bằng backprop.
        Thay vì lấy mẫu z ~ N(μ,σ²) (không khả vi theo μ,σ),
        ta biểu diễn z như hàm tất định của μ,σ và ngẫu nhiên ngoài ε.
        
        Gradient có thể chảy qua μ và σ tới tham số encoder, cho phép
        huấn luyện end-to-end qua backpropagation chuẩn.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Tính độ lệch chuẩn từ log variance
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# std = exp(log(σ²) / 2) = exp(logvar / 2)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lấy mẫu epsilon từ chuẩn chuẩn
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Khi huấn luyện: ngẫu nhiên. Khi sinh: có thể dùng ε cụ thể
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Mẫu reparameterized: z = μ + σ * ε
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Ánh xạ mã ẩn sang tái tạo&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Forward pass VAE đầy đủ.
        
        Returns:
            recon: đầu vào tái tạo
            mu: mean ẩn (cho tính KL)
            logvar: log-variance ẩn (cho tính KL)
        
        Ta trả mu và logvar riêng vì cần chúng để tính
        phân kỳ KL trong hàm loss.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reparameterize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Sinh mẫu mới bằng cách lấy mẫu từ prior và giải mã.
        
        Đây là cách ta dùng VAE đã huấn luyện để sinh:
        1. Lấy mẫu z ~ N(0, I) (prior)
        2. Giải mã để nhận x
        
        Vì ta đã chính quy hóa q(z|x) gần N(0,I) trong huấn luyện,
        mẫu từ N(0,I) nên giải mã ra đầu ra thực tế.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;vae_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Loss VAE: âm ELBO = mất mát tái tạo + phân kỳ KL
    
    Args:
        recon_x: đầu vào tái tạo
        x: đầu vào gốc
        mu: mean ẩn từ encoder
        logvar: log-variance ẩn từ encoder
        beta: trọng số hạng tử KL (β-VAE dùng β≠1 cho disentanglement)
    
    Loss có hai hạng tử:
    1. Tái tạo: ta tái tạo đầu vào tốt thế nào
    2. KL: phân phối encoder khác prior bao nhiêu
    
    Ta muốn tối thiểu hóa cả hai: tái tạo tốt VÀ phân phối ẩn
    gần prior.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Mất mát tái tạo (binary cross-entropy cho ảnh trong [0,1])
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Coi mỗi pixel như Bernoulli độc lập
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;BCE&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binary_cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reduction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Phân kỳ KL KL(N(μ,σ²) \| N(0,I))
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Có dạng đóng: 0.5 * Σ(μ² + σ² - log(σ²) - 1)
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Ta có logvar = log(σ²), nên σ² = exp(logvar)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;KLD&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tổng loss (âm ELBO)
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Tối thiểu hóa điều này tương đương tối đa hóa ELBO
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;BCE&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;KLD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;BCE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;KLD&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện VAE
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện Variational Autoencoder trên MNIST&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tải dữ liệu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ToTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo VAE
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VAE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kiến trúc VAE:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Chiều đầu vào: 784 (28×28)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Chiều ẩn: 20 (hệ số nén: 39×)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tổng tham số: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vòng huấn luyện
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện VAE...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_bce&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_kld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Làm phẳng ảnh
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính loss
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;vae_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;train_bce&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;train_kld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kld&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Trung bình trên các batch
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;n_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Mỗi mẫu
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;avg_bce&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_bce&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;avg_kld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_kld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Recon = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_bce&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, KL = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_kld&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện VAE Hoàn tất - Phân tích Kết quả&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra tái tạo
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Encode (dùng mean, bỏ qua phương sai cho tính tất định)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tái tạo
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Đo lỗi tái tạo
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;recon_error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MSE tái tạo kiểm tra: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_error&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Phân tích thống kê không gian ẩn
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Thống kê không gian ẩn (nên ~N(0,1) do phạt KL):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (5 chiều đầu)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Std:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Magnitude mean tổng thể: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Std tổng thể: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh mẫu mới
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sinh Mẫu Mới từ VAE&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Lấy mẫu từ prior N(0,I)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đã sinh &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; mẫu bằng cách lấy mẫu z ~ N(0,I)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape mẫu: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (64, 784)
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Kiểm tra thống kê mẫu
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean mẫu sinh: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (nên ~0.5)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Std mẫu sinh: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Reshape để trực quan hóa
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;samples_img&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Reshape để trực quan hóa: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Minh họa nội suy
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nội suy Không gian Ẩn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Lấy hai ảnh kiểm tra
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;img1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;img2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Encode sang mean ẩn
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mu1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mu2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nội suy giữa hai ảnh trong không gian ẩn:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Nội suy
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;img_interp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# In mỗi bước khác
&lt;/span&gt;            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  t=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Ảnh nội suy &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nội suy nên mượt nhờ chính quy hóa không gian ẩn!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đây là lợi thế then chốt của VAE so với autoencoder vanilla.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Minh họa β-VAE (thay đổi trọng số KL)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β-VAE: Điều khiển Disentanglement&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bằng cách thay đổi β (trọng số hạng tử KL), ta điều khiển đánh đổi:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  β &amp;lt; 1: Ưu tiên tái tạo (sắc nét hơn nhưng ít disentangled)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  β = 1: VAE chuẩn (cân bằng)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  β &amp;gt; 1: Ưu tiên tính đều đặn ẩn (disentangled hơn, mờ hơn)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β-VAE với β=4-10 thường học chiều ẩn diễn giải được hơn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;nơi mỗi chiều nắm một nhân tố ngữ nghĩa (kích thước, xoay, v.v.)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-các-khái-niệm-liên-quan&quot;&gt;5. Các khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;So sánh giữa VAE và autoencoder chuẩn làm rõ giá trị của khung xác suất. Cả hai đều dùng kiến trúc encoder–decoder và hàm mất mát tái tạo, nhưng VAE bổ sung ba điểm cốt lõi: (1) mã hóa thành phân phối xác suất thay vì điểm tất định, (2) thành phần chính quy hóa phân kỳ KL kéo không gian ẩn về gần phân phối tiên nghiệm, và (3) cơ chế lấy mẫu tường minh để sinh dữ liệu mới. Nhờ tối ưu cận dưới log-hợp lý, VAE mang lại nền tảng xác suất rõ ràng hơn so với autoencoder chỉ tối ưu sai số tái tạo.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;VAE gắn chặt với suy diễn biến phân trong thống kê Bayes. Khi có mô hình \(p(\mathbf{x}, \mathbf{z})\) nhưng không tính trực tiếp được hậu nghiệm $$p(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(, ta xấp xỉ nó bằng phân phối\)q(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(thuộc họ dễ tính toán (như phân phối chuẩn độc lập theo từng chiều) và tối đa hóa ELBO. VAE mở rộng phương pháp này lên dữ liệu nhiều chiều nhờ ba yếu tố: dùng mạng nơ-ron biểu diễn\)q\(và\)p$$, áp dụng thủ thuật tái tham số hóa để tối ưu bằng gradient và huấn luyện ngẫu nhiên theo mini-batch.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Từ góc độ lý thuyết thông tin, ELBO có thể viết dưới dạng:&lt;/p&gt;

\[\text{ELBO} = \mathbb{E}_{q_\phi(\mathbf{z}|\mathbf{x})}[\log p_\theta(\mathbf{x}|\mathbf{z})] - KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z}))\]

\[= -H_{q_\phi}(p_\theta(\mathbf{x}|\mathbf{z})) - KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z}))\]

&lt;p&gt;Số hạng đầu tiên thúc đẩy bộ giải mã tái tạo chính xác (độ bất định có điều kiện thấp), còn số hạng KL đo lượng thông tin cần mã hóa để chuyển từ phân phối tiên nghiệm \(p\) sang hậu nghiệm \(q_\phi\). Sự đánh đổi giữa độ trung thực tái tạo và mức độ nén này được điều khiển tường minh trong \(\beta\)-VAE thông qua hệ số \(\beta\).&lt;/p&gt;

&lt;p&gt;Đặt cạnh &lt;em&gt;normalizing flows&lt;/em&gt;, cả hai họ đều dùng biến ẩn \(\mathbf{z}\) nhưng đánh đổi khác nhau: normalizing flows sử dụng phép biến đổi song ánh khả nghịch có định thức Jacobian tính được nên cho log-hợp lý chính xác nhưng bị ràng buộc về kiến trúc; ngược lại, VAE cho phép thiết kế mạng encoder và decoder tự do nhưng chỉ tối ưu cận dưới xấp xỉ ELBO.&lt;/p&gt;

&lt;p&gt;Cuối cùng, VAE liên hệ mật thiết với học biểu diễn tách nhân tố (&lt;em&gt;disentangled representation learning&lt;/em&gt;), nơi mỗi chiều ẩn tương ứng với một thuộc tính độc lập (như tư thế, ánh sáng, hình dạng). Hậu nghiệm chuẩn độc lập theo từng chiều và việc tăng trọng số \(\beta &amp;gt; 1\) trong \(\beta\)-VAE khuyến khích sự độc lập giữa các chiều ẩn, giúp biểu diễn dễ diễn giải và thuận tiện hơn cho các tác vụ về sau.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.6114&quot;&gt;“Auto-Encoding Variational Bayes” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Diederik P. Kingma, Max Welling&lt;br /&gt;
Bài báo đề xuất VAE và đưa suy diễn biến phân vào thực hành học sâu nhờ thủ thuật tái tham số hóa \(\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon}\) với \(\boldsymbol{\epsilon} \sim \mathcal{N}(0,I)\). Nhóm tác giả trình bày đầy đủ phép suy ELBO, công thức KL dạng đóng cho phân phối chuẩn và kết quả thực nghiệm trên ảnh, mở ra một hướng mô hình sinh ổn định và có cơ sở xác suất rõ ràng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1606.05908&quot;&gt;“Tutorial on Variational Autoencoders” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Carl Doersch&lt;br /&gt;
Bài hướng dẫn trình bày trực quan ý nghĩa của ELBO, thủ thuật tái tham số hóa cùng các lưu ý thực hành khi huấn luyện VAE cho người đọc chưa có nền tảng sâu về suy diễn biến phân. Tài liệu giải đáp nhiều câu hỏi phổ biến về hậu nghiệm chuẩn, cấu trúc không gian ẩn và mối liên hệ giữa VAE với autoencoder và GAN.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://openreview.net/forum?id=Sy2fzU9gl&quot;&gt;“β-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Irina Higgins, Loic Matthey, Arka Pal, Christopher Burgess, Xavier Glorot, Matthew Botvinick, Shakir Mohamed, Alexander Lerchner&lt;br /&gt;
Bài báo giới thiệu \(\beta\)-VAE bằng cách nhân số hạng KL với trọng số \(\beta &amp;gt; 1\). Phạt KL mạnh hơn khuyến khích các chiều ẩn độc lập với nhau, giúp tách riêng các nhân tố biến thiên như hình dạng, kích thước, góc xoay hay màu sắc vào từng chiều riêng biệt và cho phép điều chỉnh từng thuộc tính khi sinh mẫu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1509.00519&quot;&gt;“Importance Weighted Autoencoders” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Yuri Burda, Roger Grosse, Ruslan Salakhutdinov&lt;br /&gt;
Bài báo cải thiện cận dưới ELBO bằng kỹ thuật lấy mẫu trọng số quan trọng (&lt;em&gt;importance sampling&lt;/em&gt;) trên \(K\) mẫu từ \(q_\phi(\mathbf{z}|\mathbf{x})\):&lt;/p&gt;

\[\mathcal{L}_{\text{IWAE}} = \mathbb{E}\left[\log \frac{1}{K}\sum_{k=1}^K \frac{p_\theta(\mathbf{x}, \mathbf{z}^{(k)})}{q_\phi(\mathbf{z}^{(k)}|\mathbf{x})}\right]\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Cận dưới này chặt hơn ELBO chuẩn và tiến tới log-hợp lý thật khi \(K \to \infty\), thường giúp cải thiện chất lượng mô hình sinh $$p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})$$.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1906.00446&quot;&gt;“Generating Diverse High-Fidelity Images with VQ-VAE-2” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ali Razavi, Aaron van den Oord, Oriol Vinyals&lt;br /&gt;
Bài báo giới thiệu VQ-VAE-2 sử dụng mã ẩn rời rạc thông qua lượng tử hóa vector (&lt;em&gt;vector quantization&lt;/em&gt;) kết hợp kiến trúc phân cấp cho cấu trúc toàn cục và cục bộ. Biểu diễn rời rạc cho phép huấn luyện phân phối tiên nghiệm tự hồi quy mạnh trên không gian mã ẩn, giúp nâng chất lượng ảnh độ phân giải cao ngang tầm GAN trong khi vẫn duy trì quá trình huấn luyện ổn định.&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo&quot;&gt;Bẫy thường gặp và Mẹo&lt;/h2&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Hiện tượng thất bại phổ biến nhất khi huấn luyện VAE là &lt;strong&gt;sụp đổ hậu nghiệm (&lt;em&gt;posterior collapse&lt;/em&gt;)&lt;/strong&gt;, khi bộ mã hóa bỏ qua đầu vào và luôn xuất ra gần đúng phân phối tiên nghiệm $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x}) \approx p(\mathbf{z}) = \mathcal{N}(0,I)\(cho mọi\)\mathbf{x}\(. Khi đó phân kỳ KL tiến về 0, còn bộ giải mã chỉ học tái tạo ảnh trung bình của toàn bộ tập dữ liệu vì mã ẩn không chứa thông tin về đầu vào. Hiện tượng này thường xảy ra khi bộ giải mã quá mạnh và tự tái tạo được khá tốt mà không cần đến\)\mathbf{z}$$.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Các biện pháp khắc phục gồm: (1) giảm dung lượng bộ giải mã để buộc nó phụ thuộc vào mã ẩn; (2) áp dụng &lt;em&gt;KL annealing&lt;/em&gt; — bắt đầu với \(\beta = 0\) rồi tăng dần lên \(\beta = 1\) để bộ mã hóa kịp học biểu diễn hữu ích trước khi siết chính quy hóa; (3) dùng kỹ thuật &lt;em&gt;free bits&lt;/em&gt; — chỉ phạt KL khi vượt qua một ngưỡng tối thiểu trên mỗi chiều ẩn; và (4) dùng learning rate lớn hơn cho bộ mã hóa so với bộ giải mã.&lt;/p&gt;

&lt;p&gt;Việc chọn số chiều ẩn cần cân bằng giữa độ chi tiết tái tạo và khả năng diễn giải. Chiều ẩn lớn giúp tái tạo tốt hơn nhưng các chiều dễ tương quan với nhau; chiều ẩn nhỏ tăng áp lực nén và dễ tách nhân tố hơn nhưng có thể bỏ sót chi tiết. Thông thường, 10–20 chiều phù hợp cho MNIST và 64–256 chiều cho tập ảnh khuôn mặt như CelebA.&lt;/p&gt;

&lt;p&gt;Trong \(\beta\)-VAE, hệ số \(\beta\) điều chỉnh trực tiếp sự cân bằng: \(\beta = 1\) là VAE chuẩn; \(\beta &amp;gt; 1\) (khoảng 2–10) ưu tiên tách nhân tố phục vụ diễn giải và điều khiển thuộc tính; còn \(\beta &amp;lt; 1\) (khoảng 0,1–0,5) ưu tiên độ sắc nét tái tạo.&lt;/p&gt;

&lt;p&gt;Để giảm độ mờ của ảnh sinh ra, có thể thay phân phối đầu ra Gaussian/Bernoulli đơn giản bằng hỗn hợp logistic rời rạc hóa hoặc bộ giải mã tự hồi quy (dù tốc độ giải mã sẽ chậm hơn). Cuối cùng, khi lấy đặc trưng ẩn của VAE cho các tác vụ sau như phân loại hay phân cụm, dùng trực tiếp vector trung bình \(\boldsymbol{\mu}\) thường ổn định hơn, trong khi lấy mẫu từ \(\mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\sigma}^2)\) phù hợp hơn khi cần phản ánh độ bất định.&lt;/p&gt;

&lt;h2 id=&quot;điểm-then-chốt&quot;&gt;Điểm then chốt&lt;/h2&gt;

&lt;p&gt;Variational Autoencoder kết hợp mạng nơ-ron với suy diễn biến phân để xây dựng mô hình sinh xác suất tối ưu cận dưới ELBO của log-hợp lý. Bộ mã hóa ánh xạ đầu vào sang tham số của phân phối chuẩn trong không gian ẩn, thủ thuật tái tham số hóa cho phép lan truyền ngược qua bước lấy mẫu, và bộ giải mã khôi phục dữ liệu từ mã ẩn. Thành phần phân kỳ KL giữ cho không gian ẩn liên tục, đầy đủ và bám sát phân phối tiên nghiệm để hỗ trợ lấy mẫu và nội suy mượt. So với GAN, VAE huấn luyện ổn định hơn và có khung xác suất rõ ràng, dù ảnh sinh ra thường kém sắc nét hơn nếu dùng hàm mất mát tái tạo đơn giản.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, tiếng Anh. Minh họa luồng tính toán mà mã nguồn cài đặt: mã hóa, tái tham số hóa rồi giải mã.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Phân tích các vấn đề thực tế khi huấn luyện như sụp đổ hậu nghiệm và ảnh mờ.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vPvnpC0PNVQ&quot;&gt;MaDL - Kullback-Leibler Divergence&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Hỗ trợ kiểm tra lại công thức KL khi hàm mất mát có dấu hiệu bất thường.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>13-01-01 Lý thuyết VAE</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter13/13_01_01_VAE_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter13/13_01_01_VAE_Theory</id>
   <content type="html">&lt;p&gt;Tại sao không thể trực tiếp tối đa hóa \(\log p_\theta(\mathbf{x}) = \log \int p_\theta(\mathbf{x}\mid\mathbf{z})p(\mathbf{z})\,d\mathbf{z}\) bằng hạ gradient? Bởi với không gian ẩn 64 chiều, tích phân kia đòi hỏi lấy mẫu qua một thể tích khổng lồ mà hầu hết các điểm đều cho \(p_\theta(\mathbf{x}\mid\mathbf{z}) \approx 0\). Bài lý thuyết này dẫn bạn từng bước qua bất đẳng thức Jensen để dựng nên &lt;strong&gt;ELBO&lt;/strong&gt; và giải mã vẻ đẹp đại số của &lt;strong&gt;Reparameterization Trick&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cấu-trúc-toán-học-của-suy-diễn-biến-phân-trong-vae&quot;&gt;Kiến thức cần nhớ: Cấu trúc toán học của suy diễn biến phân trong VAE&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bất đẳng thức Jensen và khai triển ELBO:&lt;/strong&gt; Biến đổi \(\log p_\theta(\mathbf{x}) = \text{ELBO}(\theta, \phi; \mathbf{x}) + D_{\text{KL}}(q_\phi(\mathbf{z}\mid\mathbf{x}) \| p_\theta(\mathbf{z}\mid\mathbf{x}))\), chứng minh cực đại hóa ELBO vừa nâng log-hợp lý vừa ép \(q_\phi\) tiến sát hậu nghiệm thật.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Công thức KL dạng đóng giữa hai phân phối chuẩn:&lt;/strong&gt; Chứng minh tích phân KL rút gọn thành biểu thức đại số \(\frac{1}{2}\sum_j (\mu_j^2 + \sigma_j^2 - \ln\sigma_j^2 - 1)\) không cần xấp xỉ Monte Carlo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thủ thuật tái tham số hóa:&lt;/strong&gt; Chuyển \(\mathbf{z} \sim \mathcal{N}(\boldsymbol{\mu}, \text{diag}(\boldsymbol{\sigma}^2))\) thành \(\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon}\) để \(\nabla_\phi \mathbb{E}_{q_\phi}[f(\mathbf{z})]\) có phương sai thấp và tính được trực tiếp bằng autograd.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lựa chọn phân phối đầu ra và hiện tượng Posterior Collapse:&lt;/strong&gt; Hiểu mối liên hệ giữa Gaussian decoder (MSE) vs. Bernoulli decoder (BCE), và lý do bộ giải mã quá mạnh có thể phớt lờ biến ẩn \(\mathbf{z}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-gradient-qua-nút-reparameterization-trick&quot;&gt;Giải thích: Tính tay gradient qua nút Reparameterization Trick&lt;/h3&gt;

&lt;p&gt;Giả sử hàm mất mát tái tạo phụ thuộc vào biến ẩn 1 chiều theo dạng \(\mathcal{L}_{\text{rec}}(z) = (z - 2{,}0)^2\). Tại một bước huấn luyện, bộ mã hóa xuất ra \(\mu = 0{,}5\) và \(\log(\sigma^2) = 0{,}0\) (suy ra \(\sigma = e^{0/2} = 1{,}0\)). Ta rút một mẫu nhiễu chuẩn \(\epsilon = 0{,}8\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lượt xuôi tái tham số hóa:&lt;/strong&gt;
\(z = \mu + \sigma \cdot \epsilon = 0{,}5 + 1{,}0 \times 0{,}8 = 1{,}3.\)
\(\mathcal{L}_{\text{rec}} = (1{,}3 - 2{,}0)^2 = (-0{,}7)^2 = 0{,}49.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lượt ngược theo \(\mu\) và \(\log(\sigma^2)\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Đạo hàm theo \(z\): \(\frac{\partial \mathcal{L}_{\text{rec}}}{\partial z} = 2(z - 2{,}0) = 2(-0{,}7) = -1{,}4\).&lt;/li&gt;
      &lt;li&gt;Vì \(\frac{\partial z}{\partial \mu} = 1\), ta có: \(\frac{\partial \mathcal{L}_{\text{rec}}}{\partial \mu} = -1{,}4 \times 1 = -1{,}4\).&lt;/li&gt;
      &lt;li&gt;Vì \(\sigma = \exp\left(\tfrac{1}{2}\log\sigma^2\right)\) nên \(\frac{\partial z}{\partial (\log\sigma^2)} = \frac{1}{2}\sigma\epsilon = 0{,}5(1{,}0)(0{,}8) = 0{,}4\).&lt;/li&gt;
      &lt;li&gt;Do đó: \(\frac{\partial \mathcal{L}_{\text{rec}}}{\partial (\log\sigma^2)} = -1{,}4 \times 0{,}4 = -0{,}56\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhận xét:&lt;/strong&gt; Nhờ biến \(\epsilon = 0{,}8\) đóng vai trò như một hằng số đầu vào trong đồ thị tính toán, PyTorch dễ dàng truyền đạo hàm \(-1{,}4\) và \(-0{,}56\) thẳng về các tầng Encoder!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;variational-autoencoder-mô-hình-sinh-xác-suất&quot;&gt;Variational Autoencoder: Mô hình Sinh Xác suất&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://lilianweng.github.io/posts/2018-08-12-vae/vae-gaussian.png&quot; alt=&quot;VAE Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc VAE với phân phối xác suất trong không gian ẩn. Nguồn: Lilian Weng’s Blog&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Variational Autoencoder (VAE) kết hợp suy diễn biến phân (&lt;em&gt;variational inference&lt;/em&gt;) trong thống kê với mạng nơ-ron sâu để xây dựng một khung xác suất chặt chẽ cho mô hình hóa sinh. Trong khi autoencoder chuẩn học phép mã hóa và giải mã tất định nhằm tối ưu tái tạo, VAE học các phân phối xác suất trên biến ẩn và dữ liệu, nhờ đó có thể sinh mẫu mới bằng cách lấy mẫu từ không gian ẩn. Cách tiếp cận này khắc phục hạn chế chính của autoencoder chuẩn: thay vì để không gian ẩn xuất hiện các khoảng trống không ánh xạ tới mẫu hợp lệ nào, VAE chính quy hóa phân phối ẩn để không gian này liên tục và phủ đều quanh phân phối tiên nghiệm.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Cơ sở vận hành của VAE là cận dưới bằng chứng (&lt;em&gt;Evidence Lower Bound&lt;/em&gt; — ELBO), một mục tiêu có thể tính toán và tối ưu được, đóng vai trò cận dưới cho log-hợp lý biên vốn không thể tính trực tiếp. Việc đánh giá \(\log p(\mathbf{x})\) trong mô hình biến ẩn đòi hỏi lấy tích phân trên toàn bộ không gian biến ẩn liên tục \(\mathbf{z}\), điều không khả thi với bộ giải mã là mạng nơ-ron phi tuyến. VAE giải quyết bằng cách đưa vào mạng nhận diện (bộ mã hóa) để xấp xỉ phân phối hậu nghiệm thật $$p(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})$$ rồi tối đa hóa ELBO. Bộ mã hóa xấp xỉ hậu nghiệm thật càng tốt thì cận dưới ELBO càng sát với log-hợp lý thật.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Để huấn luyện VAE hiệu quả, một số thành phần phối hợp chặt chẽ với nhau. Thủ thuật tái tham số hóa (&lt;em&gt;reparameterization trick&lt;/em&gt;) cho phép lan truyền ngược gradient qua bước lấy mẫu ngẫu nhiên, biến bài toán tối ưu trở lại dạng giải được bằng hạ gradient thông thường. Thành phần phân kỳ KL giữa hậu nghiệm xấp xỉ và phân phối tiên nghiệm đóng vai trò chính quy hóa, ngăn không gian ẩn phân mảnh thành các cụm rời rạc và tạo tính mượt phục vụ nội suy. Bộ mã hóa và bộ giải mã được huấn luyện đồng thời theo cùng mục tiêu ELBO.&lt;/p&gt;

&lt;p&gt;Khung VAE mang tính tổng quát cao: cùng cấu trúc encoder–phân phối ẩn–decoder và mục tiêu ELBO có thể áp dụng cho ảnh, văn bản, âm thanh hoặc dữ liệu chuỗi khi chọn kiến trúc và phân phối đầu ra phù hợp. Không gian ẩn của VAE thường liên tục (các điểm gần nhau giải mã ra đầu ra tương đồng), đầy đủ (vùng lấy mẫu cho đầu ra hợp lệ) và có thể diễn giải theo từng nhân tố biến thiên (như góc nhìn, màu sắc, hình dạng).&lt;/p&gt;

&lt;p&gt;Dù vậy, VAE cũng có những giới hạn đặc trưng. Ảnh sinh từ VAE thường mờ hơn so với GAN do đặc tính trung bình hóa của hàm mất mát tái tạo (như MSE với giả định Gaussian). Phân phối tiên nghiệm đơn giản (thường là chuẩn tắc) đôi khi không khớp hoàn toàn với phân phối hậu nghiệm tổng hợp của dữ liệu, tạo khoảng cách khi lấy mẫu. Vì vậy, VAE phù hợp khi cần huấn luyện ổn định, không gian ẩn mượt để nội suy và có cận dưới xác suất rõ ràng; còn khi ưu tiên tối đa độ sắc nét của mẫu, GAN hoặc mô hình khuếch tán thường được cân nhắc hơn.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Cơ sở toán học của VAE bắt nguồn từ suy diễn biến phân trong thống kê Bayes nhằm xấp xỉ các phân phối hậu nghiệm không thể tính trực tiếp.&lt;/p&gt;

&lt;p&gt;Giả sử dữ liệu \(\mathbf{x}\) được sinh từ biến ẩn \(\mathbf{z}\) qua quá trình xác suất:&lt;/p&gt;

&lt;p&gt;\(\mathbf{z} \sim p(\mathbf{z})\) (phân phối tiên nghiệm đơn giản, thường là chuẩn tắc)&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;$$\mathbf{x} \sim p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})\((phân phối dữ liệu có điều kiện, tham số hóa bởi mạng nơ-ron\)\theta$$)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Hàm hợp lý biên của dữ liệu là:&lt;/p&gt;

\[p_\theta(\mathbf{x}) = \int p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z}) d\mathbf{z}\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Với \(\mathbf{z}\) liên tục và bộ giải mã phi tuyến $$p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})$$, tích phân này không tính được trực tiếp nên không thể tối ưu hợp lý cực đại theo cách thông thường.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Suy diễn biến phân đưa vào phân phối hậu nghiệm xấp xỉ $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\((bộ mã hóa có tham số\)\phi$$) để suy ra cận dưới cho log-hợp lý:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[\log p_\theta(\mathbf{x}) = \log \int p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z}) d\mathbf{z}\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Nhân và chia biểu thức trong tích phân với $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})$$:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[= \log \int q_\phi(\mathbf{z}|\mathbf{x}) \frac{p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})} d\mathbf{z}\]

\[= \log \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}\left[\frac{p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})}\right]\]

&lt;p&gt;Áp dụng bất đẳng thức Jensen (vì hàm \(\log\) là hàm lõm):&lt;/p&gt;

\[\geq \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}\left[\log \frac{p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})}\right]\]

&lt;p&gt;Tách thành hai số hạng:&lt;/p&gt;

\[= \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}[\log p_\theta(\mathbf{x}|\mathbf{z})] - \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}\left[\log \frac{q_\phi(\mathbf{z}|\mathbf{x})}{p(\mathbf{z})}\right]\]

\[= \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}[\log p_\theta(\mathbf{x}|\mathbf{z})] - KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z}))\]

&lt;p&gt;Biểu thức thu được là cận dưới ELBO. Số hạng thứ nhất đo chất lượng tái tạo \(\mathbf{x}\) từ mã ẩn lấy mẫu bởi bộ mã hóa; số hạng thứ hai là phân kỳ KL giữa hậu nghiệm xấp xỉ và phân phối tiên nghiệm, đóng vai trò chính quy hóa.&lt;/p&gt;

&lt;p&gt;Khác với \(\log p_\theta(\mathbf{x})\), ELBO có thể ước lượng bằng phương pháp Monte Carlo:&lt;/p&gt;

\[\mathcal{L}(\theta, \phi; \mathbf{x}) \approx \frac{1}{L}\sum_{l=1}^L \log p_\theta(\mathbf{x}|\mathbf{z}^{(l)}) - KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z}))\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;với $$\mathbf{z}^{(l)} \sim q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(. Trong thực tế khi huấn luyện theo mini-batch,\)L=1$$ thường đã đủ để ước lượng gradient không chệch.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;thủ-thuật-tái-tham-số-hóa-reparameterization-trick&quot;&gt;Thủ thuật tái tham số hóa (&lt;em&gt;Reparameterization Trick&lt;/em&gt;)&lt;/h3&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Để tối ưu ELBO bằng hạ gradient, ta cần tính đạo hàm theo \(\phi\) trong khi $$\mathbf{z} \sim q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(là phép lấy mẫu ngẫu nhiên không khả vi trực tiếp theo\)\phi$$.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Với hậu nghiệm xấp xỉ dạng chuẩn $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x}) = \mathcal{N}(\boldsymbol{\mu}&lt;em&gt;\phi(\mathbf{x}), \boldsymbol{\sigma}^2&lt;/em&gt;\phi(\mathbf{x}))\(, thay vì lấy mẫu trực tiếp từ phân phối phụ thuộc\)\phi$$, ta tách phần ngẫu nhiên ra ngoài:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ol&gt;
  &lt;li&gt;Lấy mẫu \(\boldsymbol{\epsilon} \sim \mathcal{N}(0, I)\) từ phân phối cố định không chứa tham số.&lt;/li&gt;
  &lt;li&gt;Tính \(\mathbf{z} = \boldsymbol{\mu}_\phi(\mathbf{x}) + \boldsymbol{\sigma}_\phi(\mathbf{x}) \odot \boldsymbol{\epsilon}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Khi đó \(\mathbf{z}\) vẫn có đúng phân phối $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(, nhưng trở thành hàm tất định khả vi theo\)\boldsymbol{\mu}&lt;em&gt;\phi\(và\)\boldsymbol{\sigma}&lt;/em&gt;\phi\(, cho phép lan truyền ngược gradient trực tiếp về tham số\)\phi$$ của bộ mã hóa.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Khi cả $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(và\)p(\mathbf{z})$$ đều là phân phối chuẩn (với tiên nghiệm chuẩn tắc), phân kỳ KL có công thức dạng đóng:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z})) = KL(\mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\sigma}^2) \| \mathcal{N}(0, I))\]

\[= \frac{1}{2}\sum_{j=1}^{J} \left(\mu_j^2 + \sigma_j^2 - \log \sigma_j^2 - 1\right)\]

&lt;p&gt;trong đó \(J\) là số chiều không gian ẩn. Công thức đóng này giúp tính chính xác số hạng KL mà không cần lấy mẫu, làm giảm phương sai khi huấn luyện.&lt;/p&gt;

&lt;p&gt;Hàm mục tiêu VAE đầy đủ cho một mẫu dữ liệu là:&lt;/p&gt;

\[\mathcal{L}_{\text{VAE}}(\theta, \phi; \mathbf{x}) = \mathbb{E}_{\boldsymbol{\epsilon} \sim \mathcal{N}(0,I)}[\log p_\theta(\mathbf{x}|\boldsymbol{\mu}_\phi(\mathbf{x}) + \boldsymbol{\sigma}_\phi(\mathbf{x}) \odot \boldsymbol{\epsilon})] - \frac{1}{2}\sum_{j=1}^{J} (\mu_j^2 + \sigma_j^2 - \log \sigma_j^2 - 1)\]

&lt;p&gt;Huấn luyện VAE tương đương với tối đa hóa biểu thức này (hoặc tối thiểu hóa giá trị âm của nó).&lt;/p&gt;

&lt;h3 id=&quot;phân-phối-đầu-ra-của-bộ-giải-mã&quot;&gt;Phân phối đầu ra của bộ giải mã&lt;/h3&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Dạng của $$p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})$$ quyết định trực tiếp hàm mất mát tái tạo:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Hợp lý Gaussian:&lt;/strong&gt; $$p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z}) = \mathcal{N}(\mathbf{x}; \boldsymbol{\mu}_\theta(\mathbf{z}), \sigma^2 I)$$.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Âm log-hợp lý tỷ lệ với MSE: $$-\log p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z}) \propto |\mathbf{x} - \boldsymbol{\mu}_\theta(\mathbf{z})|^2$$.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Hợp lý Bernoulli&lt;/strong&gt; (phù hợp cho ảnh nhị phân hoặc chuẩn hóa trong [0, 1]): mỗi điểm ảnh tuân theo phân phối Bernoulli độc lập với xác suất \(\hat{x}_i\) từ bộ giải mã.&lt;br /&gt;
Âm log-hợp lý là binary cross-entropy: \(-\log p_\theta(\mathbf{x}|\mathbf{z}) = -\sum_i [x_i \log \hat{x}_i + (1-x_i)\log(1-\hat{x}_i)]\).&lt;/p&gt;

&lt;p&gt;Bộ giải mã xuất ra tham số của phân phối (giá trị trung bình đối với Gaussian hoặc xác suất đối với Bernoulli); khi hiển thị mẫu sinh ra, ta thường lấy trực tiếp giá trị trung bình này để ảnh ít nhiễu hơn.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;p&gt;Xét một mô hình VAE huấn luyện trên MNIST với không gian ẩn 20 chiều.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Trong quá trình huấn luyện, với mỗi ảnh chữ số “3”, bộ mã hóa tạo ra một phân phối chuẩn $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x}) = \mathcal{N}(\boldsymbol{\mu}&lt;em&gt;\phi(\mathbf{x}), \boldsymbol{\sigma}^2&lt;/em&gt;\phi(\mathbf{x}))\(trong không gian ẩn. Thành phần phạt KL kéo các phân phối này về gần\)\mathcal{N}(0, I)$$ và ngăn chúng suy biến thành các điểm rời rạc không có phương sai. Kết quả là các biến thể của chữ số “3” (nét dày, mảnh, nghiêng) ánh xạ thành các phân phối chồng lấn nhau trong cùng một vùng quanh gốc tọa độ; tương tự cho chữ số “8”, “1” và các chữ số khác. Nhờ vậy, không gian ẩn có ranh giới chuyển tiếp mượt và ít khoảng trống.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Khi sinh mẫu mới, ta chỉ cần lấy mẫu \(\mathbf{z} \sim \mathcal{N}(0, I)\) — một vector gồm 20 số ngẫu nhiên chuẩn tắc — rồi đưa qua bộ giải mã \(\hat{\mathbf{x}} = \text{decoder}_\theta(\mathbf{z})\). Nếu \(\mathbf{z}\) rơi vào vùng tương ứng với chữ số “3”, bộ giải mã sẽ tạo ra một ảnh chữ số “3” mới theo các đặc trưng đã học. Tuy nhiên, VAE tiêu chuẩn không cho phép chọn trực tiếp lớp cần sinh trừ khi ta bổ sung điều kiện nhãn (Conditional VAE) hoặc xác định trước vùng lớp trong không gian ẩn.&lt;/p&gt;

&lt;p&gt;Phép nội suy trong không gian ẩn của VAE cũng ổn định hơn autoencoder chuẩn. Sau khi mã hóa hai ảnh để lấy hai vector trung bình \(\boldsymbol{\mu}_1\) và \(\boldsymbol{\mu}_2\), ta tính:&lt;/p&gt;

\[\mathbf{z}_t = (1-t)\boldsymbol{\mu}_1 + t\boldsymbol{\mu}_2, \quad t \in [0,1]\]

&lt;p&gt;và giải mã từng \(\mathbf{z}_t\) để thu được chuỗi ảnh chuyển tiếp mượt giữa hai chữ số.&lt;/p&gt;

&lt;p&gt;Vai trò của số hạng KL có thể thấy rõ hơn qua phép phân rã:&lt;/p&gt;

\[KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z})) = -H(q_\phi(\mathbf{z}|\mathbf{x})) + H(q_\phi(\mathbf{z}|\mathbf{x}), p(\mathbf{z}))\]

&lt;p&gt;Số hạng thứ nhất khuyến khích entropy của \(q_\phi\) đủ lớn để bộ mã hóa không suy biến thành ánh xạ tất định; số hạng thứ hai (entropy chéo giữa \(q_\phi\) và \(p\)) kéo phân phối mã ẩn về gần phân phối tiên nghiệm \(p(\mathbf{z})\) sao cho quá trình lấy mẫu khi sinh khớp với phân phối đã học.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, tiếng Anh. Giải thích rõ vai trò của bộ mã hóa (hậu nghiệm xấp xỉ), bộ giải mã (hàm hợp lý) và mục tiêu ELBO.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vPvnpC0PNVQ&quot;&gt;MaDL - Kullback-Leibler Divergence&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Phân tích chi tiết số hạng chính quy hóa \(KL(q \| p)\) trong ELBO.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Một cách trình bày khác giúp củng cố bước tái tham số hóa.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>13 Variational Autoencoder (VAE)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter13/13_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter13/13_00_Introduction</id>
   <content type="html">&lt;p&gt;Ở chương trước, ta đã chứng kiến Autoencoder nén dữ liệu tuyệt vời đến đâu — nhưng hễ ta chọn một điểm ngẫu nhiên giữa hai cụm mã ẩn, bộ giải mã lại nhả ra những mảng nhiễu kỳ dị. Năm 2013, Diederik Kingma và Max Welling đã giải quyết trọn vẹn bài toán này bằng một ý tưởng đẹp đến ngỡ ngàng: thay vì ép mỗi bức ảnh vào một &lt;em&gt;chấm cố định&lt;/em&gt; trong không gian ẩn, hãy để bộ mã hóa xuất ra một &lt;em&gt;đám mây xác suất&lt;/em&gt; \(\mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\sigma}^2)\) và kéo mọi đám mây ấy đan xen mượt mà quanh phân phối chuẩn \(\mathcal{N}(\mathbf{0}, \mathbf{I})\). Chào mừng bạn đến với &lt;strong&gt;Variational Autoencoder (VAE)&lt;/strong&gt; — cầu nối giữa học sâu và suy diễn Bayes biến phân.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-variational-autoencoder-vae&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Variational Autoencoder (VAE)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình biến ẩn xác suất:&lt;/strong&gt; Biểu diễn quy trình sinh qua phân phối tiên nghiệm \(p(\mathbf{z}) = \mathcal{N}(\mathbf{0}, \mathbf{I})\) và bộ giải mã có điều kiện \(p_\theta(\mathbf{x}\mid\mathbf{z})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Suy diễn biến phân và cận dưới ELBO:&lt;/strong&gt; Tối ưu hóa tổng của hai lực kéo đối lập — độ chính xác tái tạo dữ liệu và phân kỳ KL giữ không gian ẩn trơn tru, không lỗ hổng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thủ thuật tái tham số hóa (Reparameterization Trick):&lt;/strong&gt; Tách phần ngẫu nhiên \(\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})\) ra khỏi nhánh đạo hàm để lan truyền ngược chảy thông suốt qua nút lấy mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Từ VAE cổ điển đến ứng dụng hiện đại:&lt;/strong&gt; Mở rộng sang \(\beta\)-VAE (tách thuộc tính), VQ-VAE (mã ẩn rời rạc) và bộ nén không gian ẩn của các mô hình khuếch tán ảnh/video.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-cảm-nhận-hai-lực-kéo-trong-elbo-tái-tạo-vs-phân-kỳ-kl&quot;&gt;Giải thích: Cảm nhận hai lực kéo trong ELBO: Tái tạo vs. Phân kỳ KL&lt;/h3&gt;

&lt;p&gt;Xét một chiều ẩn duy nhất \(z \in \mathbb{R}\) với phân phối tiên nghiệm \(p(z) = \mathcal{N}(0, 1)\). Giả sử bộ mã hóa dự đoán \(q_\phi(z\mid x) = \mathcal{N}(\mu = 1{,}0,\; \sigma = 0{,}5)\) (tức \(\sigma^2 = 0{,}25\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính phân kỳ KL dạng đóng:&lt;/strong&gt;
\(D_{\text{KL}}(q_\phi(z\mid x) \| \mathcal{N}(0,1)) = -\frac{1}{2}\left(1 + \ln(\sigma^2) - \mu^2 - \sigma^2\right)\)
Thay \(\mu = 1{,}0\), \(\sigma^2 = 0{,}25\) (\(\ln(0{,}25) \approx -1{,}3863\)):
\(D_{\text{KL}} = -\frac{1}{2}(1 - 1{,}3863 - 1{,}0 - 0{,}25) = -\frac{1}{2}(-1{,}6363) \approx 0{,}8182.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ý nghĩa hai lực kéo:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Nếu chỉ tối ưu &lt;strong&gt;tái tạo&lt;/strong&gt;, mạng muốn \(\sigma \to 0\) (không nhiễu) và đẩy \(\mu\) thật xa nhau giữa các ảnh — nhưng khi \(\sigma \to 0\) thì \(-\ln(\sigma^2) \to +\infty\), phạt KL bùng nổ!&lt;/li&gt;
      &lt;li&gt;Nếu chỉ tối ưu &lt;strong&gt;KL&lt;/strong&gt;, mạng kéo \(\mu \to 0, \sigma \to 1\) (\(D_{\text{KL}} = 0\)), nhưng mọi ảnh đều có cùng đám mây \(\mathcal{N}(0,1)\) nên tái tạo thất bại.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điểm cân bằng:&lt;/strong&gt; VAE tự động xếp các đám mây xác suất vừa đủ khít để không còn khoảng trống, vừa đủ tách biệt để tái tạo tốt.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Variational Autoencoder (VAE) là mô hình sinh xác suất học biểu diễn ẩn có cấu trúc. Bằng cách kết hợp suy diễn biến phân (&lt;em&gt;variational inference&lt;/em&gt;) với mạng nơ-ron, VAE có thể sinh mẫu mới và nội suy mượt trong không gian ẩn. Chương này trình bày kiến trúc VAE, mục tiêu ELBO, thủ thuật tái tham số hóa (&lt;em&gt;reparameterization trick&lt;/em&gt;) và các ứng dụng liên quan.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần mục tiêu ELBO, xem &lt;strong&gt;13-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về vai trò của VAE trong không gian ẩn cho mô hình khuếch tán ảnh, video và các mô hình nhất quán (&lt;em&gt;consistency models&lt;/em&gt;).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, tiếng Anh. Giới thiệu VAE như một autoencoder có không gian ẩn là phân phối xác suất.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Đặt VAE trong bức tranh chung bên cạnh GAN và mô hình khuếch tán.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pYxNSUDSFH4&quot;&gt;In Statistics, Probability is not Likelihood.&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Ôn lại khái niệm hàm hợp lý (&lt;em&gt;likelihood&lt;/em&gt;), đại lượng mà ELBO đóng vai trò cận dưới.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Nhiều người lầm tưởng Autoencoder là một kỹ thuật cũ kỹ của thập niên 2010 đã bị Transformer hay Diffusion thay thế. Sự thật hoàn toàn ngược lại: Autoencoder chưa bao giờ biến mất — nó đã tiến hóa thành “bộ máy nén ngầm” đứng sau hầu hết các hệ thống AI đa phương thức đỉnh cao ngày nay, từ không gian ẩn của Stable Diffusion, bộ codec âm thanh nơ-ron (EnCodec/SoundStream) cho tới Masked Autoencoder (MAE) trong thị giác máy tính.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-vai-trò-chiến-lược-của-autoencoder-hiện-đại-20222026&quot;&gt;Kiến thức cần nhớ: Ba vai trò chiến lược của Autoencoder hiện đại (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bộ nén không gian ẩn cho mô hình khuếch tán:&lt;/strong&gt; Đưa ảnh \(512 \times 512 \times 3\) xuống tensor ẩn \(64 \times 64 \times 4\) (giảm \(48\times\) số phần tử) giúp huấn luyện khuếch tán nhanh và tiết kiệm VRAM gấp hàng chục lần.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Neural Audio Codec và lượng tử hóa vector (RVQ):&lt;/strong&gt; Nén sóng âm thanh liên tục thành chuỗi mã rời rạc (audio tokens) để mô hình ngôn ngữ có thể đọc và sinh tiếng nói, âm nhạc như văn bản.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Masked Autoencoder (MAE):&lt;/strong&gt; Che ngẫu nhiên tới \(75\%\) mảng ảnh (patches) và bắt bộ giải mã nhẹ tái tạo phần bị che, buộc bộ mã hóa ViT học biểu diễn ngữ nghĩa cực mạnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Autoencoder thưa (SAE) cho diễn giải LLM:&lt;/strong&gt; Đảo ngược nút cổ chai thành không gian &lt;em&gt;rộng và cực thưa&lt;/em&gt; để tách các khái niệm bị chồng chập bên trong kích hoạt của mô hình ngôn ngữ lớn.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-toán-mức-tiết-kiệm-tính-toán-khi-dùng-autoencoder-nén-ảnh-cho-latent-diffusion-và-mae&quot;&gt;Giải thích: Tính toán mức tiết kiệm tính toán khi dùng Autoencoder nén ảnh cho Latent Diffusion và MAE&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Nén không gian ẩn (kiểu Stable Diffusion, hệ số hạ mẫu \(f = 8\)):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Ảnh gốc: \(512 \times 512 \times 3 = 786{,}432\) giá trị.&lt;/li&gt;
  &lt;li&gt;Tensor ẩn: \((512/8) \times (512/8) \times 4 = 64 \times 64 \times 4 = 16{,}384\) giá trị.&lt;/li&gt;
  &lt;li&gt;Hệ số nén số phần tử: \(786{,}432 / 16{,}384 = 48\times\)! Với cơ chế Self-Attention có độ phức tạp bậc hai theo số vị trí không gian (\(N^2\)), giảm chiều cao/rộng đi \(8\times\) giúp giảm số lượng vị trí \(64\times\) và giảm chi phí ma trận chú ý tới \(64^2 = 4{,}096\times\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Tỷ lệ che \(75\%\) trong Masked Autoencoder (MAE) trên ảnh \(224 \times 224\) (patch \(16 \times 16\)):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tổng số patch: \((224/16)^2 = 14 \times 14 = 196\) patch.&lt;/li&gt;
  &lt;li&gt;Bộ mã hóa ViT nặng chỉ xử lý \(25\%\) patch nhìn thấy: \(196 \times 0{,}25 = 49\) token.&lt;/li&gt;
  &lt;li&gt;Chi phí Self-Attention của Encoder giảm còn \((49/196)^2 = 1/16 = 6{,}25\%\) so với xử lý toàn bộ ảnh, giúp tiền huấn luyện nhanh hơn gấp \(3\text{–}4\times\) trong thực tế.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;tùy-chọn-autoencoder-trong-vai-trò-không-gian-ẩn-bộ-nén-và-tái-tạo-bị-che&quot;&gt;Tùy chọn: Autoencoder trong vai trò không gian ẩn, bộ nén và tái tạo bị che&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết về autoencoder chuẩn, khử nhiễu hay thưa. Nội dung tổng hợp cách cùng kiến trúc encoder–decoder được triển khai sau năm 2022 trong &lt;strong&gt;nén không gian ẩn cho mô hình khuếch tán&lt;/strong&gt;, &lt;strong&gt;bộ nén âm thanh nơ-ron&lt;/strong&gt; và &lt;strong&gt;mô hình ảnh bị che (MAE)&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Mục tiêu tái tạo cơ bản:&lt;/p&gt;

\[\mathcal{L} = \mathbb{E}_{\mathbf{x}}\big\|\mathbf{x} - d_\phi(e_\theta(\mathbf{x}))\big\|^2\]

&lt;p&gt;vẫn là điểm xuất phát. Điểm khác biệt trong các hệ thống hiện đại là không gian ẩn được thiết kế &lt;em&gt;có cấu trúc hơn&lt;/em&gt;: lượng tử hóa rời rạc, tối ưu theo cảm nhận thị giác hoặc huấn luyện trên đầu vào bị che một phần.&lt;/p&gt;

&lt;h2 id=&quot;1-không-gian-ẩn-cho-mô-hình-khuếch-tán&quot;&gt;1. Không gian ẩn cho mô hình khuếch tán&lt;/h2&gt;

&lt;p&gt;Giai đoạn đầu của Stable Diffusion là một autoencoder (dùng chính quy hóa KL hoặc VQ) ánh xạ ảnh kích thước \(512\times512\) xuống một lưới đặc trưng ẩn nhỏ hơn nhiều. Quá trình khuếch tán (xem bài tùy chọn Chương 11 và Chương 13) vận hành trực tiếp trên lưới ẩn này. Autoencoder được huấn luyện kết hợp sai số tái tạo, mất mát đối kháng và mất mát cảm nhận (&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;Rombach et al., 2022&lt;/a&gt;) — thực chất đóng vai trò &lt;strong&gt;bộ nén (codec) phục vụ cho mô hình sinh thứ hai&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;2-một-số-ứng-dụng-tiêu-biểu&quot;&gt;2. Một số ứng dụng tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;bộ-nén-âm-thanh-nơ-ron-neural-audio-codec&quot;&gt;Bộ nén âm thanh nơ-ron (&lt;em&gt;neural audio codec&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.13438&quot;&gt;Défossez et al., 2022&lt;/a&gt; (EnCodec) và &lt;a href=&quot;https://arxiv.org/abs/2306.06546&quot;&gt;Kumar et al., 2023&lt;/a&gt; (DAC) là các autoencoder sử dụng lượng tử hóa vector phần dư (&lt;em&gt;residual vector quantization&lt;/em&gt;) trên dạng sóng âm thanh. Chúng là tầng nền cho các hệ thống như AudioLM, MusicGen và nhiều kiến trúc tổng hợp tiếng nói (TTS), chuyển tín hiệu âm thanh liên tục thành chuỗi token rời rạc để Transformer xử lý.&lt;/p&gt;

&lt;h3 id=&quot;masked-autoencoder-mae&quot;&gt;Masked Autoencoder (MAE)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2111.06377&quot;&gt;He et al., 2022&lt;/a&gt; che ngẫu nhiên phần lớn các mảnh ảnh (&lt;em&gt;patch&lt;/em&gt;) rồi dùng kiến trúc encoder–decoder dựa trên ViT để tái tạo lại điểm ảnh. Về bản chất, MAE là bài toán tiền huấn luyện tự giám sát (Chương 16) hơn là mô hình sinh, nhưng kiến trúc cài đặt vẫn là một autoencoder hoạt động trên các mảnh ảnh.&lt;/p&gt;

&lt;h3 id=&quot;autoencoder-lượng-tử-hóa-vector&quot;&gt;Autoencoder lượng tử hóa vector&lt;/h3&gt;

&lt;p&gt;VQ-VAE và VQGAN tiếp tục giữ vai trò nút thắt rời rạc trong các bộ tách token (&lt;em&gt;tokenizer&lt;/em&gt;) cho ảnh và video (như Make-A-Video, MAGVIT-v2). Hàm mất mát cam kết (&lt;em&gt;commitment loss&lt;/em&gt;) cơ bản vẫn giữ nguyên; các cải tiến giai đoạn 2022–2025 tập trung vào &lt;strong&gt;thiết kế bảng mã (codebook) hiệu quả hơn và lượng tử hóa không cần bảng tra cứu (&lt;em&gt;lookup-free quantization&lt;/em&gt;)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-mã-nguồn-phổ-biến&quot;&gt;3. Thư viện và mã nguồn phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/diffusers&quot;&gt;diffusers&lt;/a&gt; với lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AutoencoderKL&lt;/code&gt; — bộ mã hóa không gian ẩn theo kiểu Stable Diffusion.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/encodec&quot;&gt;facebookresearch/encodec&lt;/a&gt; và &lt;a href=&quot;https://github.com/descriptinc/descript-audio-codec&quot;&gt;descriptinc/descript-audio-codec&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/mae&quot;&gt;facebookresearch/mae&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-tài-liệu-tham-khảo-20222026&quot;&gt;4. Tài liệu tham khảo (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;Latent Diffusion Models (Rombach et al., 2022)&lt;/a&gt; — ứng dụng autoencoder làm không gian ẩn cho khuếch tán.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2111.06377&quot;&gt;MAE (He et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.13438&quot;&gt;EnCodec (Défossez et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2306.06546&quot;&gt;DAC (Kumar et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-phần-bổ-sung-so-với-nội-dung-cốt-lõi&quot;&gt;5. Phần bổ sung so với nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên hoàn thành phần cài đặt autoencoder bằng PyTorch và bài về các cạm bẫy không gian ẩn trước. Bài này chỉ minh họa &lt;strong&gt;cách không gian ẩn đó được ứng dụng&lt;/strong&gt; trong các hệ thống giai đoạn 2022–2026 (khuếch tán, bộ nén âm thanh, MAE), không đưa thêm công thức tái tạo nền tảng mới.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=J87hffSMB60&quot;&gt;How does Stable Diffusion work? – Latent Diffusion Models EXPLAINED&lt;/a&gt; — AI Coffee Break with Letitia, tiếng Anh. Giải thích vai trò của autoencoder tạo không gian ẩn cho Stable Diffusion.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, tiếng Anh. Ôn lại mô hình autoencoder thuần — điểm xuất phát của các bộ nén hiện đại.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But how do AI images and videos actually work?&lt;/td&gt;
          &lt;td&gt;Guest video by Welch Labs](https://www.youtube.com/watch?v=iv-5mZ_9CPY) — 3Blue1Brown, tiếng Anh. Minh họa quá trình khuếch tán hoạt động trên không gian ẩn đó.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-01 Nền tảng Autoencoder</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_01_Autoencoder_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_01_Autoencoder_Fundamentals</id>
   <content type="html">&lt;p&gt;Trong thế giới dữ liệu khổng lồ hôm nay, phần lớn ảnh, âm thanh và văn bản đều không có nhãn. Làm thế nào để máy tính tự học được bản chất của thế giới mà không cần con người ngồi gắn nhãn từng mẫu một? Autoencoder là câu trả lời kinh điển và thanh lịch nhất: biến chính dữ liệu đầu vào thành đích đến, dùng áp lực nén để chắt lọc tri thức.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-khung-tổng-quan-nền-tảng-autoencoder&quot;&gt;Kiến thức cần nhớ: Khung tổng quan nền tảng Autoencoder&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tư duy nén có cấu trúc:&lt;/strong&gt; Phân biệt nén dữ liệu tổng quát (như ZIP/JPEG) với nén học được theo miền dữ liệu (Autoencoder chỉ nén xuất sắc đúng loại dữ liệu nó đã thấy).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phổ các biến thể cốt lõi:&lt;/strong&gt; Nắm vững vai trò riêng của Undercomplete, Denoising, Sparse và Convolutional Autoencoder.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá biểu diễn không giám sát:&lt;/strong&gt; Đánh giá không chỉ qua sai số tái tạo mà còn qua khả năng tách cụm tuyến tính (linear probing) và phát hiện bất thường.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điểm dừng của Autoencoder xác định:&lt;/strong&gt; Nhận rõ ranh giới giữa &lt;em&gt;học biểu diễn&lt;/em&gt; (Autoencoder làm rất tốt) và &lt;em&gt;sinh dữ liệu mới&lt;/em&gt; (cần nâng cấp lên VAE ở Chương 13).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-tỷ-lệ-nén-của-autoencoder-mnist-ở-ba-mức-kích-thước-nút-cổ-chai&quot;&gt;Giải thích: So sánh tỷ lệ nén của Autoencoder MNIST ở ba mức kích thước nút cổ chai&lt;/h3&gt;

&lt;p&gt;Một ảnh MNIST có \(784\) số thực (32-bit float = \(3{,}136\text{ byte}\)). Xét 3 cấu hình nút cổ chai \(d\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;\(d = 64\):&lt;/strong&gt; Tỷ lệ nén \(784 / 64 = 12{,}25\times\). Bộ nhớ mỗi mã ẩn chỉ \(256\text{ byte}\); ảnh tái tạo gần như không phân biệt được với ảnh gốc, phù hợp cho khử nhiễu hoặc rút trích đặc trưng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;\(d = 16\):&lt;/strong&gt; Tỷ lệ nén \(784 / 16 = 49\times\). Ảnh tái tạo giữ tốt hình dáng chữ số nhưng bắt đầu mất các nét rung tay nhỏ — điểm cân bằng tốt để phát hiện bất thường.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;\(d = 2\):&lt;/strong&gt; Tỷ lệ nén \(784 / 2 = 392\times\). Mọi ảnh chỉ còn đúng một tọa độ \((z_1, z_2)\) vẽ được trực tiếp lên mặt phẳng 2D, nhưng ảnh tái tạo sẽ khá mờ vì 2 số thực không đủ mã hóa độ nghiêng, độ dày và kiểu chữ của 10 lớp cùng lúc.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nội dung nền tảng về autoencoder gồm hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết&lt;/strong&gt; — tổng quan khái niệm, cơ sở toán học và ví dụ trực quan.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt&lt;/strong&gt; — mã nguồn PyTorch, trực quan hóa không gian ẩn, bài báo nền tảng và các cạm bẫy thường gặp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, tiếng Anh. Trình bày trực quan ba thành phần: bộ mã hóa, nút thắt và bộ giải mã.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, tiếng Anh. Giải thích hàm mất mát tái tạo dùng để huấn luyện kiến trúc này.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Làm rõ vì sao nút thắt tất định chưa đủ để tạo thành một mô hình sinh hoàn chỉnh, dẫn sang chương sau.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-01-02 Cài đặt Autoencoder</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_01_02_Autoencoder_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_01_02_Autoencoder_Implementation</id>
   <content type="html">&lt;p&gt;Hiểu một Autoencoder trên giấy chỉ là nửa chặng đường; nửa còn lại thú vị hơn nhiều: nhìn một bức ảnh nhiễu hạt biến thành chữ số sắc nét ngay trên màn hình, rồi tự tay xoay vòng trong không gian ẩn 2D để xem máy tính tự sắp xếp 10 chữ số ra sao. Mục cài đặt này gom gọn hai phần thực hành trọng tâm: xây dựng các biến thể Autoencoder cốt lõi và khảo sát cấu trúc không gian ẩn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bản-đồ-thực-hành-cài-đặt-autoencoder&quot;&gt;Kiến thức cần nhớ: Bản đồ thực hành cài đặt Autoencoder&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phần lõi kiến trúc (12-01-02-01):&lt;/strong&gt; Triển khai đầy đủ Vanilla, Denoising và Convolutional Autoencoder trên MNIST với vòng lặp huấn luyện sạch và so sánh sai số tái tạo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phần phân tích không gian ẩn (12-01-02-02):&lt;/strong&gt; Thực hiện nội suy tuyến tính, vẽ bản đồ mã ẩn 2D theo màu nhãn, và chẩn đoán các bẫy kỹ thuật.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa dữ liệu và hàm mất mát:&lt;/strong&gt; Đối chiếu trực tiếp sự phù hợp giữa thang giá trị ảnh (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0, 1]&lt;/code&gt; vs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[-1, 1]&lt;/code&gt;), hàm kích hoạt cuối và hàm loss (BCE vs MSE).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán lỗi nhanh:&lt;/strong&gt; Quy trình kiểm tra nhanh kích thước tensor qua từng tầng tích chập/giải tích chập và phát hiện hiện tượng học thuộc.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-kiểm-tra-nhanh-sự-khác-biệt-giữa-bce-và-mse-trên-một-điểm-ảnh-xám&quot;&gt;Giải thích: Kiểm tra nhanh sự khác biệt giữa BCE và MSE trên một điểm ảnh xám&lt;/h3&gt;

&lt;p&gt;Giả sử điểm ảnh thật là \(x = 0{,}9\) và bộ giải mã dự đoán \(\hat{x} = 0{,}2\) (sai khá nặng).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Với hàm MSE:&lt;/strong&gt; \(\mathcal{L}_{\text{MSE}} = (0{,}9 - 0{,}2)^2 = 0{,}49\), đạo hàm theo \(\hat{x}\) là \(2(\hat{x} - x) = -1{,}4\).
Nếu đi qua hàm Sigmoid \(\hat{x} = \sigma(u)\) có \(\sigma&apos;(u) = \hat{x}(1 - \hat{x}) = 0{,}2 \times 0{,}8 = 0{,}16\), thì gradient theo logit \(u\) bị co lại chỉ còn: \(-1{,}4 \times 0{,}16 = -0{,}224\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Với hàm BCE:&lt;/strong&gt; \(\mathcal{L}_{\text{BCE}} = -[0{,}9\ln(0{,}2) + 0{,}1\ln(0{,}8)] \approx 1{,}471\), nhưng điều kỳ diệu nằm ở đạo hàm theo logit \(u\) (triệt tiêu nhân tử \(\hat{x}(1-\hat{x})\)):
\(\frac{\partial \mathcal{L}_{\text{BCE}}}{\partial u} = \hat{x} - x = 0{,}2 - 0{,}9 = -0{,}700.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài học thực hành:&lt;/strong&gt; Gradient của BCE mạnh hơn gấp &lt;strong&gt;3 lần&lt;/strong&gt; MSE ở vùng bão hòa Sigmoid, giúp Autoencoder hội tụ nhanh và sắc nét hơn rõ rệt trên dữ liệu ảnh chuẩn hóa về \([0, 1]\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Phần cài đặt autoencoder gồm hai bài:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt Cốt lõi&lt;/strong&gt; — xây dựng, huấn luyện và đánh giá tái tạo autoencoder chuẩn và khử nhiễu trên MNIST.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không gian Ẩn, Bài báo và Bẫy thường gặp&lt;/strong&gt; — nội suy mã ẩn, trực quan hóa không gian ẩn 2D, autoencoder tích chập, khái niệm liên quan và điểm then chốt.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, tiếng Anh. Ôn lại kiến trúc encoder–decoder tương ứng với phần mã cài đặt.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, tiếng Anh. Giải thích hàm mất mát tái tạo và cách trực quan hóa không gian ẩn trong các bài thực hành.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, tiếng Anh. Cấu trúc vòng lặp huấn luyện PyTorch áp dụng cho bộ mã hóa và bộ giải mã.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-01-02-02 Không gian Ẩn, Bài báo và Bẫy thường gặp</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_01_02_02_Latent_Space_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_01_02_02_Latent_Space_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Hãy tưởng tượng bạn lấy mã ẩn của một chữ số 1 và một chữ số 7, rồi đi dọc theo đoạn thẳng nối giữa hai điểm đó trong không gian ẩn — liệu những bức ảnh giải mã dọc đường có biến hình mượt mà từ số 1 sang số 7 hay sẽ vỡ nát thành nhiễu hỗn độn? Bài học này đưa bạn bước vào bên trong “hộp đen” không gian ẩn của Autoencoder để trực quan hóa các cụm dữ liệu, thử nghiệm nội suy và nhận diện lý do chính Autoencoder thường chưa thể sinh dữ liệu mới một cách tin cậy.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-khám-phá-không-gian-ẩn-và-những-giới-hạn-dẫn-đường-sang-vae&quot;&gt;Kiến thức cần nhớ: Khám phá không gian ẩn và những giới hạn dẫn đường sang VAE&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Nội suy tuyến tính trong không gian ẩn:&lt;/strong&gt; Tính \(\mathbf{z}(\alpha) = (1-\alpha)\mathbf{z}_A + \alpha\mathbf{z}_B\) và giải mã \(g_\theta(\mathbf{z}(\alpha))\) để kiểm tra tính liên tục cục bộ của biểu diễn học được.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trực quan hóa không gian ẩn 2D:&lt;/strong&gt; Chiếu dữ liệu xuống \(d = 2\) để quan sát cách các lớp tự tách cụm mà không hề dùng nhãn lớp trong quá trình huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lỗ hổng không gian ẩn (Holes in Latent Space):&lt;/strong&gt; Vì Autoencoder thường không áp đặt phân phối tiên nghiệm lên \(\mathbf{z}\), nhiều vùng nằm giữa các cụm không hề tương ứng với dữ liệu thật, khiến việc lấy mẫu ngẫu nhiên tạo ra ảnh méo mó.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bẫy thực hành phổ biến:&lt;/strong&gt; Lạm dụng nút cổ chai quá rộng (học thuộc), dùng sai hàm mất mát (MSE gây mờ nhẹ trên ảnh nhị phân), hoặc quên chuẩn hóa thang ảnh.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-đường-nội-suy-5-bước-trong-không-gian-ẩn-2d-và-nhận-diện-vùng-trống&quot;&gt;Giải thích: Tính tay một đường nội suy 5 bước trong không gian ẩn 2D và nhận diện vùng trống&lt;/h3&gt;

&lt;p&gt;Giả sử sau khi huấn luyện Autoencoder 2D trên MNIST, ảnh chữ số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; được mã hóa tại \(\mathbf{z}_A = (-2{,}0,\; 1{,}0)\) và ảnh chữ số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;7&lt;/code&gt; tại \(\mathbf{z}_B = (2{,}0,\; 3{,}0)\).&lt;/p&gt;

&lt;p&gt;Ta nội suy với \(\alpha \in \{0;\; 0{,}25;\; 0{,}50;\; 0{,}75;\; 1{,}0\}\) theo công thức \(\mathbf{z}(\alpha) = (1-\alpha)\mathbf{z}_A + \alpha\mathbf{z}_B\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\alpha = 0{,}00\): \((-2{,}0,\; 1{,}0)\) (ảnh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; sắc nét)&lt;/li&gt;
  &lt;li&gt;\(\alpha = 0{,}25\): \((-1{,}0,\; 1{,}5)\)&lt;/li&gt;
  &lt;li&gt;\(\alpha = 0{,}50\): \((0{,}0,\; 2{,}0)\) (trung điểm)&lt;/li&gt;
  &lt;li&gt;\(\alpha = 0{,}75\): \((1{,}0,\; 2{,}5)\)&lt;/li&gt;
  &lt;li&gt;\(\alpha = 1{,}00\): \((2{,}0,\; 3{,}0)\) (ảnh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;7&lt;/code&gt; sắc nét)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Điểm mấu chốt:&lt;/strong&gt; Nếu cụm ảnh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; tập trung trong bán kính \(0{,}8\) quanh \((-2, 1)\) và cụm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;7&lt;/code&gt; tập trung trong bán kính \(0{,}8\) quanh \((2, 3)\), thì điểm giữa \((0{,}0,\; 2{,}0)\) nằm cách cả hai tâm cụm một khoảng \(\sqrt{2^2 + 1^2} = \sqrt{5} \approx 2{,}24 \gg 0{,}8\) — rơi trọn vào &lt;strong&gt;vùng trống chưa từng được bộ giải mã nhìn thấy lúc huấn luyện&lt;/strong&gt;. Đây chính là động lực trực tiếp để Chương 13 (VAE) dùng phân kỳ KL nén mọi mã ẩn về một phân phối chuẩn liên tục.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Minh họa nội suy không gian ẩn
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nội suy Không gian Ẩn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Lấy hai chữ số khác nhau
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;idx1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Nội suy giữa ảnh kiểm tra thứ nhất và thứ sáu
&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;img1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;img2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Encode cả hai
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nội suy giữa hai ảnh kiểm tra:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mean mã ẩn ảnh 1: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mean mã ẩn ảnh 2: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Nội suy trong không gian ẩn
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sinh &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; ảnh trung gian bằng nội suy:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;img_interp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Bước &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (t=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;): Shape ảnh giải mã &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img_interp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trong hiển thị trực quan, bạn sẽ thấy biến hình mượt từ chữ số này sang chữ số kia.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Điều này chứng tỏ không gian ẩn đã học cấu trúc có nghĩa!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Minh họa giảm chiều trực quan hóa (không gian ẩn 2D)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện Autoencoder 2D để Trực quan hóa&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Autoencoder với không gian ẩn 2D để trực quan hóa&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Latent 2D để vẽ!
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_2d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer_2d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện autoencoder 2D (nén cực đoan: 784 → 2)...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;optimizer_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Trực quan hóa không gian ẩn
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mã hóa tập kiểm tra vào không gian ẩn 2D...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;latent_codes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;labels_all&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;latent_codes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels_all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;latent_codes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;concatenate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_codes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;labels_all&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;concatenate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape tọa độ không gian ẩn: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_codes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (10000, 2)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trong scatter plot, các chữ số khác nhau sẽ cụm trong không gian 2D.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Điều này chứng tỏ autoencoder học biểu diễn có nghĩa!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Chữ số 0 ở một vùng, 1 ở vùng khác, v.v.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Dưới đây là phần cài đặt autoencoder tích chập (&lt;em&gt;convolutional autoencoder&lt;/em&gt;) dành cho dữ liệu ảnh:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Autoencoder tích chập cho ảnh.
    
    Dùng tầng conv trong encoder (downsample không gian qua stride)
    và transposed convolution trong decoder (upsample).
    Hiệu quả tham số hơn nhiều so với fully connected cho ảnh.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Encoder: downsample bằng tầng conv
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# 28×28×1 → 14×14×32 → 7×7×64 → flatten → latent_dim
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 28→14
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 14→7
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Decoder: upsample bằng transposed conv
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# latent_dim → 7×7×64 → 14×14×32 → 28×28×1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder_linear&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder_conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ConvTranspose2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 7→14
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ConvTranspose2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 14→28
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder_linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reshape thành feature map
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Autoencoder Tích chập cho Ảnh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;conv_ae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;conv_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tổng tham số: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện nhanh
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer_conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện autoencoder tích chập...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Giữ cấu trúc 2D cho tầng conv
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;optimizer_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Autoencoder tích chập đã huấn luyện!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lợi ích: Ít tham số hơn, tái tạo ảnh tốt hơn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cấu trúc conv cung cấp inductive bias cho dữ liệu không gian&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-các-khái-niệm-liên-quan&quot;&gt;5. Các khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Autoencoder có liên hệ trực tiếp với phân tích thành phần chính (PCA), một phương pháp giảm chiều tuyến tính kinh điển. Một autoencoder chỉ gồm các tầng tuyến tính tối ưu theo MSE sẽ học phép chiếu dữ liệu lên đúng không gian con sinh bởi \(k\) thành phần chính đầu tiên như PCA. Nhờ bổ sung các hàm kích hoạt phi tuyến, autoencoder tổng quát hóa PCA để tìm đa tạp phi tuyến \(k\) chiều phù hợp nhất với dữ liệu — rất cần thiết với dữ liệu ảnh nơi các phép biến đổi như xoay, co giãn hay biến dạng đều mang tính phi tuyến.&lt;/p&gt;

&lt;p&gt;Autoencoder cũng gắn chặt với học biểu diễn và học chuyển giao. Trước thời kỳ ImageNet, kỹ thuật tiền huấn luyện từng tầng bằng &lt;em&gt;stacked autoencoder&lt;/em&gt; là phương pháp quan trọng để khởi tạo trọng số cho mạng sâu. Dù ReLU, batch normalization và kỹ thuật khởi tạo hiện đại đã giảm nhu cầu tiền huấn luyện kiểu cũ trong học giám sát, nguyên lý cốt lõi — tận dụng dữ liệu không nhãn để học đặc trưng nền tảng trước khi tinh chỉnh — vẫn là trụ cột của học tự giám sát ngày nay.&lt;/p&gt;

&lt;p&gt;Từ góc độ lý thuyết thông tin, autoencoder gắn với nguyên lý nút thắt thông tin (&lt;em&gt;information bottleneck&lt;/em&gt;): biểu diễn ẩn \(\mathbf{z}\) cần bảo toàn lượng thông tin hữu ích về \(\mathbf{x}\) cho nhiệm vụ tái tạo — tối đa hóa thông tin tương hỗ \(I(\mathbf{x}; \mathbf{z})\) — đồng thời loại bỏ thông tin nhiễu \(I(\mathbf{z}; \text{noise})\) hoặc giới hạn độ phức tạp \(H(\mathbf{z})\) của mã ẩn. Variational Autoencoder diễn đạt ràng buộc này tường minh hơn thông qua thành phần phân kỳ KL trên phân phối ẩn.&lt;/p&gt;

&lt;p&gt;Nhìn rộng hơn, tiến trình từ autoencoder sang VAE và GAN cho thấy cách mỗi bước mở rộng giải quyết một giới hạn cụ thể: autoencoder chuẩn đơn giản và dễ huấn luyện nhưng không gian ẩn có khoảng trống; VAE bổ sung khung xác suất và chính quy hóa phân phối ẩn để lấy mẫu và nội suy ổn định; còn GAN thay mục tiêu tái tạo bằng huấn luyện đối kháng để tạo ảnh sắc nét hơn.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.science.org/doi/10.1126/science.1127647&quot;&gt;“Reducing the Dimensionality of Data with Neural Networks” (2006)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Geoffrey E. Hinton, Ruslan Salakhutdinov&lt;br /&gt;
Bài báo công bố trên tạp chí &lt;em&gt;Science&lt;/em&gt; chứng minh autoencoder sâu có thể giảm chiều tốt hơn đáng kể so với PCA hoặc mạng nông. Nhóm tác giả đề xuất chiến lược tiền huấn luyện từng tầng (sử dụng máy Boltzmann hạn chế xếp chồng) rồi tinh chỉnh toàn mạng, qua đó mở khóa khả năng huấn luyện mạng sâu trước khi có ReLU và các phương pháp khởi tạo hiện đại, đồng thời khẳng định vai trò của học biểu diễn phân cấp không giám sát.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.cs.toronto.edu/~larocheh/publications/icml-2008-denoising-autoencoders.pdf&quot;&gt;“Extracting and Composing Robust Features with Denoising Autoencoders” (2008)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Pascal Vincent, Hugo Larochelle, Yoshua Bengio, Pierre-Antoine Manzagol&lt;br /&gt;
Bài báo giới thiệu autoencoder khử nhiễu và giải thích cơ sở lý thuyết vì sao làm nhiễu đầu vào rồi tái tạo bản sạch giúp mạng học cấu trúc đa tạp dữ liệu thay vì ghi nhớ từng mẫu. Cơ chế này đóng vai trò chính quy hóa ngay cả khi số chiều ẩn lớn, tạo ra đặc trưng bền vững hơn cho các bài toán phân loại sau đó. Mô hình “làm khuyết rồi tái tạo” này sau đó ảnh hưởng trực tiếp tới masked language modeling trong BERT và nhiều phương pháp tự giám sát khác.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://www.iro.umontreal.ca/~lisa/pointeurs/ICML2011_explicit_invariance.pdf&quot;&gt;“Contractive Auto-Encoders: Explicit Invariance During Feature Extraction” (2011)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Salah Rifai, Pascal Vincent, Xavier Muller, Xavier Glorot, Yoshua Bengio&lt;br /&gt;
Bài báo đề xuất &lt;em&gt;contractive autoencoder&lt;/em&gt; bằng cách bổ sung thành phần phạt chuẩn Frobenius của ma trận Jacobian của bộ mã hóa:&lt;/p&gt;

\[\mathcal{L} = \|\mathbf{x} - \hat{\mathbf{x}}\|^2 + \lambda \|J_f(\mathbf{x})\|_F^2\]

&lt;p&gt;trong đó \(J_f(\mathbf{x}) = \frac{\partial f(\mathbf{x})}{\partial \mathbf{x}}\). Thành phần phạt này khuyến khích biểu diễn ẩn ít thay đổi khi đầu vào chịu nhiễu loạn nhỏ, giúp tăng tính bất biến cục bộ của đặc trưng dù phải đánh đổi thêm chi phí tính toán Jacobian.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.6114&quot;&gt;“Auto-Encoding Variational Bayes” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Diederik P. Kingma, Max Welling&lt;br /&gt;
Bài báo xây dựng khung xác suất biến phân cho autoencoder (VAE), coi bộ mã hóa là hàm dự đoán phân phối trên biến ẩn và tối ưu cận dưới log-hợp lý. Bằng cách chính quy hóa không gian ẩn gần phân phối tiên nghiệm (thường là chuẩn tắc) và dùng thủ thuật tái tham số hóa để lan truyền ngược qua phép lấy mẫu, VAE khắc phục tình trạng khoảng trống trong không gian ẩn của autoencoder chuẩn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1511.05644&quot;&gt;“Adversarial Autoencoders” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Alireza Makhzani, Jonathon Shlens, Navdeep Jaitly, Ian Goodfellow, Brendan Frey&lt;br /&gt;
Bài báo kết hợp autoencoder với huấn luyện đối kháng, sử dụng một bộ phân biệt để ép phân phối mã ẩn khớp với phân phối tiên nghiệm mong muốn thay cho thành phần phạt KL của VAE. Cách tiếp cận lai này giữ được mục tiêu tái tạo của autoencoder nhưng linh hoạt hơn trong việc chọn phân phối tiên nghiệm (không bị giới hạn ở phân phối chuẩn độc lập theo từng chiều).&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo&quot;&gt;Bẫy thường gặp và Mẹo&lt;/h2&gt;

&lt;p&gt;Lỗi thường gặp nhất khi xây dựng autoencoder là đặt số chiều ẩn quá lớn, làm mất tác dụng nén của nút thắt. Khi số chiều ẩn xấp xỉ số chiều đầu vào, mạng dễ học sao chép gần như nguyên vẹn dữ liệu mà không rút trích được cấu trúc hữu ích. Cách xử lý là thu nhỏ mạnh chiều ẩn hoặc bổ sung ràng buộc (độ thưa, khử nhiễu, phạt contractive). Quy tắc khởi đầu hợp lý là nén khoảng 10–20 lần — ví dụ 32–64 chiều ẩn cho MNIST (784 chiều) — rồi điều chỉnh theo thực nghiệm.&lt;/p&gt;

&lt;p&gt;Quên chuẩn hóa dữ liệu đầu vào cũng dễ gây bất ổn huấn luyện. Nếu giá trị điểm ảnh giữ nguyên trong [0, 255], sai số tái tạo và gradient sẽ lớn hơn nhiều so với dải [0, 1]. Cần chuẩn hóa đầu vào về [0, 1] hoặc trung bình 0, độ lệch chuẩn 1, đồng thời chọn hàm kích hoạt đầu ra của bộ giải mã cho khớp: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sigmoid&lt;/code&gt; cho [0, 1], &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tanh&lt;/code&gt; cho [-1, 1] và tuyến tính cho dữ liệu đã chuẩn hóa z-score.&lt;/p&gt;

&lt;p&gt;Tối ưu trực tiếp theo MSE trên ảnh dễ tạo ra kết quả tái tạo bị mờ vì MSE cân bằng sai lệch trên mọi điểm ảnh thay vì ưu tiên biên cạnh và cấu trúc như thị giác người. Khi yêu cầu cao về chất lượng thị giác, nên cân nhắc dùng hàm mất mát cảm nhận (&lt;em&gt;perceptual loss&lt;/em&gt;) tính khoảng cách trên bản đồ đặc trưng của mạng tiền huấn luyện như VGG.&lt;/p&gt;

&lt;p&gt;Ngoài nút thắt chiều, việc bổ sung chính quy hóa tường minh giúp định hình không gian ẩn theo mục tiêu thiết kế cụ thể: phạt L1 (autoencoder thưa) tăng tính diễn giải, phạt KL (VAE) giúp không gian ẩn mượt để nội suy, còn phạt Jacobian (contractive autoencoder) tăng tính bền vững trước nhiễu loạn nhỏ.&lt;/p&gt;

&lt;p&gt;Khi tận dụng autoencoder làm bước tiền huấn luyện trong bài toán ít dữ liệu, cần quyết định rõ phần nào nên tinh chỉnh: với bài toán phân loại, thường chỉ giữ bộ mã hóa và gắn thêm tầng phân loại (tinh chỉnh tầng mới và có thể cả bộ mã hóa); với bài toán sinh, có thể cố định bộ mã hóa và tinh chỉnh bộ giải mã; còn khi thích ứng miền dữ liệu mới, tinh chỉnh cả hai thường hiệu quả hơn.&lt;/p&gt;

&lt;h2 id=&quot;điểm-then-chốt&quot;&gt;Điểm then chốt&lt;/h2&gt;

&lt;p&gt;Autoencoder học biểu diễn dữ liệu gọn bằng cách tái tạo đầu vào qua một nút thắt thông tin. Bộ mã hóa nén dữ liệu nhiều chiều thành mã ẩn, bộ giải mã khôi phục đầu vào từ mã ẩn đó, và cả hai được huấn luyện đồng thời bằng hàm mất mát tái tạo (MSE cho dữ liệu liên tục, binary cross-entropy cho dữ liệu nhị phân). Chiều nút thắt quyết định mức độ nén và chất lượng tái tạo, trong khi các biến thể như autoencoder khử nhiễu, autoencoder thưa và contractive autoencoder bổ sung ràng buộc giúp đặc trưng bền vững và có cấu trúc hơn. Không gian ẩn học được phục vụ hiệu quả cho giảm chiều, trực quan hóa, khử nhiễu và học đặc trưng không giám sát, đồng thời là bước đệm trực tiếp để hiểu Variational Autoencoder và các phương pháp học tự giám sát hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, tiếng Anh. Giải thích vì sao một mã ẩn chỉ tối ưu tái tạo vẫn có thể không phù hợp để lấy mẫu sinh dữ liệu mới.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, tiếng Anh. Cách tiếp cận biến phân khắc phục hạn chế trên, nội dung trọng tâm của chương tiếp theo.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=J87hffSMB60&quot;&gt;How does Stable Diffusion work? – Latent Diffusion Models EXPLAINED&lt;/a&gt; — AI Coffee Break with Letitia, tiếng Anh. Ví dụ thực tế về một không gian ẩn hiện đại được dùng trực tiếp cho quá trình sinh mẫu.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-01-02-01 Cài đặt Cốt lõi Autoencoder</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_01_02_01_Autoencoder_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_01_02_01_Autoencoder_Core_Code</id>
   <content type="html">&lt;p&gt;Một bức ảnh chữ số viết tay MNIST có tới \(784\) điểm ảnh, nhưng liệu bao nhiêu con số là đủ để tái hiện lại dáng cong của số 3 hay nét thẳng của số 7? Khi tự tay viết mã nguồn Vanilla Autoencoder, Denoising Autoencoder và Convolutional Autoencoder bằng PyTorch, bạn sẽ thấy ngay sự khác biệt giữa việc ép phẳng ảnh thành vector (mất cấu trúc không gian) với việc dùng tầng tích chập và tích chập chuyển vị để giữ trọn hình dáng chữ số.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-thiết-kế-kiến-trúc-và-quy-trình-huấn-luyện-autoencoder-trong-pytorch&quot;&gt;Kiến thức cần nhớ: Thiết kế kiến trúc và quy trình huấn luyện Autoencoder trong PyTorch&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thiết kế đối xứng Encoder–Decoder:&lt;/strong&gt; Giảm dần kích thước chiều (ví dụ \(784 \to 256 \to 64 \to 16\)) rồi mở rộng ngược lại, khớp hàm kích hoạt đầu ra (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Sigmoid&lt;/code&gt; cho ảnh \([0,1]\), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tanh&lt;/code&gt; cho \([-1,1]\)) với hàm mất mát.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biến thể Denoising ngay trong vòng huấn luyện:&lt;/strong&gt; Cộng nhiễu Gaussian \(\tilde{\mathbf{x}} = \text{clip}(\mathbf{x} + \sigma\boldsymbol{\epsilon}, 0, 1)\) tại bước forward nhưng vẫn tính loss so với ảnh sạch \(\mathbf{x}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convolutional Autoencoder (CAE):&lt;/strong&gt; Dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d(stride=2)&lt;/code&gt; để hạ mẫu và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ConvTranspose2d&lt;/code&gt; để nâng mẫu, khai thác tính bất biến tịnh tiến và giảm hàng chục lần số tham số so với MLP.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm định trực quan và định lượng:&lt;/strong&gt; Theo dõi đồng thời MSE/BCE trên tập kiểm tra và bảng đối chiếu ảnh gốc – ảnh nhiễu – ảnh tái tạo.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-kích-thước-tensor-và-số-tham-số-mlp-autoencoder-vs-conv-autoencoder-trên-mnist&quot;&gt;Giải thích: Tính kích thước tensor và số tham số: MLP Autoencoder vs. Conv Autoencoder trên MNIST&lt;/h3&gt;

&lt;p&gt;Xét đầu vào MNIST kích thước \(1 \times 28 \times 28 = 784\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tầng đầu của MLP Autoencoder&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(784, 256)&lt;/code&gt;):
    &lt;ul&gt;
      &lt;li&gt;Số tham số riêng tầng này: \(784 \times 256 + 256 = 200{,}960\) tham số.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng đầu của Conv Autoencoder&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d(1, 16, kernel_size=3, stride=2, padding=1)&lt;/code&gt;):
    &lt;ul&gt;
      &lt;li&gt;Kích thước không gian đầu ra: \(H_{\text{out}} = \left\lfloor\frac{28 + 2(1) - 3}{2}\right\rfloor + 1 = 14\), tức tensor \(16 \times 14 \times 14\).&lt;/li&gt;
      &lt;li&gt;Số tham số: \(16 \times (1 \times 3 \times 3 + 1) = 160\) tham số — &lt;strong&gt;ít hơn 1.256 lần&lt;/strong&gt; so với tầng MLP tương đương!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng nâng mẫu tương ứng&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ConvTranspose2d(16, 1, kernel_size=3, stride=2, padding=1, output_padding=1)&lt;/code&gt;):
    &lt;ul&gt;
      &lt;li&gt;Kích thước đầu ra: \((14 - 1)\times 2 - 2(1) + 3 + 1 = 28\), khớp chính xác \(1 \times 28 \times 28\). Chỉ sai &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output_padding=0&lt;/code&gt; sẽ cho ra \(27 \times 27\) và gây lỗi lệch kích thước khi tính loss!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-đoạn-mã&quot;&gt;4. Đoạn mã&lt;/h2&gt;

&lt;p&gt;Phần mã dưới đây cài đặt autoencoder chuẩn và autoencoder khử nhiễu bằng PyTorch cùng quy trình huấn luyện đầy đủ trên tập dữ liệu MNIST:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Autoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Autoencoder chuẩn với các tầng fully connected.
    
    Kiến trúc: Input → Encoder → Latent (nút thắt) → Decoder → Reconstruction
    
    Nút thắt buộc nén — chiều đầu vào &amp;gt; chiều ẩn.
    Mạng phải học mã hóa hiệu quả cấu trúc dữ liệu.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        input_dim: kích thước đầu vào làm phẳng (28*28=784 cho MNIST)
        latent_dim: chiều nút thắt (hệ số nén = input_dim/latent_dim)
        
        Ta dùng kiến trúc encoder–decoder đối xứng với chiều giảm rồi tăng dần:
        784 → 256 → 128 → 32 → 128 → 256 → 784
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Autoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Encoder: nén dần
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Không kích hoạt — để latent không bị chặn
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Decoder: giải nén dần
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Sigmoid cho giá trị pixel trong [0,1]
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Ánh xạ đầu vào sang biểu diễn ẩn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tái tạo từ mã ẩn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Autoencoder đầy đủ: encode rồi decode&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DenoisingAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Autoencoder khử nhiễu: huấn luyện tái tạo dữ liệu sạch từ đầu vào hỏng.
    
    Quá trình làm hỏng buộc học đặc trưng robust nắm cấu trúc dữ liệu
    thay vì ghi nhớ ví dụ huấn luyện. Kết quả là đặc trưng tốt hơn cho
    tác vụ downstream.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DenoisingAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Cùng kiến trúc với autoencoder vanilla
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Chính quy hóa thêm
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;add_noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Làm hỏng đầu vào bằng nhiễu.
        
        Với MNIST, ta dùng nhiễu Gaussian và clip về [0,1].
        Các loại hỏng khác: masking (zero pixel),
        muối-tiêu, hoặc nhiễu adversarial.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;noisy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clamp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noisy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Huấn luyện: làm hỏng đầu vào, encode bản hỏng, decode ra bản sạch.
        
        Khác biệt then chốt so với vanilla: ta thêm nhiễu vào đầu vào trước khi encode
        nhưng tính loss so với đầu vào sạch gốc. Điều này huấn luyện mạng khử nhiễu.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Làm hỏng đầu vào
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x_noisy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;add_noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Encode đầu vào hỏng
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_noisy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Decode (nên tái tạo đầu vào sạch, không phải đầu vào nhiễu!)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_noisy&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tải MNIST để minh họa
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện Autoencoder trên MNIST&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tải dữ liệu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Compose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ToTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện autoencoder vanilla
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Huấn luyện Autoencoder Vanilla (latent_dim=32)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Autoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer_ae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MSELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Làm phẳng ảnh: (batch, 1, 28, 28) → (batch, 784)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Huấn luyện Autoencoder Khử nhiễu (latent_dim=32, noise=0.3)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DenoisingAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer_dae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward pass (thêm nhiễu bên trong)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noisy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Loss: tái tạo dữ liệu SẠCH từ đầu vào NHIỄU
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;optimizer_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra và trực quan hóa
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kiểm tra Tái tạo&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Lấy batch kiểm tra
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Autoencoder vanilla
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;recon_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_ae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Autoencoder khử nhiễu (thêm nhiễu khi kiểm tra nữa)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;test_noisy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;add_noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;recon_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tính lỗi tái tạo
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mse_ae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mse_dae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MSE tái tạo AE vanilla: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mse_ae&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;MSE tái tạo AE khử nhiễu: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mse_dae&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Trực quan hóa một số tái tạo
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;n_display&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hiển thị &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_display&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; ảnh kiểm tra đầu với tái tạo...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Reshape để trực quan hóa
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;originals&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_display&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;recon_ae_imgs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;recon_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_display&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;recon_dae_imgs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;recon_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_display&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# In shape (sẽ hiển thị trong notebook thực)
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape gốc: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;originals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape tái tạo: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_ae_imgs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, tiếng Anh. Hình dung cấu trúc hai mô-đun encoder và decoder cần xây dựng trong phần mã.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, tiếng Anh. Cách ghép bộ tối ưu, hàm mất mát và bước huấn luyện quanh encoder và decoder.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, tiếng Anh. Cách đánh giá kết quả tái tạo hợp lý để phát hiện lỗi cài đặt.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-01-01 Lý thuyết Autoencoder</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_01_01_Autoencoder_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_01_01_Autoencoder_Theory</id>
   <content type="html">&lt;p&gt;Một câu hỏi hóc búa từng khiến nhiều người mới học phải khựng lại: nếu mục tiêu của Autoencoder chỉ là tái tạo lại đúng đầu vào \(\mathbf{x}\), vậy tại sao mạng không đơn giản là “chép nguyên xi” đầu vào ra đầu ra để đạt loss bằng 0? Câu trả lời nằm ở hình học của những ràng buộc: chính việc &lt;em&gt;tước bỏ năng lực ghi nhớ tầm thường&lt;/em&gt; mới buộc mạng phải học ra các đặc trưng bậc cao. Bài lý thuyết này phân tích chặt chẽ từ toán học tuyến tính (PCA) đến các biến thể Denoising và Sparse Autoencoder.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-nền-tảng-toán-học-của-autoencoder-và-các-cơ-chế-chính-quy-hóa&quot;&gt;Kiến thức cần nhớ: Nền tảng toán học của Autoencoder và các cơ chế chính quy hóa&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Autoencoder thiếu hoàn chỉnh (Undercomplete) và định lý tương đương PCA:&lt;/strong&gt; Chứng minh khi kích hoạt tuyến tính và loss MSE, nghiệm tối ưu của Autoencoder trải cùng không gian con với \(d\) vector riêng hàng đầu của ma trận hiệp phương sai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Autoencoder dư thừa (Overcomplete) và nguy cơ ánh xạ đồng nhất:&lt;/strong&gt; Giải thích vì sao khi \(d \ge D\), mục tiêu tái tạo thuần túy trở nên vô nghĩa nếu thiếu ràng buộc cấu trúc.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Denoising Autoencoder (DAE) và hình học trường vector:&lt;/strong&gt; Làm nhiễu đầu vào $$\tilde{\mathbf{x}} \sim q(\tilde{\mathbf{x}}&lt;/td&gt;
          &lt;td&gt;\mathbf{x})\(rồi bắt mạng khôi phục\)\mathbf{x}$$, thực chất dạy mạng học vector kéo điểm nhiễu quay về đa tạp dữ liệu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sparse &amp;amp; Contractive Autoencoder:&lt;/strong&gt; Dùng phạt phân kỳ KL lên độ kích hoạt trung bình \(\hat{\rho}_j\) hoặc chuẩn Frobenius của Jacobian \(\|J_f(\mathbf{x})\|_F^2\) để tạo biểu diễn chọn lọc và bền vững.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-số-hạng-phạt-thưa-kl-trong-sparse-autoencoder&quot;&gt;Giải thích: Tính tay số hạng phạt thưa KL trong Sparse Autoencoder&lt;/h3&gt;

&lt;p&gt;Trong Sparse Autoencoder, ta mong muốn mỗi nơ-ron ẩn chỉ “bật” trung bình khoảng \(\rho = 0{,}05\) (\(5\%\) số mẫu trong batch). Hàm phạt phân kỳ KL giữa phân phối Bernoulli(\(\rho\)) và độ kích hoạt thực tế \(\hat{\rho}_j\) là:
\(\Omega_{\text{sparse}}(\hat{\rho}_j) = \rho \ln\frac{\rho}{\hat{\rho}_j} + (1 - \rho)\ln\frac{1 - \rho}{1 - \hat{\rho}_j}.\)&lt;/p&gt;

&lt;p&gt;So sánh hai nơ-ron ẩn trên cùng một batch:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nơ-ron A hoạt động đúng mục tiêu&lt;/strong&gt; (\(\hat{\rho}_A = 0{,}05\)):
\(\Omega(0{,}05) = 0{,}05\ln(1) + 0{,}95\ln(1) = 0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nơ-ron B bị “bật tràn lan”&lt;/strong&gt; (\(\hat{\rho}_B = 0{,}50\)):
\(\Omega(0{,}50) = 0{,}05\ln\frac{0{,}05}{0{,}50} + 0{,}95\ln\frac{0{,}95}{0{,}50} = 0{,}05(-2{,}3026) + 0{,}95(0{,}6419) = -0{,}1151 + 0{,}6098 = 0{,}4947.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu ứng tối ưu:&lt;/strong&gt; Nơ-ron B chịu mức phạt gần \(0{,}50\) nhân hệ số \(\beta\), tạo gradient dương ép bias và trọng số của nó giảm xuống cho đến khi nó chỉ phản ứng mạnh với một mẫu đặc trưng thực sự chuyên biệt.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;autoencoder-học-biểu-diễn-hiệu-quả&quot;&gt;Autoencoder: Học biểu diễn hiệu quả&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/2/28/Autoencoder_structure.png/600px-Autoencoder_structure.png&quot; alt=&quot;Autoencoder Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc Autoencoder với bộ mã hóa (encoder) và bộ giải mã (decoder). Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Autoencoder đại diện cho một cách huấn luyện mạng nơ-ron khác hẳn học có giám sát. Thay vì học ánh xạ từ đầu vào sang nhãn mục tiêu, autoencoder học cách tái tạo chính đầu vào của nó đi qua một nút thắt thông tin (&lt;em&gt;information bottleneck&lt;/em&gt;). Nhiệm vụ tưởng như đơn giản này trở nên hữu ích khi mạng bị ràng buộc phải truyền dữ liệu qua một tầng ẩn có số chiều nhỏ hơn gọi là không gian ẩn (&lt;em&gt;latent space&lt;/em&gt;) hay mã (&lt;em&gt;code&lt;/em&gt;). Để nén rồi giải nén thành công, mạng buộc phải giữ lại cấu trúc cốt lõi của dữ liệu và loại bỏ nhiễu cũng như chi tiết dư thừa.&lt;/p&gt;

&lt;p&gt;Giá trị chính của autoencoder không nằm ở bản thân việc tái tạo lại ảnh gốc mà ở biểu diễn dữ liệu được học trong quá trình đó. Bộ mã hóa (&lt;em&gt;encoder&lt;/em&gt;) học cách rút trích các đặc trưng quan trọng từ dữ liệu nhiều chiều thành mã gọn, còn bộ giải mã (&lt;em&gt;decoder&lt;/em&gt;) học cách khôi phục dữ liệu từ mã đó. Trong một autoencoder huấn luyện tốt, các điểm gần nhau trong không gian ẩn thường tương ứng với các đầu vào tương đồng về mặt ngữ nghĩa, cho phép nội suy mượt giữa các mẫu. Nhờ vậy, autoencoder được ứng dụng trong giảm chiều, khử nhiễu, phát hiện bất thường, trích xuất đặc trưng cho tác vụ sau và làm nền tảng cho các mô hình sinh phức tạp hơn.&lt;/p&gt;

&lt;p&gt;Hoạt động của autoencoder phụ thuộc trực tiếp vào sự cân bằng giữa dung lượng mạng và ràng buộc nén. Nếu số chiều ẩn lớn hơn hoặc bằng số chiều đầu vào mà không có ràng buộc bổ sung, mạng có thể học hàm đồng nhất — sao chép nguyên xi đầu vào — và không rút trích được cấu trúc nào. Nút thắt chiều buộc mạng phải chọn lọc thông tin cần giữ: khi nén ảnh 784 chiều xuống 32 chiều ẩn, mạng không thể lưu từng điểm ảnh độc lập mà phải khám phá các đặc trưng bậc cao hơn như biên cạnh, hình dạng và kết cấu phù hợp với phân phối dữ liệu huấn luyện.&lt;/p&gt;

&lt;p&gt;Về mặt lịch sử, autoencoder là một trong những hướng học không giám sát thành công sớm nhất của học sâu, chứng minh mạng nơ-ron có thể học biểu diễn hữu ích mà không cần nhãn. Ý tưởng này từng đóng vai trò quan trọng trong tiền huấn luyện nhiều tầng trước thời kỳ ReLU, đồng thời ảnh hưởng trực tiếp tới các phương pháp học tự giám sát hiện đại — nơi mô hình dự đoán hoặc tái tạo một phần dữ liệu từ phần còn lại. Kiến trúc encoder–decoder cũng trở thành mẫu thiết kế phổ biến trong mô hình chuỗi-sang-chuỗi, VAE và nhiều họ mô hình sinh khác.&lt;/p&gt;

&lt;p&gt;Tuy vậy, autoencoder chuẩn có những giới hạn rõ rệt khi dùng làm mô hình sinh. Vì mục tiêu chỉ là tái tạo dữ liệu huấn luyện, không gian ẩn có thể tồn tại các “khoảng trống” không tương ứng với mẫu huấn luyện nào, khiến việc lấy mẫu ngẫu nhiên dễ tạo đầu ra bất hợp lý. Ngoài ra, autoencoder không mô hình hóa tường minh phân phối dữ liệu, và sai số tái tạo theo điểm ảnh (như MSE) không luôn phản ánh đúng cảm nhận thị giác của con người. Những hạn chế này dẫn tới sự ra đời của Variational Autoencoder (chính quy hóa phân phối không gian ẩn), GAN (dùng mục tiêu đối kháng) và hàm mất mát cảm nhận (&lt;em&gt;perceptual loss&lt;/em&gt;).&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Cấu trúc toán học của autoencoder tương đối gọn gàng nhưng mang nhiều hệ quả quan trọng. Mô hình gồm hai mạng nơ-ron nối tiếp: bộ mã hóa \(f_\phi\) với tham số \(\phi\) và bộ giải mã \(g_\theta\) với tham số \(\theta\). Với đầu vào \(\mathbf{x} \in \mathbb{R}^{d}\), bộ mã hóa tạo ra biểu diễn ẩn:&lt;/p&gt;

\[\mathbf{z} = f_\phi(\mathbf{x}) \in \mathbb{R}^{k}\]

&lt;p&gt;trong đó thường chọn \(k &amp;lt; d\) để tạo nút thắt (trừ các biến thể dùng ràng buộc chính quy hóa thay cho nút thắt chiều). Bộ giải mã tái tạo đầu vào từ mã ẩn:&lt;/p&gt;

\[\hat{\mathbf{x}} = g_\theta(\mathbf{z}) = g_\theta(f_\phi(\mathbf{x})) \in \mathbb{R}^{d}\]

&lt;p&gt;Mục tiêu huấn luyện là tối thiểu hóa sai số tái tạo:&lt;/p&gt;

\[\mathcal{L}(\mathbf{x}, \hat{\mathbf{x}}) = \|\mathbf{x} - \hat{\mathbf{x}}\|^2\]

&lt;p&gt;cho dữ liệu liên tục (sai số bình phương trung bình — MSE), hoặc:&lt;/p&gt;

\[\mathcal{L}(\mathbf{x}, \hat{\mathbf{x}}) = -\sum_{i=1}^{d} [x_i \log(\hat{x}_i) + (1-x_i)\log(1-\hat{x}_i)]\]

&lt;p&gt;cho dữ liệu nhị phân (binary cross-entropy, xem mỗi chiều là một biến Bernoulli độc lập).&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Lựa chọn hàm mất mát phản ánh giả định về mô hình nhiễu của dữ liệu. Tối thiểu hóa MSE tương đương với ước lượng hợp lý cực đại dưới giả định nhiễu chuẩn $$p(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z}) = \mathcal{N}(\mathbf{x}; g_\theta(\mathbf{z}), \sigma^2 I)\(. Binary cross-entropy giả định mỗi điểm ảnh tuân theo phân phối Bernoulli với xác suất\)\hat{x}_i$$; trong thực tế, hàm này cũng thường hoạt động tốt với ảnh có giá trị chuẩn hóa về đoạn [0, 1]. Ở mức cao hơn, có thể dùng hàm mất mát cảm nhận đo khoảng cách trong không gian đặc trưng của mạng tiền huấn luyện.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Số chiều nút thắt \(k\) điều chỉnh sự đánh đổi giữa mức độ nén và độ trung thực tái tạo. Giá trị \(k\) rất nhỏ (2–3 chiều) thuận tiện cho việc trực quan hóa không gian ẩn nhưng dễ làm mất chi tiết quan trọng; giá trị trung bình (32–128 chiều đối với ảnh cỡ nhỏ) cân bằng tốt giữa nén và chất lượng tái tạo; còn \(k\) quá lớn làm giảm áp lực nén.&lt;/p&gt;

&lt;p&gt;Ngay cả khi \(k \geq d\) (không tạo nút thắt chiều), ta vẫn có thể tránh hàm đồng nhất bằng các ràng buộc chính quy hóa khác. &lt;strong&gt;Autoencoder thưa (&lt;em&gt;sparse autoencoder&lt;/em&gt;)&lt;/strong&gt; bổ sung thành phần phạt độ thưa lên giá trị kích hoạt ẩn:&lt;/p&gt;

\[\mathcal{L}_{\text{sparse}} = \|\mathbf{x} - \hat{\mathbf{x}}\|^2 + \lambda \sum_{j=1}^{k} KL(\rho \| \hat{\rho}_j)\]

&lt;p&gt;trong đó \(\rho\) là mức độ kích hoạt mục tiêu nhỏ (chẳng hạn 0,05) và \(\hat{\rho}_j\) là mức kích hoạt trung bình của nơ-ron ẩn thứ \(j\) trên tập huấn luyện. Thành phần phân kỳ KL khuyến khích phần lớn đơn vị ẩn giữ giá trị gần 0 ở hầu hết thời điểm, buộc mỗi đơn vị chuyên biệt hóa vào một nhóm mẫu hình riêng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Autoencoder khử nhiễu (&lt;em&gt;denoising autoencoder&lt;/em&gt;)&lt;/strong&gt; chủ động làm nhiễu đầu vào \(\mathbf{x}\) thành \(\tilde{\mathbf{x}}\) (bằng nhiễu Gaussian, che ngẫu nhiên điểm ảnh hoặc nhiễu muối-tiêu) nhưng yêu cầu mạng tái tạo bản gốc sạch:&lt;/p&gt;

\[\mathcal{L} = \|\mathbf{x} - g_\theta(f_\phi(\tilde{\mathbf{x}}))\|^2\]

&lt;p&gt;Cách huấn luyện này buộc bộ mã hóa học các đặc trưng bền vững trước nhiễu, còn bộ giải mã học cách khôi phục phần bị hỏng dựa trên ngữ cảnh còn lại. Do đó, autoencoder khử nhiễu thường học được biểu diễn hữu ích hơn autoencoder chuẩn vì không thể chỉ ghi nhớ điểm ảnh thô.&lt;/p&gt;

&lt;p&gt;Về hình học không gian ẩn, trong một autoencoder được huấn luyện tốt, ta có thể nội suy tuyến tính giữa hai mã ẩn \(\mathbf{z}_1\) và \(\mathbf{z}_2\):&lt;/p&gt;

\[\mathbf{z}_t = (1-t)\mathbf{z}_1 + t\mathbf{z}_2, \quad t \in [0,1]\]

&lt;p&gt;rồi giải mã \(g_\theta(\mathbf{z}_t)\) để thu được các mẫu trung gian. Tuy nhiên, autoencoder chuẩn không có cơ chế đảm bảo không gian ẩn liên tục khắp mọi nơi; nếu đường nội suy đi qua vùng trống không có mẫu huấn luyện, ảnh giải mã có thể bị méo hoặc phi thực tế. Đây là lý do Variational Autoencoder bổ sung ràng buộc trực tiếp lên phân phối không gian ẩn.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;p&gt;Hãy theo dõi quá trình huấn luyện một autoencoder nén ảnh MNIST kích thước 28×28 = 784 điểm ảnh xuống mã ẩn 32 chiều.&lt;/p&gt;

&lt;p&gt;Ở những bước đầu với trọng số ngẫu nhiên, bộ mã hóa tạo ra các vector vô nghĩa và bộ giải mã xuất ra ảnh gần như nhiễu, dẫn đến sai số tái tạo rất lớn. Lan truyền ngược dần điều chỉnh trọng số để giảm sai số này.&lt;/p&gt;

&lt;p&gt;Trong giai đoạn sớm, bộ mã hóa học các thông tin thô như vùng nền tối và vùng nét sáng ở từng khu vực ảnh. Khi tiếp tục huấn luyện, mạng nhận ra các thành phần hình học rõ hơn: một số chiều ẩn phản ứng mạnh với nét dọc (như chữ số 1, 4, 7), chiều khác gắn với đường cong (0, 6, 8, 9) hoặc nét ngang (2, 3, 5, 7). Đến khi hội tụ, 32 chiều ẩn tự tổ chức để mã hóa kiểu chữ số, độ dày nét, độ nghiêng, kích thước và vị trí — hoàn toàn phát sinh từ mục tiêu tái tạo mà không cần nhãn.&lt;/p&gt;

&lt;p&gt;Khi chiếu các mẫu kiểm tra vào không gian ẩn 32 chiều, các biến thể của chữ số “3” (nét dày, mảnh, nghiêng) thường tập trung gần nhau do chia sẻ cấu trúc hình học tương tự, trong khi các chữ số “8” (gồm hai vòng kín) tụ thành một cụm khác.&lt;/p&gt;

&lt;p&gt;Ta có thể kiểm tra cấu trúc không gian ẩn bằng phép nội suy giữa mã ẩn \(\mathbf{z}_3\) của một chữ số “3” và \(\mathbf{z}_8\) của một chữ số “8”:&lt;/p&gt;

&lt;p&gt;\(\mathbf{z}_{0.0} = \mathbf{z}_3 \to\) giải mã thành “3”&lt;br /&gt;
\(\mathbf{z}_{0.25} = 0.75\mathbf{z}_3 + 0.25\mathbf{z}_8 \to\) giải mã thành “3” bắt đầu xuất hiện nét của “8”&lt;br /&gt;
\(\mathbf{z}_{0.5} = 0.5\mathbf{z}_3 + 0.5\mathbf{z}_8 \to\) giải mã thành hình dạng trung gian giữa “3” và “8”&lt;br /&gt;
\(\mathbf{z}_{0.75} = 0.25\mathbf{z}_3 + 0.75\mathbf{z}_8 \to\) giải mã thành “8” còn lưu nét của “3”&lt;br /&gt;
\(\mathbf{z}_{1.0} = \mathbf{z}_8 \to\) giải mã thành “8”&lt;/p&gt;

&lt;p&gt;Quá trình biến đổi mượt cho thấy không gian ẩn có cấu trúc liên tục tốt; ngược lại, các điểm nhảy đột ngột hoặc ảnh mờ nhiễu cho thấy tồn tại khoảng trống trong không gian ẩn.&lt;/p&gt;

&lt;p&gt;Với autoencoder khử nhiễu, giả sử ta xóa ngẫu nhiên 20% điểm ảnh của chữ số “7”. Dựa trên phần nét còn lại, mạng phải suy luận bối cảnh tổng thể để phân biệt đó là “7” chứ không phải “1” và khôi phục trọn vẹn chữ số gốc. Chính yêu cầu suy luận từ thông tin thiếu hụt này giúp biểu diễn ẩn nắm bắt cấu trúc ngữ nghĩa tốt hơn so với chỉ sao chép điểm ảnh.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, tiếng Anh. Minh họa cách tín hiệu tái tạo tự đóng vai trò mục tiêu huấn luyện không cần nhãn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, tiếng Anh. Phân biệt kiến trúc &lt;em&gt;undercomplete&lt;/em&gt; và &lt;em&gt;overcomplete&lt;/em&gt; được đề cập trong phần lý thuyết.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Góc nhìn nút thắt thông tin đối với cùng mục tiêu tái tạo.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12 Autoencoder</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter12/12_00_Introduction</id>
   <content type="html">&lt;p&gt;Giả sử bạn phải mô tả một bức ảnh chân dung độ phân giải cao cho một người bạn qua điện thoại, nhưng cước gọi chỉ cho phép bạn nói đúng… 10 con số. Nếu bạn lãng phí 10 con số đó để đọc giá trị màu của 10 điểm ảnh ngẫu nhiên, người bạn ở đầu dây bên kia sẽ chẳng thể vẽ lại được gì; nhưng nếu bạn mã hóa dáng mặt, hướng nhìn, ánh sáng và biểu cảm, bức chân dung sẽ hiện lên đầy sống động. Đó chính là nghệ thuật của &lt;strong&gt;Autoencoder&lt;/strong&gt; — ép mạng nơ-ron đi qua một “nút cổ chai” thông tin để tự khám phá cấu trúc tinh túy nhất của dữ liệu mà không cần bất kỳ nhãn thủ công nào.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-học-biểu-diễn-bằng-autoencoder&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của học biểu diễn bằng Autoencoder&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc nút cổ chai Encoder–Decoder:&lt;/strong&gt; Bộ mã hóa \(f_\phi\) nén đầu vào \(\mathbf{x} \in \mathbb{R}^D\) xuống mã ẩn \(\mathbf{z} \in \mathbb{R}^d\) (\(d \ll D\)), còn bộ giải mã \(g_\theta\) tái tạo \(\hat{\mathbf{x}}\) từ \(\mathbf{z}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mối liên hệ với PCA và đa tạp phi tuyến:&lt;/strong&gt; Hiểu vì sao Autoencoder tuyến tính phục hồi không gian con chính của PCA, còn Autoencoder phi tuyến học được các bề mặt cong (manifold) trong không gian cao chiều.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chính quy hóa biểu diễn (Denoising, Sparse, Contractive):&lt;/strong&gt; Ngăn mạng học hàm đồng nhất tầm thường ngay cả khi nút cổ chai rộng bằng cách thêm nhiễu đầu vào hoặc ràng buộc thưa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối tới hệ sinh thái hiện đại:&lt;/strong&gt; Từ giảm chiều, phát hiện bất thường đến bộ nén không gian ẩn cho Diffusion và Masked Autoencoder (MAE).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tỷ-lệ-nén-và-sai-số-tái-tạo-của-một-nút-cổ-chai-2d--1d&quot;&gt;Giải thích: Tỷ lệ nén và sai số tái tạo của một nút cổ chai 2D → 1D&lt;/h3&gt;

&lt;p&gt;Xét tập dữ liệu 2D gồm 3 điểm nằm gần đường thẳng \(x_2 = x_1\): \(\mathbf{x}^{(1)} = (1, 1)\), \(\mathbf{x}^{(2)} = (2, 2)\), \(\mathbf{x}^{(3)} = (3, 2{,}8)\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bộ mã hóa tuyến tính chiếu lên trục 1D&lt;/strong&gt; với trọng số \(\mathbf{w}_e = (0{,}5,\; 0{,}5)\): \(z = 0{,}5 x_1 + 0{,}5 x_2\).
    &lt;ul&gt;
      &lt;li&gt;\(z^{(1)} = 1{,}0\), \(z^{(2)} = 2{,}0\), \(z^{(3)} = 2{,}9\) (nén giảm \(50\%\) số chiều).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bộ giải mã tuyến tính&lt;/strong&gt; \(\hat{\mathbf{x}} = (z, z)\):
    &lt;ul&gt;
      &lt;li&gt;\(\hat{\mathbf{x}}^{(1)} = (1, 1)\) (sai số \(0\)), \(\hat{\mathbf{x}}^{(2)} = (2, 2)\) (sai số \(0\)), \(\hat{\mathbf{x}}^{(3)} = (2{,}9, 2{,}9)\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính MSE tái tạo:&lt;/strong&gt; Chỉ điểm thứ 3 có sai số \((3 - 2{,}9)^2 + (2{,}8 - 2{,}9)^2 = 0{,}01 + 0{,}01 = 0{,}02\), nên \(\text{MSE} = \frac{0 + 0 + 0{,}02}{3 \times 2} \approx 0{,}0033\).
Một điểm bất thường như \((1, 5)\) sẽ bị nén thành \(z = 3\) và tái tạo thành \((3, 3)\) với sai số bình phương bằng \((1-3)^2 + (5-3)^2 = 8{,}0\) — lớn gấp &lt;strong&gt;400 lần&lt;/strong&gt; điểm bình thường, giải thích trực giác phát hiện bất thường bằng Autoencoder!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Autoencoder học biểu diễn dữ liệu gọn và có cấu trúc thông qua học không giám sát bằng cách nén đầu vào vào không gian ẩn (&lt;em&gt;latent space&lt;/em&gt;) có số chiều thấp hơn rồi tái tạo lại đầu vào ban đầu. Chương này trình bày autoencoder chuẩn (&lt;em&gt;vanilla&lt;/em&gt;), autoencoder khử nhiễu (&lt;em&gt;denoising autoencoder&lt;/em&gt;), autoencoder thưa (&lt;em&gt;sparse autoencoder&lt;/em&gt;) cùng các ứng dụng trong giảm chiều, khử nhiễu và phát hiện bất thường.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần lý thuyết autoencoder, xem &lt;strong&gt;12-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về không gian ẩn cho mô hình khuếch tán, bộ nén âm thanh nơ-ron và masked autoencoder.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, tiếng Anh. Giới thiệu trực quan nguyên lý nén và tái tạo của autoencoder, trọng tâm của chương này.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, tiếng Anh. Đặt kiến trúc nút thắt thông tin của autoencoder trong bức tranh chung của các mô hình sinh.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Phần trình bày về autoencoder trong bài giảng năm 2024 trước khi chuyển sang VAE.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Chỉ vài năm trước, GAN vẫn là “vị vua không ngai” của thế giới sinh ảnh; thế nhưng ngày nay, từ Stable Diffusion 3, Flux đến các hệ thống tạo video siêu thực, sân khấu trung tâm đã thuộc về &lt;strong&gt;Mô hình Khuếch tán (Diffusion)&lt;/strong&gt; và &lt;strong&gt;Flow Matching&lt;/strong&gt;. Điều gì khiến ý tưởng “phá hủy ảnh bằng nhiễu rồi học cách khử nhiễu từng bước” lại đánh bại được cả cuộc đấu trí đối kháng lẫn chuỗi tự hồi quy? Bài cập nhật này giải mã bước chuyển mình quan trọng nhất của AI tạo sinh giai đoạn 2022–2026.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-ai-tạo-sinh-hiện-đại-20222026&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của AI tạo sinh hiện đại (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Quá trình khuếch tán thuận và ngược (DDPM / Score Matching):&lt;/strong&gt; Thêm nhiễu chuẩn hóa theo lịch trình \(\bar{\alpha}_t\) rồi huấn luyện mạng dự đoán nhiễu \(\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t)\) (tương đương học trường điểm số \(\nabla_{\mathbf{x}} \log p_t(\mathbf{x})\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Flow Matching và đường đi thẳng (Rectified Flow):&lt;/strong&gt; Thay quỹ đạo nhiễu cong phức tạp bằng phép nội suy tuyến tính \(\mathbf{x}_t = (1-t)\mathbf{x}_0 + t\mathbf{x}_1\) và học trường vận tốc \(\mathbf{v}_\theta(\mathbf{x}_t, t) \approx \mathbf{x}_1 - \mathbf{x}_0\) giúp giảm mạnh số bước lấy mẫu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khuếch tán trong không gian ẩn (Latent Diffusion) và DiT:&lt;/strong&gt; Kết hợp bộ nén VAE (Chương 12–13) với kiến trúc Diffusion Transformer để mở rộng lên độ phân giải cao và dữ liệu video.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hệ sinh thái dẫn đường và tăng tốc:&lt;/strong&gt; Classifier-Free Guidance (CFG) để bám sát prompt văn bản, cùng các bộ giải ODE/SDE và chưng cất vài bước cho suy luận thực tế.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-thêm-nhiễu-ddpm-và-mục-tiêu-vận-tốc-flow-matching&quot;&gt;Giải thích: Tính tay một bước thêm nhiễu DDPM và mục tiêu vận tốc Flow Matching&lt;/h3&gt;

&lt;p&gt;Xét một giá trị điểm ảnh (đã chuẩn hóa) \(x_0 = 0{,}8\) và một mẫu nhiễu chuẩn \(\epsilon = -0{,}5\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Quá trình thuận DDPM tại bước \(t\) với \(\bar{\alpha}_t = 0{,}64\):&lt;/strong&gt;
   \(x_t = \sqrt{\bar{\alpha}_t}\,x_0 + \sqrt{1 - \bar{\alpha}_t}\,\epsilon = \sqrt{0{,}64}(0{,}8) + \sqrt{0{,}36}(-0{,}5) = 0{,}8(0{,}8) + 0{,}6(-0{,}5) = 0{,}64 - 0{,}30 = 0{,}34.\)
   Mạng nhận đầu vào \((x_t = 0{,}34, t)\) và phải dự đoán \(\hat{\epsilon}\) gần \(-0{,}5\). Nếu mạng dự đoán \(\hat{\epsilon} = -0{,}4\), loss MSE đơn giản là \((-0{,}4 - (-0{,}5))^2 = 0{,}01\) — hoàn toàn không cần trò chơi minimax!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Mục tiêu Flow Matching (đường đi thẳng) tại \(t = 0{,}5\) giữa nhiễu \(x_0^{\text{nhiễu}} = -0{,}5\) và ảnh thật \(x_1 = 0{,}8\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Điểm trung gian: \(x_{0{,}5} = (1 - 0{,}5)(-0{,}5) + 0{,}5(0{,}8) = 0{,}15\).&lt;/li&gt;
  &lt;li&gt;Vận tốc mục tiêu không đổi dọc đường thẳng: \(u_t = x_1 - x_0^{\text{nhiễu}} = 0{,}8 - (-0{,}5) = 1{,}3\).&lt;/li&gt;
  &lt;li&gt;Khi suy luận bằng 2 bước Euler (\(\Delta t = 0{,}5\)) với vận tốc chuẩn \(v = 1{,}3\): \(-0{,}5 \xrightarrow{+0{,}65} 0{,}15 \xrightarrow{+0{,}65} 0{,}80\) — chạm đúng ảnh thật chỉ sau 2 bước vì quỹ đạo là đường thẳng!&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;tùy-chọn-mô-hình-sinh-sau-gan--khuếch-tán-và-flow-matching&quot;&gt;Tùy chọn: Mô hình sinh sau GAN — Khuếch tán và Flow Matching&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế phần nền tảng về hàm hợp lý, MLE và đánh giá mô hình của chương, cũng &lt;strong&gt;không&lt;/strong&gt; thay thế các chương về VAE hay GAN. Nội dung ghi nhận sự chuyển dịch lớn giai đoạn 2022–2026: &lt;strong&gt;mô hình khuếch tán dựa trên score&lt;/strong&gt; và &lt;strong&gt;flow matching&lt;/strong&gt; đã trở thành lựa chọn mặc định cho sinh ảnh, sau đó mở rộng sang video và âm thanh.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Nguyên lý cốt lõi vẫn giữ nguyên: một mô hình sinh biểu diễn phân phối \(p_\theta(\mathbf{x})\) cho phép lấy mẫu và (lý tưởng nhất) đánh giá xác suất. Điểm thay đổi nằm ở &lt;em&gt;họ&lt;/em&gt; mô hình \(p_\theta\) được triển khai rộng rãi trong thực tế.&lt;/p&gt;

&lt;h2 id=&quot;1-mô-hình-khuếch-tán-khử-nhiễu-tổng-quan&quot;&gt;1. Mô hình khuếch tán khử nhiễu (tổng quan)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2006.11239&quot;&gt;Ho et al., 2020&lt;/a&gt; (DDPM) và làn sóng khuếch tán không gian ẩn năm 2022 (&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;Rombach et al., 2022&lt;/a&gt;, Stable Diffusion) huấn luyện mạng khử nhiễu \(\boldsymbol{\varepsilon}_\theta(\mathbf{x}_t, t)\) đảo ngược một quá trình thêm nhiễu thuận. Hàm mất mát rút gọn thường có dạng:&lt;/p&gt;

\[\mathcal{L} = \mathbb{E}_{t,\mathbf{x}_0,\boldsymbol{\varepsilon}}\big\|\boldsymbol{\varepsilon} - \boldsymbol{\varepsilon}_\theta(\mathbf{x}_t, t)\big\|^2, \quad
\mathbf{x}_t = \sqrt{\bar{\alpha}_t}\,\mathbf{x}_0 + \sqrt{1-\bar{\alpha}_t}\,\boldsymbol{\varepsilon}.\]

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2212.09748&quot;&gt;Peebles &amp;amp; Xie, 2023&lt;/a&gt; (DiT) thay mạng khử nhiễu bằng kiến trúc Transformer, còn &lt;a href=&quot;https://arxiv.org/abs/2403.03206&quot;&gt;Esser et al., 2024&lt;/a&gt; (SD3) chuyển dần sang mục tiêu flow matching / rectified flow trong không gian ẩn.&lt;/p&gt;

&lt;h2 id=&quot;2-flow-matching&quot;&gt;2. Flow Matching&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.02747&quot;&gt;Lipman et al., 2023&lt;/a&gt; huấn luyện trường vector vận tốc \(v_\theta(\mathbf{x}, t)\) dọc theo đường xác suất nối giữa phân phối nhiễu và phân phối dữ liệu. Với quỹ đạo nội suy thẳng \(\mathbf{x}_t = (1-t)\mathbf{z} + t\mathbf{x}\), mục tiêu hồi quy có dạng:&lt;/p&gt;

\[\mathcal{L}_{\mathrm{FM}} = \mathbb{E}_{t,\mathbf{x},\mathbf{z}}\big\| v_\theta(\mathbf{x}_t, t) - (\mathbf{x} - \mathbf{z}) \big\|^2.\]

&lt;p&gt;Hướng tiếp cận theo phương trình vi phân thường (ODE) với quỹ đạo thẳng hơn này là nền tảng của nhiều hệ thống sinh ảnh và video giai đoạn 2023–2025 như Stable Diffusion 3 và dòng mô hình Flux.&lt;/p&gt;

&lt;h2 id=&quot;3-ứng-dụng-tiêu-biểu&quot;&gt;3. Ứng dụng tiêu biểu&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Sinh ảnh và video từ văn bản:&lt;/strong&gt; Stable Diffusion, SDXL, SD3 và các hệ thống khuếch tán video thương mại.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoa học dữ liệu:&lt;/strong&gt; tạo ảnh hoặc dữ liệu bảng tổng hợp khi quy định bảo mật không cho phép dùng trực tiếp dữ liệu thật (vẫn đánh giá bằng các chỉ số như FID và mật độ đã trình bày trong chương).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vai trò tiếp nối của AE và GAN:&lt;/strong&gt; autoencoder (Chương 12) đóng vai trò tạo không gian &lt;em&gt;ẩn&lt;/em&gt; cho mô hình khuếch tán, còn GAN (Chương 14) vẫn hữu ích cho tổng hợp khuôn mặt, ánh xạ ngược (&lt;em&gt;inversion&lt;/em&gt;) và các bộ sinh một bước tốc độ cao.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-thư-viện-và-mã-nguồn-phổ-biến&quot;&gt;4. Thư viện và mã nguồn phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/diffusers&quot;&gt;Hugging Face diffusers&lt;/a&gt; — cung cấp pipeline cho DDPM, LDM và flow matching.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/Stability-AI/sd3&quot;&gt;Stability-AI / SD3&lt;/a&gt; và &lt;a href=&quot;https://github.com/black-forest-labs/flux&quot;&gt;black-forest-labs/flux&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/openai/guided-diffusion&quot;&gt;openai/guided-diffusion&lt;/a&gt; — mã nguồn huấn luyện tham chiếu giai đoạn 2022.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-tài-liệu-tham-khảo-20222026&quot;&gt;5. Tài liệu tham khảo (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;Latent Diffusion Models (Rombach et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2212.09748&quot;&gt;DiT (Peebles &amp;amp; Xie, 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.02747&quot;&gt;Flow Matching (Lipman et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2403.03206&quot;&gt;SD3 (Esser et al., 2024)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;6-phần-bổ-sung-so-với-nội-dung-cốt-lõi&quot;&gt;6. Phần bổ sung so với nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên học vững MLE, sự khác biệt giữa mật độ tường minh và mật độ ẩn, cũng như ví dụ GAN đơn giản trong chương này trước. Khuếch tán và flow matching là &lt;strong&gt;bản cập nhật các họ mô hình hiện đại&lt;/strong&gt;, không thay thế các định nghĩa cơ bản đó; chi tiết về VAE và GAN vẫn nằm ở Chương 13 và 14.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=firXjwZ_6KI&quot;&gt;Flow-Matching vs Diffusion Models explained side by side&lt;/a&gt; — AI Coffee Break with Letitia, tiếng Anh. So sánh trực tiếp flow matching và khuếch tán khử nhiễu, khớp với bức tranh giai đoạn 2022–2026 trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But how do AI images and videos actually work?&lt;/td&gt;
          &lt;td&gt;Guest video by Welch Labs](https://www.youtube.com/watch?v=iv-5mZ_9CPY) — 3Blue1Brown, tiếng Anh. Giải thích cách mô hình khuếch tán biến nhiễu thành ảnh, bao gồm cả kỹ thuật classifier-free guidance.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=J87hffSMB60&quot;&gt;How does Stable Diffusion work? – Latent Diffusion Models EXPLAINED&lt;/a&gt; — AI Coffee Break with Letitia, tiếng Anh. Trình bày mô hình khuếch tán trong không gian ẩn — dạng triển khai thực tế phổ biến nhất của các ý tưởng này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-01 Mô hình Sinh - Các Khái niệm Cốt lõi</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_01_Generative_Models_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_01_Generative_Models_Fundamentals</id>
   <content type="html">&lt;p&gt;Trước khi bước vào từng kiến trúc chuyên sâu như Autoencoder, VAE hay GAN ở các chương sau, bạn cần một tấm la bàn chung để không bị lạc giữa rừng thuật ngữ: tại sao có mô hình cần tích phân, mô hình lại cần hai mạng đấu nhau, còn mô hình khác lại dự đoán từng pixel một? Mục tổng quan cốt lõi này đặt tất cả các họ mô hình sinh lên cùng một hệ quy chiếu xác suất.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-hệ-quy-chiếu-thống-nhất-các-mô-hình-sinh-cốt-lõi&quot;&gt;Kiến thức cần nhớ: Hệ quy chiếu thống nhất các mô hình sinh cốt lõi&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bản chất học mật độ dữ liệu:&lt;/strong&gt; Mọi mô hình sinh đều hướng tới việc xấp xỉ \(p_{\text{data}}(\mathbf{x})\), khác biệt nằm ở việc chúng xấp xỉ &lt;em&gt;trực tiếp hàm mật độ&lt;/em&gt; hay &lt;em&gt;trực tiếp bộ lấy mẫu&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tam giác đánh đổi của mô hình sinh:&lt;/strong&gt; Ba thuộc tính khó đồng thời đạt tối ưu tuyệt đối — chất lượng mẫu cao, độ phủ phân phối (đa dạng) rộng, và tốc độ lấy mẫu nhanh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kết nối lý thuyết sang mã nguồn:&lt;/strong&gt; Liên kết bài &lt;strong&gt;11-01-01 (Lý thuyết)&lt;/strong&gt; về MLE/KL/ELBO với bài &lt;strong&gt;11-01-02 (Cài đặt)&lt;/strong&gt; để kiểm chứng trực tiếp sự đánh đổi trên dữ liệu thật.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước đệm tới mô hình hiện đại:&lt;/strong&gt; Đặt nền móng để đọc hiểu cách khuếch tán (Diffusion) và Flow Matching dung hòa các đánh đổi của thế hệ cổ điển.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-đối-chiếu-tốc-độ-sinh-và-khả-năng-tính-xác-suất-trên-một-ảnh-32-times-32-times-3&quot;&gt;Giải thích: Đối chiếu tốc độ sinh và khả năng tính xác suất trên một ảnh \(32 \times 32 \times 3\)&lt;/h3&gt;

&lt;p&gt;Xét một ảnh màu nhỏ kích thước \(32 \times 32 \times 3 = 3{,}072\) giá trị kênh màu. Giả sử một lượt suy luận mạng mất \(1\text{ ms}\) trên GPU:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình tự hồi quy (kiểu PixelCNN):&lt;/strong&gt; Để sinh trọn 1 ảnh, phải chạy mạng tuần tự qua từng thành phần: \(3{,}072 \times 1\text{ ms} = 3{,}072\text{ ms} \approx 3{,}07\text{ giây/ảnh}\), đổi lại ta tính được chính xác \(\log p(\mathbf{x})\) chỉ trong 1 lượt song song khi huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;VAE / GAN:&lt;/strong&gt; Sinh toàn bộ \(3{,}072\) giá trị trong đúng &lt;strong&gt;1 lượt xuôi&lt;/strong&gt; từ vector ẩn \(\mathbf{z}\): thời gian chỉ \(1\text{ ms/ảnh}\) — nhanh hơn hơn &lt;strong&gt;3.000 lần&lt;/strong&gt; lúc sinh! Đổi lại, VAE chỉ cho cận dưới ELBO, còn GAN không tính được \(\log p(\mathbf{x})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài học kiến trúc:&lt;/strong&gt; Chỉ từ một phép nhân đơn giản, ta thấy ngay lý do công nghiệp vừa cần tính toán song song (lúc huấn luyện) vừa cần giảm số bước lấy mẫu (lúc suy luận) — động lực trực tiếp thúc đẩy các kỹ thuật chưng cất và flow matching sau này.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nội dung nền tảng về mô hình sinh gồm hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết&lt;/strong&gt; — tổng quan khái niệm, cơ sở toán học và ví dụ trực quan.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt&lt;/strong&gt; — mã nguồn minh họa, bài báo nền tảng, các cạm bẫy thường gặp và điểm then chốt.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Làm rõ sự phân biệt giữa mô hình mật độ tường minh và mô hình lấy mẫu ẩn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, tiếng Anh. Cách phân loại tương tự trong bài giảng CS231n mà phần học này bám theo.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Ví dụ cài đặt mô hình tự hồi quy, tương ứng với bài mã đầu tiên của phần này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-01-02 Cài đặt Mô hình Sinh</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_01_02_Generative_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_01_02_Generative_Implementation</id>
   <content type="html">&lt;p&gt;Đọc công thức MLE hay minimax thường mang lại cảm giác mọi thứ đều trơn tru, cho đến khi bạn bấm chạy vòng lặp huấn luyện đầu tiên và thấy đường loss nhảy múa không ngừng. Trang tổng hợp cài đặt này đóng vai trò cầu nối giữa hai thế giới: biến lý thuyết mô hình sinh thành mã nguồn chạy được trên bộ dữ liệu 8-Gaussian kinh điển để bạn trực tiếp so sánh mô hình tự hồi quy với GAN.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-lộ-trình-từ-mô-hình-toán-học-sang-thí-nghiệm-sinh-dữ-liệu&quot;&gt;Kiến thức cần nhớ: Lộ trình từ mô hình toán học sang thí nghiệm sinh dữ liệu&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thiết kế tập dữ liệu chuẩn đoán (Toy Benchmark):&lt;/strong&gt; Dùng hỗn hợp 8 phân phối chuẩn 2D đặt trên vòng tròn giúp trực quan hóa tức thì độ phủ mode, độ sắc nét và mật độ tràn mà không cần GPU lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhánh 1 — Cài đặt tự hồi quy:&lt;/strong&gt; Thực hành tách biến, tối ưu NLL chính xác và sinh mẫu tuần tự để thấy ưu thế ổn định của mật độ tường minh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhánh 2 — Cài đặt GAN và kiểm tra bẫy:&lt;/strong&gt; Thực hành vòng lặp đối kháng, đo độ phủ mode tự động và nhận diện lỗi huấn luyện phổ biến.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá thực nghiệm đa góc nhìn:&lt;/strong&gt; Kết hợp cả thước đo định lượng (log-likelihood, số mode phủ được) lẫn trực quan hóa phân bố mẫu sinh.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-cách-tính-nhanh-chỉ-số-độ-phủ-mode-mode-coverage-trên-8-cụm-gaussian&quot;&gt;Giải thích: Cách tính nhanh chỉ số độ phủ mode (Mode Coverage) trên 8 cụm Gaussian&lt;/h3&gt;

&lt;p&gt;Giả sử 8 tâm cụm nằm trên vòng tròn bán kính \(R = 2{,}0\) tại các góc \(\theta_k = \frac{2\pi k}{8}\) (\(k = 0,\dots,7\)), mỗi cụm có độ lệch chuẩn \(\sigma = 0{,}1\). Ta rút \(N = 800\) mẫu từ mô hình và gán mỗi mẫu vào tâm gần nhất nếu khoảng cách Euclid \(d &amp;lt; 3\sigma = 0{,}3\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kỳ vọng lý tưởng:&lt;/strong&gt; Mỗi cụm nhận khoảng \(800 / 8 = 100\) mẫu (\(12{,}5\%\)), tỷ lệ mẫu hợp lệ (nằm trong bán kính \(0{,}3\) quanh một tâm) đạt gần \(99\%\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kịch bản GAN bị sụp đổ mode:&lt;/strong&gt; Giả sử đếm được số mẫu ở 8 cụm là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[390, 0, 0, 385, 0, 0, 0, 0]&lt;/code&gt; và \(25\) mẫu rơi ngoài bán kính \(0{,}3\).
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Độ phủ mode:&lt;/strong&gt; chỉ \(2/8 = 25\%\) (thất bại nghiêm trọng dù \(775/800 = 96{,}9\%\) mẫu trông “rất thật”!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kịch bản tự hồi quy đơn đỉnh:&lt;/strong&gt; Phủ được cả \(8/8\) hướng nhưng có tới \(320/800 = 40\%\) mẫu rơi vào khoảng trống giữa các cụm (chất lượng cao về độ phủ nhưng thấp về độ sắc nét). Con số đơn giản này cho thấy vì sao một chỉ số duy nhất không bao giờ đủ để đánh giá mô hình sinh.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Phần cài đặt mô hình sinh gồm hai bài:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình tự hồi quy (Autoregressive Model)&lt;/strong&gt; — tạo tập dữ liệu hỗn hợp 2D đơn giản và huấn luyện mô hình tự hồi quy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GAN đơn giản, Bài báo và Bẫy thường gặp&lt;/strong&gt; — cài đặt GAN để so sánh trực tiếp, giới thiệu các chỉ số đánh giá, bài báo nền tảng và điểm then chốt.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Minh họa trực tiếp nhánh cài đặt mô hình tự hồi quy.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, tiếng Anh. Giải thích cơ chế mô hình GAN đơn giản được huấn luyện ở bài thứ hai.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Giúp phân biệt rõ mục tiêu và hàm mất mát của từng họ mô hình khi cài đặt.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-01-02-02 GAN Toy, Bài báo và Bẫy thường gặp</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_01_02_02_Toy_GAN_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_01_02_02_Toy_GAN_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Nếu mô hình tự hồi quy giống một nghệ nhân tỉ mỉ vẽ từng nét theo công thức xác suất, thì GAN lại giống một cuộc đấu trí kịch tính giữa kẻ làm tiền giả và chuyên gia kiểm định. Trên cùng tập dữ liệu 8 cụm Gaussian nằm trên vòng tròn, chỉ cần vài chục dòng mã là bạn sẽ chứng kiến tận mắt hiện tượng đáng sợ nhất của GAN: &lt;em&gt;mode collapse&lt;/em&gt; — khi bộ sinh bỏ mặc 7 cụm dữ liệu còn lại để chỉ vẽ đi vẽ lại đúng 1 cụm duy nhất nhằm đánh lừa bộ phân biệt.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cơ-chế-thực-nghiệm-và-các-bẫy-kinh-điển-khi-huấn-luyện-gan&quot;&gt;Kiến thức cần nhớ: Cơ chế thực nghiệm và các bẫy kinh điển khi huấn luyện GAN&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Vòng lặp đối kháng xen kẽ (Alternating Optimization):&lt;/strong&gt; Cập nhật bộ phân biệt \(D\) để tách mẫu thật/giả trước, rồi đóng băng \(D\) để cập nhật bộ sinh \(G\) theo hướng làm tăng xác suất \(D(G(\mathbf{z}))\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán sụp đổ mode (Mode Collapse):&lt;/strong&gt; Đo độ phủ trên từng tâm cụm thật để phát hiện sớm tình trạng \(G\) chỉ sinh ra các mẫu rất đẹp nhưng lặp đi lặp lại ở một vài vùng hẹp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh đổi giữa hợp lý tường minh và chất lượng mẫu:&lt;/strong&gt; So sánh trực tiếp trên cùng bộ dữ liệu toy giữa mô hình tự hồi quy (tính được NLL chính xác, phủ đều mode nhưng có thể tràn xác suất) và GAN (mẫu sắc nét nhưng không có log-likelihood).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỹ thuật ổn định thực hành:&lt;/strong&gt; Nhận biết bẫy bão hòa gradient của hàm loss gốc, lệch nhịp tốc độ học giữa \(G\) và \(D\), cùng giải pháp non-saturating loss.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-gradient-của-hàm-loss-gốc-và-non-saturating-loss-khi-dgmathbfz-gần-0&quot;&gt;Giải thích: So sánh gradient của hàm loss gốc và non-saturating loss khi \(D(G(\mathbf{z}))\) gần 0&lt;/h3&gt;

&lt;p&gt;Ở giai đoạn đầu huấn luyện, ảnh giả còn rất thô nên bộ phân biệt dễ dàng bác bỏ: giả sử \(D(G(\mathbf{z})) = 0{,}01\) (logit \(u = \text{logit}(0{,}01) \approx -4{,}595\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mục tiêu minimax gốc của \(G\):&lt;/strong&gt; \(\mathcal{L}_G^{\text{minimax}} = \ln(1 - D(G(\mathbf{z}))) = \ln(1 - \sigma(u))\).
Đạo hàm theo logit \(u\) là:
\(\frac{\partial \mathcal{L}_G^{\text{minimax}}}{\partial u} = -\sigma(u) = -0{,}01.\)
Độ lớn gradient chỉ bằng \(0{,}01\) — gần như &lt;strong&gt;triệt tiêu&lt;/strong&gt; đúng lúc \(G\) cần học mạnh nhất!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mục tiêu non-saturating (dùng trong thực tế):&lt;/strong&gt; \(\mathcal{L}_G^{\text{NS}} = -\ln D(G(\mathbf{z})) = -\ln \sigma(u)\).
Đạo hàm theo logit \(u\) là:
\(\frac{\partial \mathcal{L}_G^{\text{NS}}}{\partial u} = -(1 - \sigma(u)) = -(1 - 0{,}01) = -0{,}99.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kết luận định lượng:&lt;/strong&gt; Tại cùng một trạng thái \(D(G(\mathbf{z})) = 0{,}01\), non-saturating loss tạo ra tín hiệu gradient &lt;strong&gt;mạnh gấp 99 lần&lt;/strong&gt; so với công thức minimax gốc, giúp \(G\) thoát khỏi điểm chết ban đầu mà vẫn giữ nguyên điểm tối ưu toàn cục.&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 2. GAN đơn giản để so sánh
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Huấn luyện GAN (Mật độ Ẩn)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyGenerator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generator đơn giản cho dữ liệu 2D&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Xuất điểm 2D
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyDiscriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Discriminator đơn giản cho dữ liệu 2D&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LeakyReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LeakyReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;gen&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyGenerator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;disc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyDiscriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;gen_optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0002&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;betas&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;disc_optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0002&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;betas&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BCELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện GAN trên hỗn hợp Gaussian...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Huấn luyện discriminator
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# k bước discriminator mỗi bước generator
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Dữ liệu thật
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;batch_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,))]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_d_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Dữ liệu giả
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_d_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;loss_d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss_d_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss_d_fake&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;disc_optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Huấn luyện generator
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;labels_real_for_g&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss_g&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_real_for_g&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;loss_g&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;gen_optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: D_loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;G_loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_g&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;D(real) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;D(fake) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh mẫu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;z_sample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;samples_gan&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GAN đã sinh &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_gan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; mẫu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kiểm tra phủ mode (mẫu nên cụm quanh 8 tâm)...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra GAN có phủ mọi mode không (phát hiện sụp đổ mode)
# Với mỗi tâm thật, đếm mẫu sinh lân cận
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_centers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;distances&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_gan&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;nearby&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;distances&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mode &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (tâm &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nearby&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; mẫu lân cận&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_gan&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt; 
       &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_centers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✓ GAN phủ thành công mọi mode!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✗ Phát hiện sụp đổ mode — một số mode có ít/không có mẫu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;So sánh Mô hình hóa Sinh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mô hình Tự hồi quy:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Hợp lý chính xác tính được&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Huấn luyện ổn định&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Sinh tuần tự (chậm)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Giả định thứ tự mạnh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GAN:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Sinh song song nhanh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Thường chất lượng mẫu cao&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Không có hợp lý tường minh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Huấn luyện có thể bất ổn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Rủi ro sụp đổ mode&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;VAE (chương sau):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Không gian ẩn tường minh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Huấn luyện ổn định&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Sinh nhanh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Mẫu đôi khi mờ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Đoạn mã dưới đây minh họa cách đánh giá mô hình dựa trên log-hợp lý (với mô hình tự hồi quy) và các chỉ số thay thế (với GAN):&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đánh giá Chất lượng Mô hình Sinh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Với mô hình tự hồi quy, ta có thể tính hợp lý chính xác
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Tập kiểm tra (dữ liệu giữ lại từ cùng phân phối)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;data_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_mixture_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;data_test_tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tính log-hợp lý trên tập kiểm tra
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;test_log_probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_test_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;avg_test_ll&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_log_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Log-hợp lý Kiểm tra Mô hình Tự hồi quy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_test_ll&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cao hơn thì tốt hơn — mô hình gán xác suất cao cho dữ liệu kiểm tra&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Sinh và đánh giá (mẫu nên có hợp lý tương tự dữ liệu thật)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;samples_ar_eval&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;samples_log_probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_ar_eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;avg_sample_ll&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;samples_log_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Log-hợp lý Mẫu Sinh: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_sample_ll&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nên tương tự LL kiểm tra nếu mô hình tốt&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_test_ll&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;avg_sample_ll&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✓ Chênh lệch nhỏ (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;) chỉ ra mô hình tốt!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✗ Chênh lệch lớn (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;) chỉ ra vấn đề&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Với GAN, ta không tính được hợp lý, nên dùng chỉ số proxy
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đánh giá GAN (không có hợp lý tường minh):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Kiểm tra bằng mắt (mẫu trông thực tế không?)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Phủ mode (mẫu có trải mọi mode không?)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Đa dạng (mẫu có biến thiên hay lặp lại?)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Điểm discriminator (nên ~0.5 với generator tốt)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;disc_scores_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_test_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;disc_scores_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_gan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Điểm discriminator:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Dữ liệu thật: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;disc_scores_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (nên ~1.0 nếu D tốt)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mẫu sinh: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;disc_scores_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (nên ~0.5 ở cân bằng)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;disc_scores_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;disc_scores_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✓ Generator đánh lừa thành công discriminator!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-các-khái-niệm-liên-quan&quot;&gt;5. Các khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Mô hình sinh gắn trực tiếp với bài toán ước lượng mật độ (&lt;em&gt;density estimation&lt;/em&gt;) trong thống kê cổ điển. Các phương pháp truyền thống như ước lượng mật độ hạt nhân (&lt;em&gt;kernel density estimation&lt;/em&gt;) hay mô hình hỗn hợp Gaussian hoạt động tốt ở số chiều thấp, nhưng nhanh chóng suy giảm khi số chiều tăng cao do lời nguyền số chiều (&lt;em&gt;curse of dimensionality&lt;/em&gt;). Mô hình sinh sâu vượt qua hạn chế này bằng cách học các tầng đặc trưng phân cấp nắm bắt cấu trúc dữ liệu, thực chất ước lượng mật độ trong một không gian biểu diễn có cấu trúc đơn giản hơn rồi ánh xạ ngược về không gian dữ liệu gốc.&lt;/p&gt;

&lt;p&gt;Mô hình hóa sinh cũng liên hệ mật thiết với học không giám sát và học tự giám sát (&lt;em&gt;self-supervised learning&lt;/em&gt;). Vì không đòi hỏi nhãn, mô hình buộc phải tự khám phá quy luật nội tại của dữ liệu. Các biểu diễn học được thường chuyển giao tốt sang các tác vụ giám sát về sau — chẳng hạn bộ mã hóa của autoencoder và VAE hay đặc trưng trung gian của bộ phân biệt trong GAN. Xu hướng tiền huấn luyện tự giám sát quy mô lớn (như các mô hình ngôn ngữ BERT hoặc GPT) rồi tinh chỉnh cho bài toán cụ thể cũng bắt nguồn từ cùng nguyên lý này.&lt;/p&gt;

&lt;p&gt;Trong thực hành, mô hình sinh còn được dùng để tăng cường dữ liệu bằng mẫu tổng hợp, đặc biệt khi tập dữ liệu mất cân bằng lớp hoặc chi phí gán nhãn cao (như ảnh y khoa). Tuy nhiên, nếu mô hình sinh chưa khớp tốt với phân phối thật, dữ liệu tổng hợp có thể khuếch đại sai lệch sẵn có; vì vậy luôn cần kiểm chứng xem dữ liệu sinh thêm có thực sự cải thiện hiệu năng trên tập kiểm tra thật hay không.&lt;/p&gt;

&lt;p&gt;Sự phát triển của các chỉ số đánh giá cũng phản ánh mức độ khó của việc định lượng đồng thời chất lượng và độ đa dạng. Sau giai đoạn dựa vào đánh giá thủ công hoặc bộ phân loại nhị phân, các chỉ số tự động như Inception Score và FID được dùng phổ biến hơn dù vẫn có những thiên lệch nhất định. Các hướng đánh giá sau này bổ sung thêm khoảng cách cảm nhận (&lt;em&gt;perceptual distance&lt;/em&gt;), đường cong precision–recall để tách riêng chất lượng với độ đa dạng, cùng các phép đo dựa trên hàm hợp lý khi mô hình hỗ trợ. Do không có một chỉ số đơn lẻ nào phản ánh toàn diện, thực hành tốt nhất là kết hợp nhiều thước đo bổ trợ nhau.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-06.pdf&quot;&gt;“A tutorial on Energy-Based Learning” (2006)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Yann LeCun&lt;br /&gt;
Bài hướng dẫn này xây dựng khung học dựa trên năng lượng (&lt;em&gt;energy-based learning&lt;/em&gt;), nền tảng lý thuyết của nhiều hướng mô hình hóa sinh. Ý tưởng trung tâm là học một hàm năng lượng gán giá trị thấp cho các cấu hình dữ liệu hợp lệ và giá trị cao cho các cấu hình bất hợp lý. Khung này bao quát máy Boltzmann, &lt;em&gt;contrastive divergence&lt;/em&gt; và kết nối mô hình hóa sinh với vật lý thống kê. Dù các mô hình hiện đại thường dùng lan truyền ngược kết hợp tái tham số hóa hoặc huấn luyện đối kháng, góc nhìn năng lượng vẫn rất hữu ích để hiểu cơ chế hoạt động chung của các thuật toán sinh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://proceedings.mlr.press/v15/larochelle11a.html&quot;&gt;“NADE: The Neural Autoregressive Distribution Estimator” (2011)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Hugo Larochelle, Iain Murray&lt;br /&gt;
Bài báo giới thiệu NADE, một mô hình tự hồi quy sử dụng mạng nơ-ron chia sẻ trọng số để tính chính xác và hiệu quả tích phân rã \(p(\mathbf{x}) = \prod_i p(x_i|\mathbf{x}_{&amp;lt;i})\). Nhờ chia sẻ tham số thay vì huấn luyện mạng riêng cho từng phân phối điều kiện, NADE vừa giảm chi phí tính toán vừa hạn chế quá khớp, đồng thời đạt kết quả cạnh tranh với máy Boltzmann hạn chế (RBM). NADE đặt nền móng trực tiếp cho các kiến trúc tự hồi quy về sau như PixelRNN/PixelCNN cho ảnh và WaveNet cho âm thanh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.6114&quot;&gt;“Auto-Encoding Variational Bayes” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Diederik P. Kingma, Max Welling&lt;br /&gt;
Bài báo giới thiệu Variational Autoencoder (VAE), kết hợp suy diễn biến phân với mạng nơ-ron sâu cho mô hình biến ẩn. Đóng góp cốt lõi là thủ thuật tái tham số hóa (&lt;em&gt;reparameterization trick&lt;/em&gt;): thay vì lấy mẫu trực tiếp \(\mathbf{z} \sim q(\mathbf{z}|\mathbf{x})\) (không khả vi theo tham số của \(q\)), biểu diễn \(\mathbf{z} = \mu + \sigma \odot \boldsymbol{\epsilon}\) với \(\boldsymbol{\epsilon} \sim \mathcal{N}(0, I)\). Cách viết này cho phép lan truyền ngược gradient qua phép lấy mẫu để tối ưu mục tiêu ELBO bằng hạ gradient, đưa VAE trở thành một trong những công cụ chuẩn của học sâu xác suất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1406.2661&quot;&gt;“Generative Adversarial Networks” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ian Goodfellow và cộng sự&lt;br /&gt;
Bài báo mở ra hướng huấn luyện đối kháng thay thế cho ước lượng hợp lý cực đại. Bằng cách mô hình hóa quá trình sinh như trò chơi hai người giữa bộ sinh và bộ phân biệt, GAN học trực tiếp hàm lấy mẫu mà không cần tính hàm mật độ tường minh hay tích phân biên. Phần phân tích lý thuyết chứng minh tại điểm cân bằng Nash, phân phối của bộ sinh trùng với phân phối dữ liệu thật. Ý tưởng huấn luyện đối kháng sau đó không chỉ thúc đẩy mảng sinh ảnh mà còn mở rộng sang thích ứng miền, tăng độ bền vững và học bán giám sát.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1912.02762&quot;&gt;“Normalizing Flows for Probabilistic Modeling and Inference” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: George Papamakarios, Eric Nalisnick, Danilo Jimenez Rezende, Shakir Mohamed, Balaji Lakshminarayanan&lt;br /&gt;
Bài tổng quan hệ thống hóa nhóm mô hình &lt;em&gt;normalizing flows&lt;/em&gt; dựa trên chuỗi phép biến đổi song ánh khả nghịch \(\mathbf{x} = f(\mathbf{z})\) có định thức Jacobian tính được. Cách tiếp cận này đồng thời cho phép tính log-hợp lý chính xác (khác với GAN) và lấy mẫu nhanh (khác với mô hình tự hồi quy). Bài báo bao quát các kiến trúc chính (&lt;em&gt;coupling flow&lt;/em&gt;, &lt;em&gt;autoregressive flow&lt;/em&gt;, &lt;em&gt;continuous flow&lt;/em&gt;) và chỉ ra thế mạnh của nhóm mô hình này trong các bài toán yêu cầu mật độ chính xác như phát hiện bất thường, nén dữ liệu hoặc thiết kế phân tử.&lt;/p&gt;

&lt;h2 id=&quot;bẫy-thường-gặp-và-mẹo&quot;&gt;Bẫy thường gặp và Mẹo&lt;/h2&gt;

&lt;p&gt;Một sai lầm phổ biến là chỉ đánh giá mô hình sinh qua log-hợp lý trên tập huấn luyện hoặc sai số tái tạo. Một mô hình học thuộc lòng tập huấn luyện vẫn có thể đạt giá trị tối ưu rất tốt nhưng không tạo ra được mẫu mới. Để kiểm tra hiện tượng này, cần tìm láng giềng gần nhất trong tập huấn luyện cho các mẫu sinh ra và luôn đánh giá trên tập kiểm tra độc lập. Các biện pháp phòng tránh gồm dùng chính quy hóa phù hợp (weight decay, dropout), chọn mô hình trên tập validation và thiết kế kiến trúc hạn chế sao chép trực tiếp.&lt;/p&gt;

&lt;p&gt;Lựa chọn hàm mất mát tái tạo không phù hợp cũng dễ tạo chênh lệch giữa giá trị tối ưu và cảm nhận thị giác. MSE theo từng điểm ảnh xem mọi sai lệch là như nhau, trong khi mắt người nhạy hơn nhiều với cấu trúc và biên cạnh, dẫn đến hiện tượng ảnh tái tạo bị mờ khi tối ưu MSE. Các phương án cải thiện gồm hàm mất mát cảm nhận (&lt;em&gt;perceptual loss&lt;/em&gt; tính trong không gian đặc trưng của mạng tiền huấn luyện như VGG), hàm mất mát đối kháng hoặc các hàm đo tương đồng cấu trúc.&lt;/p&gt;

&lt;p&gt;Trong mô hình biến ẩn, kích thước không gian ẩn cần được chọn cân bằng. Số chiều quá nhỏ (2–3 chiều) thuận tiện cho việc trực quan hóa nhưng khó giữ đủ thông tin phức tạp của dữ liệu. Ngược lại, số chiều quá lớn (gần bằng số chiều đầu vào) khiến mô hình dễ học ánh xạ đồng nhất mà không rút trích được cấu trúc hữu ích. Một quy tắc khởi đầu hợp lý là tỷ lệ nén khoảng 10–20 lần rồi tinh chỉnh theo chất lượng tái tạo và tác vụ đích — ví dụ khoảng 32–64 chiều cho MNIST (784 chiều) hoặc 512–2048 chiều cho ImageNet (224×224×3).&lt;/p&gt;

&lt;p&gt;Khi lấy mẫu từ mô hình tự hồi quy hoặc VAE, tham số nhiệt độ lấy mẫu (&lt;em&gt;sampling temperature&lt;/em&gt;) giúp điều chỉnh trực tiếp sự đánh đổi giữa chất lượng và độ đa dạng bằng cách chia logit cho \(T\) trước hàm softmax:&lt;/p&gt;

\[p(x_i | \mathbf{x}_{&amp;lt;i}) = \text{softmax}(\mathbf{z}_i / T)\]

&lt;p&gt;Nhiệt độ thấp (\(T &amp;lt; 1\)) làm phân phối tập trung hơn, mẫu sinh ổn định nhưng kém đa dạng; nhiệt độ cao (\(T &amp;gt; 1\)) tăng độ đa dạng nhưng dễ xuất hiện mẫu kém hợp lý. Đây là cơ chế điều chỉnh linh hoạt ở giai đoạn suy luận mà không cần huấn luyện lại mô hình.&lt;/p&gt;

&lt;p&gt;Ngoài ra, kỹ thuật &lt;em&gt;rejection sampling&lt;/em&gt; — sinh nhiều mẫu ứng viên, chấm điểm bằng bộ phân biệt hoặc bộ phân loại rồi chỉ giữ các mẫu đạt điểm cao — là cách hậu xử lý đơn giản để nâng chất lượng đầu ra trong các ứng dụng ưu tiên chất lượng hơn tốc độ sinh (như thiết kế đồ họa hay sinh cấu trúc phân tử).&lt;/p&gt;

&lt;h2 id=&quot;điểm-then-chốt&quot;&gt;Điểm then chốt&lt;/h2&gt;

&lt;p&gt;Mô hình sinh học cách nắm bắt và tái tạo phân phối xác suất của dữ liệu để tạo ra các mẫu mới hợp lệ. Ba hướng tiếp cận nền tảng — mô hình tự hồi quy (phân rã mật độ tuần tự tường minh), Variational Autoencoder (biến ẩn kết hợp suy diễn biến phân) và GAN (huấn luyện đối kháng mật độ ẩn) — tạo nên các điểm cân bằng khác nhau giữa khả năng tính hàm hợp lý, tốc độ lấy mẫu, độ ổn định khi huấn luyện và chất lượng mẫu. Ước lượng hợp lý cực đại cung cấp mục tiêu tối ưu có cơ sở lý thuyết chặt chẽ thông qua phân kỳ KL, còn mô hình biến ẩn mang lại không gian biểu diễn nén dễ thao tác và nội suy. Vì đánh giá mô hình sinh khó hơn bài toán phân loại, cần phối hợp nhiều thước đo (log-hợp lý khi có, Inception Score, FID, đánh giá trực quan và chỉ số chuyên ngành) thay vì dựa vào một con số duy nhất.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=Gib_kiXgnvA&quot;&gt;The Math Behind Generative Adversarial Networks Clearly Explained!&lt;/a&gt; — Normalized Nerd, tiếng Anh. Giải thích mục tiêu minimax tương ứng với hàm mất mát của mô hình GAN đơn giản trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, tiếng Anh. Trình bày trực quan trò chơi hai người giữa bộ sinh và bộ phân biệt trước khi đi vào mã nguồn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TpMIssRdhco&quot;&gt;What are GANs (Generative Adversarial Networks)?&lt;/a&gt; — IBM Technology, tiếng Anh. Minh họa ngắn gọn vai trò của bộ sinh và bộ phân biệt nếu bạn cần nhìn tổng quan trước phần toán học.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-01-02-01 Cài đặt Mô hình Tự hồi quy</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_01_02_01_Autoregressive_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_01_02_01_Autoregressive_Code</id>
   <content type="html">&lt;p&gt;Khi chuyển từ phương trình trên bảng đen sang những dòng mã PyTorch chạy thật, một câu hỏi thực tế lập tức nảy sinh: làm sao một mạng nơ-ron có thể học phân phối của 8 cụm điểm nằm trên một vòng tròn chỉ bằng cách dự đoán tọa độ \(x_2\) sau khi đã biết \(x_1\)? Trong bài thực hành này, ta sẽ tự tay lắp ráp một mô hình tự hồi quy tối giản cho dữ liệu 2D và nhìn thấy tận mắt cách mạng chuyển từ “đoán mù” sang vẽ trọn vẹn cấu trúc vòng tròn xác suất.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-cấu-trúc-kỹ-thuật-của-cài-đặt-mô-hình-tự-hồi-quy-2d&quot;&gt;Kiến thức cần nhớ: Cấu trúc kỹ thuật của cài đặt mô hình tự hồi quy 2D&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân rã hai chiều có điều kiện:&lt;/strong&gt; Biểu diễn mật độ đồng thời \(p(x_1, x_2) = p(x_1)\,p(x_2 \mid x_1)\), trong đó mô hình hóa phân phối biên \(p(x_1)\) và dùng mạng MLP dự đoán tham số \((\mu_2(x_1), \sigma_2(x_1))\) cho \(p(x_2 \mid x_1)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mất mát Negative Log-Likelihood (NLL) của phân phối chuẩn:&lt;/strong&gt; Chuyển đổi công thức mật độ Gaussian sang dạng ổn định số học bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log_var&lt;/code&gt; hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softplus&lt;/code&gt; để tránh phương sai âm và chia cho 0.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy trình lấy mẫu tuần tự (Ancestral Sampling):&lt;/strong&gt; Rút mẫu \(x_1 \sim p(x_1)\) trước, rồi đưa \(x_1\) vào mạng để lấy tham số và rút \(x_2 \sim p(x_2 \mid x_1)\), minh họa trực tiếp lý do mô hình tự hồi quy sinh chậm trên dữ liệu nhiều chiều.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giới hạn biểu diễn của phân phối điều kiện đơn đỉnh:&lt;/strong&gt; Nhận diện điểm yếu khi \(p(x_2 \mid x_1)\) thực tế có hai đỉnh (nửa trên và nửa dưới vòng tròn) nhưng mô hình chỉ dùng một Gaussian duy nhất.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-loss-nll-và-lấy-mẫu-tuần-tự-trên-điểm-x_1-x_2&quot;&gt;Giải thích: Tính tay một bước loss NLL và lấy mẫu tuần tự trên điểm \((x_1, x_2)\)&lt;/h3&gt;

&lt;p&gt;Giả sử với một điểm dữ liệu trên vòng tròn bán kính \(2\) là \((x_1, x_2) = (0{,}0,\; 2{,}0)\), mạng dự đoán phân phối điều kiện \(p(x_2 \mid x_1 = 0) = \mathcal{N}(\mu = 0{,}5,\; \sigma = 1{,}0)\) (tức \(\log \sigma^2 = 0\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính Negative Log-Likelihood cho chiều \(x_2\):&lt;/strong&gt;
\(-\ln p(x_2 \mid x_1) = \frac{1}{2}\ln(2\pi) + \ln \sigma + \frac{(x_2 - \mu)^2}{2\sigma^2} = 0{,}9189 + 0 + \frac{(2{,}0 - 0{,}5)^2}{2(1{,}0)^2} = 0{,}9189 + 1{,}125 = 2{,}0439.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient theo \(\mu\):&lt;/strong&gt;
\(\frac{\partial \text{NLL}}{\partial \mu} = -\frac{x_2 - \mu}{\sigma^2} = -\frac{2{,}0 - 0{,}5}{1{,}0} = -1{,}5.\)
Với tốc độ học \(\eta = 0{,}1\), bước cập nhật kéo \(\mu\) về phía \(x_2\): \(\mu_{\text{mới}} = 0{,}5 - 0{,}1(-1{,}5) = 0{,}65\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhận xét quan trọng trên vòng tròn:&lt;/strong&gt; Vì vòng tròn đối xứng nên tại \(x_1 = 0\) có cả \((0, +2)\) lẫn \((0, -2)\). Một Gaussian đơn đỉnh sẽ bị kéo về trung bình \(\mu = 0\) và phình to \(\sigma \approx 2\) — minh họa trực tiếp lý do trong thực tế ta cần &lt;strong&gt;hỗn hợp Gaussian (Mixture of Gaussians)&lt;/strong&gt; hoặc &lt;strong&gt;rời rạc hóa thành phân loại softmax&lt;/strong&gt; (như PixelCNN) để mô tả phân phối điều kiện đa đỉnh.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-đoạn-mã&quot;&gt;4. Đoạn mã&lt;/h2&gt;

&lt;p&gt;Dưới đây là phần cài đặt mô hình tự hồi quy trên một tập dữ liệu 2D đơn giản nhằm minh họa cơ chế huấn luyện và lấy mẫu của mô hình mật độ tường minh:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh dữ liệu toy: hỗn hợp 8 Gaussian trên một đường tròn
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_mixture_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Sinh dữ liệu 2D từ hỗn hợp 8 Gaussian sắp xếp theo vòng tròn.
    
    Tập dữ liệu toy này cho phép trực quan hóa các phân phối đã học và so sánh
    các cách tiếp cận mô hình hóa sinh khác nhau. Mỗi Gaussian biểu diễn một
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mode&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; — mô hình sinh nên học cách sinh từ mọi mode.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n_modes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;radius&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.02&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Góc cho các mode cách đều quanh vòng tròn
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;thetas&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_modes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;endpoint&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tâm của các Gaussian
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;centers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;radius&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;radius&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;thetas&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Lấy mẫu từ hỗn hợp
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Chọn mode đều
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;mode_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_modes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Lấy mẫu từ Gaussian đã chọn
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;sample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mode_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centers&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh dữ liệu huấn luyện
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mô hình Sinh trên Tập Dữ liệu Toy 2D&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;data_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_centers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_mixture_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đã sinh &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; mẫu từ 8 mode Gaussian&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hình dạng dữ liệu: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (10000, 2)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tâm các mode:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_centers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 1. Mô hình tự hồi quy đơn giản
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;AutoregressiveModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Mô hình tự hồi quy 2D đơn giản: p(x) = p(x2|x1) * p(x1)
    
    Mô hình hóa p(x1) như hỗn hợp logistic, p(x2|x1) như hỗn hợp điều kiện.
    Minh họa mô hình mật độ tường minh — ta có thể tính p(x) chính xác.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# p(x1): hỗn hợp logistic
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Parameter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Parameter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_scales&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Parameter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# p(x2|x1): mạng neuron xuất tham số hỗn hợp
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x2_net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# logits, means, scales cho hỗn hợp
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Tính log p(x) = log p(x1) + log p(x2|x1)
        
        Đây là điều khiến đây là mô hình mật độ tường minh — ta có thể đánh giá
        xác suất của bất kỳ điểm nào, cho phép huấn luyện hợp lý cực đại.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# log p(x1): log hỗn hợp logistic
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;logits_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, n_components)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;means_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scales_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_scales&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Log-prob logistic cho mỗi thành phần
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;means_1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scales_1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;log_probs_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;functional&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softplus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scales_1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Log-prob hỗn hợp dùng log-sum-exp
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;log_p_x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_probs_1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; \
                   &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits_1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# log p(x2|x1): hỗn hợp điều kiện
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;x2_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;logits_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;means_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scales_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;z_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;means_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scales_2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;log_probs_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;functional&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softplus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scales_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;log_p_x2_given_x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_probs_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; \
                            &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tổng log-prob
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_p_x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_p_x2_given_x1&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Sinh mẫu: trước hết lấy mẫu x1, rồi x2|x1
        
        Minh họa sinh tuần tự — đặc trưng của tự hồi quy.
        Lấy mẫu chính xác từ phân phối đã học.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Lấy mẫu x1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;probs_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;components&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;multinomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;probs_1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;replacement&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scales&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_scales&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Mẫu logistic (xấp xỉ dùng Gaussian)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scales&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lấy mẫu x2|x1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;x2_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lấy mẫu thành phần cho mỗi x1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;logits_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;probs_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;components_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;multinomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;probs_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lấy tham số cho các thành phần đã chọn
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;means_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;components_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scales_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;components_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;means_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scales_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện mô hình tự hồi quy
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Huấn luyện Mô hình Tự hồi quy (Mật độ Tường minh)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;AutoregressiveModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ar_optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Xáo dữ liệu
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randperm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Huấn luyện mini-batch
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính âm log-hợp lý
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;log_probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Negative log-likelihood
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;ar_optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;ar_optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: NLL = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh mẫu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;samples_ar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đã sinh &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_ar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; mẫu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean mẫu: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_ar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean dữ liệu:   &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Minh họa trực tiếp cách xây dựng mô hình tự hồi quy dự đoán ký tự tiếp theo từ đầu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Mở rộng cùng nguyên lý phân rã xác suất tự hồi quy vào kiến trúc Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=L8HKweZIOmg&quot;&gt;Sequence-to-Sequence (seq2seq) Encoder-Decoder Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích mô hình sequence-to-sequence như phiên bản có điều kiện của tích xác suất tự hồi quy.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-01-01 Lý thuyết Mô hình Sinh</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_01_01_Generative_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_01_01_Generative_Theory</id>
   <content type="html">&lt;p&gt;Đằng sau mỗi bức ảnh khuôn mặt do AI tạo ra không hề có một chiếc máy ảnh nào — chỉ có một hàm mật độ xác suất trong không gian hàng trăm nghìn chiều đang thì thầm rằng “tổ hợp điểm ảnh này rất hợp lý”. Nhưng làm thế nào để ta viết ra, tính toán và tối ưu được một hàm mật độ phức tạp như vậy mà không rơi vào bế tắc tích phân? Bài lý thuyết này mở khóa tấm bản đồ toán học phân tách mọi mô hình sinh thành hai trường phái lớn: mật độ tường minh và mật độ ẩn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-nền-tảng-toán-học-phân-loại-các-họ-mô-hình-sinh&quot;&gt;Kiến thức cần nhớ: Nền tảng toán học phân loại các họ mô hình sinh&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Quy tắc chuỗi và mô hình tự hồi quy:&lt;/strong&gt; Dùng đồng nhất thức \(p(\mathbf{x}) = \prod_{i=1}^d p(x_i \mid \mathbf{x}_{&amp;lt;i})\) để biến mật độ đồng thời phức tạp thành chuỗi bài toán phân loại/hồi quy có điều kiện tính được chính xác.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Định lý đổi biến và chuẩn hóa luồng (Normalizing Flows):&lt;/strong&gt; Khai thác phép biến đổi khả nghịch \(\mathbf{x} = f(\mathbf{z})\) cùng định thức ma trận Jacobian $$&lt;/td&gt;
          &lt;td&gt;\det J_{f^{-1}}(\mathbf{x})&lt;/td&gt;
          &lt;td&gt;$$ để vừa lấy mẫu nhanh vừa tính mật độ chính xác.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Suy diễn biến phân và cận dưới ELBO:&lt;/strong&gt; Khi tích phân biên $$\int p(\mathbf{x}&lt;/td&gt;
          &lt;td&gt;\mathbf{z})p(\mathbf{z})d\mathbf{z}\(bất khả tính, đưa vào phân phối xấp xỉ\)q_\phi(\mathbf{z}&lt;/td&gt;
          &lt;td&gt;\mathbf{x})$$ để tối ưu cận dưới khả tính.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng cách giữa hai phân phối (KL, FID, IS):&lt;/strong&gt; Liên kết lý thuyết thông tin (phân kỳ KL, entropy) với hình học xác suất (khoảng cách Fréchet giữa hai phân phối chuẩn) để đánh giá chất lượng sinh.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-định-thức-jacobian-trong-mô-hình-luồng-và-chỉ-số-fid-trên-đặc-trưng-1d&quot;&gt;Giải thích: Tính tay định thức Jacobian trong mô hình luồng và chỉ số FID trên đặc trưng 1D&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Công thức đổi biến (Normalizing Flow 1D):&lt;/strong&gt; Giả sử biến ẩn \(z \sim \mathcal{N}(0, 1)\) có mật độ \(p_z(z) = \frac{1}{\sqrt{2\pi}} e^{-z^2/2}\), và phép biến đổi khả nghịch là \(x = f(z) = 2z + 3\) (nên \(z = f^{-1}(x) = \frac{x - 3}{2}\)).&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Tính đạo hàm ngược: $$\left&lt;/td&gt;
          &lt;td&gt;\frac{df^{-1}(x)}{dx}\right&lt;/td&gt;
          &lt;td&gt;= \frac{1}{2} = 0{,}5$$.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;Tại điểm \(x = 5\), ta có \(z = (5-3)/2 = 1\) và \(p_z(1) = \frac{1}{\sqrt{2\pi}}e^{-0{,}5} \approx 0{,}2420\).&lt;/li&gt;
  &lt;li&gt;Mật độ tại \(x = 5\) là \(p_x(5) = 0{,}2420 \times 0{,}5 = 0{,}1210\). Hệ số Jacobian \(0{,}5\) chính là yếu tố bảo toàn tổng xác suất bằng \(1\) khi phép biến đổi kéo giãn trục số gấp đôi.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Tính tay FID trên đặc trưng 1D:&lt;/strong&gt; Giả sử đặc trưng Inception 1 chiều của ảnh thật có trung bình \(\mu_r = 2{,}0\), phương sai \(\sigma_r^2 = 4{,}0\); ảnh sinh có \(\mu_g = 2{,}5\), phương sai \(\sigma_g^2 = 1{,}0\).
\(\text{FID} = (\mu_r - \mu_g)^2 + \left(\sigma_r^2 + \sigma_g^2 - 2\sqrt{\sigma_r^2 \sigma_g^2}\right) = (2{,}0 - 2{,}5)^2 + (4{,}0 + 1{,}0 - 2\sqrt{4{,}0 \cdot 1{,}0}) = 0{,}25 + (5 - 4) = 1{,}25.\)
Quan sát: Dù trung bình chỉ lệch \(0{,}5\) (đóng góp \(0{,}25\)), việc phương sai bị thu hẹp từ \(4{,}0\) xuống \(1{,}0\) (dấu hiệu thiếu đa dạng / sụp đổ mode) làm FID vọt thêm \(1{,}00\) đơn vị.&lt;/p&gt;

&lt;h1 id=&quot;mô-hình-sinh-học-cách-tạo-ra-dữ-liệu&quot;&gt;Mô hình Sinh: Học cách tạo ra dữ liệu&lt;/h1&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Mô hình sinh (&lt;em&gt;generative models&lt;/em&gt;) thể hiện một hướng tiếp cận khác căn bản so với mô hình phân biệt (&lt;em&gt;discriminative models&lt;/em&gt;). Trong khi mô hình phân biệt học ánh xạ từ đầu vào sang đầu ra — chẳng hạn phân loại ảnh, dịch câu giữa hai ngôn ngữ hay dự báo chuỗi thời gian — mô hình sinh hướng tới việc nắm bắt và tái tạo cấu trúc xác suất của chính dữ liệu. Bài toán đặt ra tham vọng hơn: từ tập mẫu quan sát được, liệu mô hình có thể sinh ra các mẫu mới hợp lệ tuân theo cùng phân phối dữ liệu hay không? Khả năng này cho phép tổng hợp ảnh khuôn mặt chưa từng tồn tại, sáng tác nhạc theo phong cách cho trước, thiết kế cấu trúc phân tử đáp ứng tính chất mong muốn hoặc bổ sung dữ liệu tổng hợp cho các tập dữ liệu nhỏ.&lt;/p&gt;

&lt;p&gt;Sự khác biệt cốt lõi nằm ở mức độ hiểu cấu trúc dữ liệu. Một bộ phân loại giống chó chỉ cần học các đặc trưng đủ để tách biệt các lớp — như hình dáng tai, họa tiết lông hay kích thước — mà không cần biết các bộ phận đó ghép lại thành một cơ thể hợp lý như thế nào. Ngược lại, một mô hình sinh phải học cấu trúc đầy đủ hơn: cách các điểm ảnh kết hợp thành kết cấu bề mặt, kết cấu tạo thành bộ phận, các bộ phận ghép thành đối tượng hoàn chỉnh, và tổ hợp nào là hợp lý so với phi thực tế. Chính vì vậy, mô hình sinh thường học được các biểu diễn dữ liệu giàu thông tin hơn, hữu ích ngay cả khi mục tiêu cuối cùng không phải là sinh mẫu.&lt;/p&gt;

&lt;p&gt;Cơ sở toán học của mô hình sinh dựa trên lý thuyết xác suất và thống kê. Ta giả định dữ liệu \(\mathbf{x}\) được lấy mẫu từ một phân phối thật chưa biết \(p_{\text{data}}(\mathbf{x})\). Mục tiêu là học một phân phối tham số \(p_{\text{model}}(\mathbf{x}; \theta)\) (với \(\theta\) là trọng số mạng nơ-ron) sao cho gần với \(p_{\text{data}}\). Nếu phép xấp xỉ đủ tốt, việc lấy mẫu từ \(p_{\text{model}}\) sẽ tạo ra các mẫu khó phân biệt với dữ liệu thật. Khung tiếp cận này kết nối trực tiếp mô hình sinh với ước lượng hợp lý cực đại (&lt;em&gt;maximum likelihood estimation&lt;/em&gt;), suy diễn biến phân (&lt;em&gt;variational inference&lt;/em&gt;) và lý thuyết thông tin, đồng thời tận dụng khả năng biểu diễn hàm phi tuyến linh hoạt của mạng nơ-ron.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Mỗi họ mô hình sinh mang lại sự đánh đổi riêng giữa chất lượng mẫu, độ ổn định khi huấn luyện, khả năng tính xác suất và chi phí tính toán. Mô hình tự hồi quy (&lt;em&gt;autoregressive models&lt;/em&gt;) như PixelCNN biểu diễn tường minh $$p(\mathbf{x}) = \prod_i p(x_i&lt;/td&gt;
      &lt;td&gt;x_{&amp;lt;i})\(, phân rã quá trình sinh thành chuỗi phân phối điều kiện; chúng cho phép tính chính xác hàm hợp lý và huấn luyện ổn định, nhưng tốc độ sinh chậm do phải tạo từng phần tử tuần tự. Variational Autoencoder (VAE) đưa vào biến ẩn\)\mathbf{z}\(với\)p(\mathbf{x}) = \int p(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})p(\mathbf{z})d\mathbf{z}\(và tối ưu cận dưới khả tính của log-hợp lý; VAE lấy mẫu nhanh và có cơ sở xác suất chặt chẽ, nhưng ảnh sinh ra thường hơi mờ. Mạng sinh đối kháng (GAN) không mô hình hóa mật độ tường minh mà dùng cơ chế đối kháng để học trực tiếp hàm lấy mẫu từ\)p_{\text{data}}$$; GAN thường tạo ảnh sắc nét hơn nhưng dễ gặp bất ổn khi huấn luyện và hiện tượng sụp đổ mode (&lt;em&gt;mode collapse&lt;/em&gt;).&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Trong thực tế, mô hình sinh được ứng dụng rộng rãi ở nhiều lĩnh vực. Trong thị giác máy tính, chúng hỗ trợ tăng cường dữ liệu, siêu phân giải (&lt;em&gt;super-resolution&lt;/em&gt; — nâng độ phân giải ảnh), khôi phục vùng ảnh khuyết (&lt;em&gt;inpainting&lt;/em&gt;) và chuyển đổi phong cách (&lt;em&gt;style transfer&lt;/em&gt;). Trong xử lý ngôn ngữ tự nhiên, chúng là nền tảng cho sinh văn bản, dịch máy và tạo dữ liệu bổ sung cho ngôn ngữ ít tài nguyên. Trong hóa dược, mô hình sinh hỗ trợ đề xuất cấu trúc phân tử mới; trong phát hiện bất thường, chúng xác định điểm ngoại lai bằng cách đo mức độ phù hợp với phân phối đã học.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, mô hình hóa sinh về bản chất khó hơn học phân biệt. Không gian đầu ra có kích thước lớn hơn không gian nhãn theo cấp số mũ (chẳng hạn \(2^{784}\) cấu hình ảnh nhị phân trên MNIST so với chỉ 10 nhãn lớp). Phân phối học được phải nắm bắt các phụ thuộc phức tạp giữa các chiều dữ liệu, vì các điểm ảnh lân cận luôn có tương quan chặt chẽ và các bộ phận đối tượng phải hợp lý về mặt cấu trúc. Việc đánh giá chất lượng mô hình cũng không đơn giản như tính độ chính xác phân loại. Những thách thức này khiến mô hình hóa sinh tiếp tục là một lĩnh vực nghiên cứu phát triển nhanh.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Cơ sở toán học của mô hình sinh dựa trên lý thuyết xác suất, ước lượng hợp lý và lý thuyết thông tin. Phần này trình bày các mục tiêu tối ưu chính và lý do vì sao các giả định khác nhau dẫn đến các họ thuật toán khác nhau.&lt;/p&gt;

&lt;h3 id=&quot;mật-độ-xác-suất-và-phân-phối-dữ-liệu&quot;&gt;Mật độ xác suất và phân phối dữ liệu&lt;/h3&gt;

&lt;p&gt;Giả sử tập huấn luyện \(\{\mathbf{x}^{(1)}, \ldots, \mathbf{x}^{(m)}\}\) gồm các mẫu độc lập rút ra từ phân phối chưa biết \(p_{\text{data}}(\mathbf{x})\). Với dữ liệu ảnh, \(\mathbf{x}\) có thể có \(28 \times 28 = 784\) chiều (MNIST) hoặc \(224 \times 224 \times 3 = 150{,}528\) chiều (ImageNet). Phân phối \(p_{\text{data}}\) gán mật độ xác suất cao cho các ảnh hợp lệ (chữ số viết tay, ảnh chụp tự nhiên) và mật độ gần bằng 0 cho các cấu hình phi thực tế (nhiễu ngẫu nhiên, cấu trúc sai lệch).&lt;/p&gt;

&lt;p&gt;Mục tiêu là tìm tham số \(\theta\) của mô hình \(p_{\text{model}}(\mathbf{x}; \theta)\) sao cho gán xác suất cao cho dữ liệu huấn luyện và tổng quát hóa tốt sang dữ liệu mới từ cùng phân phối. Cách tiếp cận chuẩn là ước lượng hợp lý cực đại (MLE):&lt;/p&gt;

\[\theta^* = \arg\max_\theta \prod_{i=1}^{m} p_{\text{model}}(\mathbf{x}^{(i)}; \theta)\]

&lt;p&gt;Lấy logarit để thuận tiện cho việc tính toán và tránh tràn số dưới (&lt;em&gt;underflow&lt;/em&gt;):&lt;/p&gt;

\[\theta^* = \arg\max_\theta \sum_{i=1}^{m} \log p_{\text{model}}(\mathbf{x}^{(i)}; \theta) = \arg\max_\theta \frac{1}{m}\sum_{i=1}^{m} \log p_{\text{model}}(\mathbf{x}^{(i)}; \theta)\]

&lt;p&gt;Giá trị log-hợp lý trung bình \(\frac{1}{m}\sum_{i=1}^{m} \log p_{\text{model}}(\mathbf{x}^{(i)}; \theta)\) là ước lượng thực nghiệm của kỳ vọng log-hợp lý theo phân phối dữ liệu:&lt;/p&gt;

\[\mathbb{E}_{\mathbf{x} \sim p_{\text{data}}}[\log p_{\text{model}}(\mathbf{x}; \theta)]\]

&lt;p&gt;Cực đại hóa kỳ vọng này tương đương với cực tiểu hóa phân kỳ Kullback–Leibler (KL) từ phân phối dữ liệu tới phân phối mô hình:&lt;/p&gt;

\[KL(p_{\text{data}} \| p_{\text{model}}) = \mathbb{E}_{\mathbf{x} \sim p_{\text{data}}}[\log p_{\text{data}}(\mathbf{x}) - \log p_{\text{model}}(\mathbf{x}; \theta)]\]

&lt;p&gt;Do \(p_{\text{data}}\) cố định không phụ thuộc \(\theta\), tối thiểu hóa phân kỳ KL tương đương với tối đa hóa kỳ vọng log-hợp lý. Kết quả này kết nối trực tiếp MLE với lý thuyết thông tin và cung cấp một thước đo rõ ràng về độ sai lệch giữa mô hình và phân phối thật.&lt;/p&gt;

&lt;h3 id=&quot;mô-hình-mật-độ-tường-minh-và-mô-hình-mật-độ-ẩn&quot;&gt;Mô hình mật độ tường minh và mô hình mật độ ẩn&lt;/h3&gt;

&lt;p&gt;Với dữ liệu nhiều chiều, khó khăn chính là thiết kế hàm mật độ \(p_{\text{model}}(\mathbf{x}; \theta)\) sao cho vừa đủ linh hoạt để mô tả phân phối phức tạp, vừa có thể tính toán và tối ưu được (&lt;em&gt;tractable&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mô hình mật độ tường minh (&lt;em&gt;explicit density models&lt;/em&gt;)&lt;/strong&gt; tham số hóa trực tiếp hàm mật độ \(p_{\text{model}}(\mathbf{x}; \theta)\):&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Mô hình tự hồi quy&lt;/em&gt; dùng quy tắc chuỗi xác suất để phân rã mật độ đồng thời thành tích các phân phối điều kiện:&lt;/p&gt;

\[p(\mathbf{x}) = p(x_1) p(x_2|x_1) p(x_3|x_1, x_2) \cdots p(x_d|x_1, \ldots, x_{d-1}) = \prod_{i=1}^{d} p(x_i|\mathbf{x}_{&amp;lt;i})\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Mỗi phân phối điều kiện $$p(x_i&lt;/td&gt;
      &lt;td&gt;\mathbf{x}_{&amp;lt;i})\(được mô hình hóa bằng mạng nơ-ron. Cách này cho phép tính chính xác\)p(\mathbf{x})\(cho mọi điểm\)\mathbf{x}$$, nhưng tốc độ sinh mẫu chậm do phải sinh tuần tự từng chiều và phụ thuộc vào thứ tự sắp xếp các biến.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;em&gt;Mô hình dựa trên luồng (flow-based models)&lt;/em&gt; sử dụng phép biến đổi khả nghịch \(\mathbf{x} = f(\mathbf{z})\) với \(\mathbf{z} \sim p_{\mathbf{z}}\) tuân theo phân phối đơn giản (như chuẩn hóa Gaussian). Theo công thức đổi biến xác suất:&lt;/p&gt;

\[p_{\mathbf{x}}(\mathbf{x}) = p_{\mathbf{z}}(f^{-1}(\mathbf{x})) \left|\det \frac{\partial f^{-1}}{\partial \mathbf{x}}\right|\]

&lt;p&gt;Cách tiếp cận này vừa đánh giá được mật độ chính xác vừa cho phép lấy mẫu nhanh, nhưng đòi hỏi kiến trúc mạng được thiết kế đặc biệt để đảm bảo tính khả nghịch và tính được định thức ma trận Jacobian hiệu quả.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mô hình mật độ ẩn (&lt;em&gt;implicit density models&lt;/em&gt;)&lt;/strong&gt; định nghĩa trực tiếp quy trình lấy mẫu ngẫu nhiên mà không biểu diễn tường minh \(p_{\text{model}}(\mathbf{x})\):&lt;/p&gt;

&lt;p&gt;&lt;em&gt;GAN&lt;/em&gt; học một bộ sinh (&lt;em&gt;generator&lt;/em&gt;) \(G: \mathcal{Z} \to \mathcal{X}\) sao cho khi \(\mathbf{z} \sim p_{\mathbf{z}}\) thì \(G(\mathbf{z})\) có phân phối gần với \(p_{\text{data}}\). Ta không tính tường minh \(p_{\text{model}}\) mà huấn luyện thông qua mục tiêu đối kháng để đổi lấy tốc độ lấy mẫu nhanh.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;em&gt;VAE&lt;/em&gt; nằm ở nhóm trung gian (mật độ tường minh xấp xỉ): mô hình biểu diễn tường minh $$p(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})\(, nhưng việc lấy tích phân biên theo biến ẩn\)\mathbf{z}$$ được xấp xỉ bằng suy diễn biến phân, tối ưu cận dưới ELBO thay vì log-hợp lý chính xác.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Việc chọn họ mô hình nào phụ thuộc vào yêu cầu bài toán: cần tính xác suất chính xác (cho phát hiện bất thường, nén dữ liệu), cần lấy mẫu nhanh theo thời gian thực, hay ưu tiên độ sắc nét của mẫu hơn tính ổn định khi huấn luyện.&lt;/p&gt;

&lt;h3 id=&quot;mô-hình-biến-ẩn&quot;&gt;Mô hình biến ẩn&lt;/h3&gt;

&lt;p&gt;Nhiều mô hình sinh đưa thêm biến ẩn \(\mathbf{z}\) để biểu diễn các nhân tố nền tảng chi phối sự biến thiên của dữ liệu. Quy trình sinh gồm hai bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Lấy mẫu mã ẩn từ phân phối tiên nghiệm: \(\mathbf{z} \sim p(\mathbf{z})\) (thường chọn \(\mathcal{N}(0, I)\)).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Sinh dữ liệu có điều kiện: $$\mathbf{x} \sim p(\mathbf{x}&lt;/td&gt;
          &lt;td&gt;\mathbf{z}; \theta)$$.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Phân phối biên của dữ liệu khi đó là:&lt;/p&gt;

\[p(\mathbf{x}; \theta) = \int p(\mathbf{x}|\mathbf{z}; \theta) p(\mathbf{z}) d\mathbf{z}\]

&lt;p&gt;Khung mô hình này rất hữu ích vì các chiều của biến ẩn có thể tương ứng với những thuộc tính diễn giải được (chẳng hạn góc mặt, ánh sáng, biểu cảm đối với ảnh khuôn mặt), đồng thời biểu diễn đa tạp dữ liệu nhiều chiều trong không gian thấp chiều hơn. Khó khăn nằm ở chỗ tích phân biên theo biến liên tục \(\mathbf{z}\) không thể tính trực tiếp. Các họ mô hình giải quyết vấn đề này theo cách khác nhau:&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;VAE áp dụng suy diễn biến phân, giới thiệu bộ mã hóa (&lt;em&gt;encoder&lt;/em&gt;) $$q(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x}; \phi)\(để xấp xỉ phân phối hậu nghiệm\)p(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})$$ và tối đa hóa cận dưới bằng chứng (&lt;em&gt;Evidence Lower Bound&lt;/em&gt; — ELBO):&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[\log p(\mathbf{x}; \theta) \geq \mathbb{E}_{\mathbf{z} \sim q(\mathbf{z}|\mathbf{x}; \phi)}[\log p(\mathbf{x}|\mathbf{z}; \theta)] - KL(q(\mathbf{z}|\mathbf{x}; \phi) \| p(\mathbf{z}))\]

&lt;p&gt;Cận dưới này có thể ước lượng bằng lấy mẫu và tối ưu qua lan truyền ngược nhờ kỹ thuật tái tham số hóa (&lt;em&gt;reparameterization trick&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;GAN bỏ qua hoàn toàn tích phân hợp lý và huấn luyện trực tiếp bộ sinh \(G(\mathbf{z}; \theta)\) thông qua trò chơi đối kháng với bộ phân biệt để học cách lấy mẫu ẩn từ phân phối dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;các-chỉ-số-đánh-giá&quot;&gt;Các chỉ số đánh giá&lt;/h3&gt;

&lt;p&gt;Đánh giá mô hình sinh khó hơn đánh giá phân loại vì mục tiêu là đo mức độ trùng khớp giữa hai phân phối nhiều chiều:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Log-hợp lý (&lt;em&gt;log-likelihood&lt;/em&gt;)&lt;/strong&gt; (khi tính được): đo xác suất mà mô hình gán cho tập kiểm tra; giá trị càng cao càng tốt. Tuy nhiên, log-hợp lý cao không luôn đồng nghĩa với chất lượng thị giác tốt, và một mô hình ghi nhớ dữ liệu huấn luyện có thể đạt log-hợp lý rất cao trên tập huấn luyện nhưng vô dụng khi sinh mẫu mới.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inception Score (IS)&lt;/strong&gt;: đưa các mẫu sinh qua mạng phân loại Inception tiền huấn luyện rồi tính:&lt;/p&gt;

\[IS = \exp(\mathbb{E}_{\mathbf{x} \sim p_G}[KL(p(y|\mathbf{x}) \| p(y))])\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;IS phản ánh đồng thời độ rõ nét (phân phối có điều kiện $$p(y&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(tập trung vào một lớp) và độ đa dạng (phân phối biên\)p(y)$$ trải đều các lớp). Giá trị cao hơn là tốt hơn, nhưng IS bị phụ thuộc vào các lớp của ImageNet và không phát hiện được hiện tượng ghi nhớ dữ liệu.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Fréchet Inception Distance (FID)&lt;/strong&gt;: so sánh phân phối đặc trưng trích từ mạng Inception của tập mẫu thật và tập mẫu sinh dưới giả định phân phối chuẩn nhiều chiều:&lt;/p&gt;

\[FID = \|\mu_r - \mu_g\|^2 + \text{Tr}(\Sigma_r + \Sigma_g - 2(\Sigma_r \Sigma_g)^{1/2})\]

&lt;p&gt;FID càng thấp chứng tỏ phân phối mẫu sinh càng gần phân phối dữ liệu thật. Chỉ số này ổn định hơn IS nhưng vẫn bị giới hạn bởi giả định đặc trưng tuân theo phân phối chuẩn.&lt;/p&gt;

&lt;p&gt;Vì không có thước đo tự động nào hoàn hảo, đánh giá trực quan bằng mắt người vẫn rất cần thiết. Ngoài ra, với các ứng dụng chuyên biệt, những chỉ số theo miền (như độ bảo toàn danh tính khuôn mặt hay tính hợp lệ hóa học của phân tử) thường mang lại thông tin thiết thực hơn chỉ số tổng quát.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;p&gt;Để hình dung cách mô hình sinh hoạt động, hãy xét bài toán sinh ảnh chữ số viết tay. Nếu bạn chưa từng nhìn thấy chữ số “3”, bạn khó có thể vẽ ra một chữ số “3” hợp lệ. Nhưng sau khi quan sát hàng nghìn ví dụ về các chữ số, bạn nắm được quy luật chung: chữ số “3” có hai nét cong nối nhau theo chiều dọc với nét bút liên tục. Từ đó bạn có thể viết ra nhiều chữ số “3” mới — không sao chép nguyên mẫu nào nhưng vẫn đúng quy luật. Mô hình sinh thực hiện chính quá trình học cấu trúc đó một cách tự động từ dữ liệu.&lt;/p&gt;

&lt;p&gt;Cùng trên bài toán này, ba họ mô hình hành xử rất khác nhau:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mô hình tự hồi quy:&lt;/strong&gt; Sinh ảnh lần lượt từng điểm ảnh theo thứ tự trái sang phải, trên xuống dưới. Mỗi điểm ảnh mới được dự đoán dựa trên toàn bộ các điểm ảnh đã sinh trước đó, giúp đảm bảo tính nhất quán cục bộ nhưng mất nhiều bước tuần tự (784 bước cho một ảnh MNIST).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;VAE:&lt;/strong&gt; Học một không gian ẩn trong đó các vùng khác nhau tương ứng với các chữ số và phong cách viết khác nhau. Để sinh chữ số “3”, chỉ cần lấy mẫu một điểm từ vùng tương ứng và giải mã trong một lượt truyền xuôi. Không gian ẩn mượt cũng cho phép nội suy liên tục giữa các chữ số, nhưng hàm mất mát tái tạo theo điểm ảnh (như MSE) thường khiến ảnh đầu ra hơi mờ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GAN:&lt;/strong&gt; Huấn luyện bộ sinh để đánh lừa bộ phân biệt phân tách ảnh thật và ảnh giả. Vì không bị ép khớp từng điểm ảnh theo nghĩa trung bình bình phương, bộ sinh có xu hướng tạo ra ảnh sắc nét hơn, nhưng đổi lại quá trình huấn luyện kém ổn định hơn và dễ xảy ra sụp đổ mode (chẳng hạn chỉ sinh lặp đi lặp lại một vài kiểu viết chữ số “3”).&lt;/p&gt;

&lt;p&gt;Xét thêm một ví dụ đơn giản trong không gian 2D: phân phối dữ liệu thật \(p_{\text{data}}\) là hỗn hợp hai phân phối chuẩn tạo thành hai cụm tách biệt:&lt;/p&gt;

\[p_{\text{data}}(\mathbf{x}) = 0.5 \mathcal{N}(\mathbf{x}; [2, 2], I) + 0.5 \mathcal{N}(\mathbf{x}; [-2, -2], I)\]

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Mô hình tự hồi quy&lt;/strong&gt; phân rã thành $$p(x_2&lt;/td&gt;
          &lt;td&gt;x_1)p(x_1)\(. Tại cụm thứ nhất có tâm [2, 2], thành phần tương ứng xấp xỉ\)p(x_1) \approx \mathcal{N}(2, 1)\(và phân phối điều kiện\)p(x_2&lt;/td&gt;
          &lt;td&gt;x_1) \approx \mathcal{N}(2, 1)\((tương tự quanh [-2, -2] cho cụm thứ hai). Khi sinh mẫu, mô hình lấy mẫu\)x_1 \sim p(x_1)\(rồi lấy mẫu\)x_2 \sim p(x_2&lt;/td&gt;
          &lt;td&gt;x_1)$$.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;VAE&lt;/strong&gt; sử dụng biến ẩn \(z \in \mathbb{R}\), học cách ánh xạ vùng \(z &amp;lt; 0\) sang cụm [-2, -2] và vùng \(z &amp;gt; 0\) sang cụm [2, 2]. Khi sinh mẫu, chỉ cần lấy \(z \sim \mathcal{N}(0, 1)\) và đưa qua bộ giải mã để thu được \(\mathbf{x}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GAN&lt;/strong&gt; huấn luyện bộ sinh ánh xạ nhiễu 1D \(z\) sang điểm 2D sao cho bộ phân biệt không thể tách biệt với mẫu thật, ví dụ ánh xạ đoạn \(z \in [-3, 0]\) sang cụm thứ nhất và \(z \in [0, 3]\) sang cụm thứ hai.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nếu được huấn luyện phù hợp, cả ba cách tiếp cận đều có thể bao phủ đủ hai cụm dữ liệu, nhưng khác nhau rõ rệt về cách biểu diễn phân phối, độ ổn định khi tối ưu và quy trình lấy mẫu.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Giải thích mục tiêu khớp \(p_{\text{model}}\) với \(p_{\text{data}}\) xuyên suốt phần lý thuyết của bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, tiếng Anh. Trình bày ba hướng tiếp cận chính: tự hồi quy, biến ẩn và huấn luyện đối kháng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pYxNSUDSFH4&quot;&gt;In Statistics, Probability is not Likelihood.&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Phân biệt rõ xác suất và hàm hợp lý, giúp hiểu chính xác mục tiêu MLE trong bài.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11 Giới thiệu về Mô hình Sinh</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter11/11_00_Introduction</id>
   <content type="html">&lt;p&gt;Hãy hình dung một họa sĩ tập sự chỉ từng xem qua vài nghìn bức tranh phong cảnh nhưng chưa bao giờ được ai chỉ tay dạy cách vẽ từng nhát cọ. Nếu ta chỉ yêu cầu anh ta &lt;em&gt;phân biệt&lt;/em&gt; tranh sơn dầu với tranh thủy mặc, nhiệm vụ đó khá nhẹ nhàng; nhưng nếu ta đưa toan trắng và đề nghị anh ta &lt;em&gt;sáng tác một bức tranh mới hoàn toàn&lt;/em&gt;, anh ta buộc phải hiểu sâu quy luật ánh sáng, bố cục và xác suất xuất hiện của từng mảng màu. Đó chính là bước nhảy vọt tư duy của &lt;strong&gt;Mô hình Sinh (Generative Models)&lt;/strong&gt; — từ việc trả lời “đây là gì?” sang khả năng “tạo ra một thế giới dữ liệu mới”.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-học-máy-sinh-dữ-liệu&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của học máy sinh dữ liệu&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết xác suất và phân phối nhiều chiều:&lt;/strong&gt; Nghiên cứu cách biểu diễn dữ liệu (ảnh, âm thanh, văn bản) như những điểm được rút ra từ một phân phối mật độ chưa biết \(p_{\text{data}}(\mathbf{x})\), làm nền móng để đo lường xem một mẫu mới có “hợp lý” hay không.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ước lượng hợp lý cực đại (MLE) và phân kỳ KL:&lt;/strong&gt; Cung cấp hàm mục tiêu thống kê để ép phân phối mô hình \(p_{\theta}(\mathbf{x})\) tiến sát \(p_{\text{data}}(\mathbf{x})\) bằng cách cực đại hóa xác suất quan sát được tập dữ liệu thật.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc biến ẩn và chuỗi điều kiện:&lt;/strong&gt; Phân loại ba chiến lược thiết kế mô hình sinh cổ điển — phân rã chuỗi tự hồi quy, nén qua biến ẩn (VAE), và học lấy mẫu gián tiếp qua đối kháng (GAN).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thước đo đánh giá phân phối sinh:&lt;/strong&gt; Nghiên cứu lý do độ chính xác phân loại không còn dùng được, từ đó xây dựng các chỉ số so sánh hai phân phối nhiều chiều như log-likelihood, IS và FID.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giải-thích-vì-sao-không-gian-dữ-liệu-sinh-bùng-nổ-và-mle-kéo-phân-phối-mô-hình-ra-sao&quot;&gt;Giải thích: Vì sao không gian dữ liệu sinh bùng nổ và MLE kéo phân phối mô hình ra sao?&lt;/h3&gt;

&lt;p&gt;Xét một bài toán sinh ảnh nhị phân siêu nhỏ chỉ gồm \(2 \times 2 = 4\) điểm ảnh (mỗi điểm nhận \(0\) hoặc \(1\)). Tổng số cấu hình khả dĩ là \(2^4 = 16\). Giả sử phân phối dữ liệu thật \(p_{\text{data}}\) chỉ tập trung vào 2 mẫu hợp lệ: ảnh A (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1,0,0,1]&lt;/code&gt;, xác suất \(0{,}6\)) và ảnh B (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0,1,1,0]&lt;/code&gt;, xác suất \(0{,}4\)), 14 mẫu còn lại có xác suất \(0\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình ban đầu (phân phối đều):&lt;/strong&gt; Gán \(p_\theta(\mathbf{x}) = 1/16 = 0{,}0625\) cho mọi mẫu. Kỳ vọng log-hợp lý (dùng logarit tự nhiên) là:
\(\mathbb{E}_{p_{\text{data}}}[\ln p_\theta(\mathbf{x})] = 0{,}6 \ln(0{,}0625) + 0{,}4 \ln(0{,}0625) = \ln(0{,}0625) \approx -2{,}773.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình sau khi tối ưu MLE:&lt;/strong&gt; Dồn khối xác suất vào hai mẫu thật, giả sử đạt \(p_\theta(A) = 0{,}55\), \(p_\theta(B) = 0{,}35\) (còn lại \(0{,}10\) rải cho 14 mẫu nhiễu). Khi đó:
\(\mathbb{E}_{p_{\text{data}}}[\ln p_\theta(\mathbf{x})] = 0{,}6 \ln(0{,}55) + 0{,}4 \ln(0{,}35) \approx 0{,}6(-0{,}598) + 0{,}4(-1{,}050) = -0{,}779.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giới hạn tối ưu (Entropy âm):&lt;/strong&gt; Nếu \(p_\theta = p_{\text{data}}\), log-hợp lý đạt trần lý thuyết \(0{,}6\ln(0{,}6) + 0{,}4\ln(0{,}4) \approx -0{,}673\), khi đó phân kỳ \(D_{\text{KL}}(p_{\text{data}} \| p_\theta) = 0\). Nhìn vào con số \(-2{,}773 \to -0{,}779 \to -0{,}673\), ta thấy bản chất của học sinh dữ liệu là &lt;em&gt;kéo khối xác suất ra khỏi đại dương cấu hình vô nghĩa&lt;/em&gt; để dồn chính xác lên đa tạp dữ liệu thật.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mô hình sinh (&lt;em&gt;generative models&lt;/em&gt;) học cách tạo ra các mẫu dữ liệu mới tương đồng với dữ liệu huấn luyện. Chương này trình bày các khái niệm nền tảng của mô hình hóa sinh: phân phối xác suất, ước lượng hợp lý cực đại (&lt;em&gt;maximum likelihood estimation&lt;/em&gt;) và các chỉ số đánh giá. Đây là cơ sở lý thuyết cho autoencoder, VAE và GAN ở các chương tiếp theo.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần nền tảng, bạn có thể xem &lt;strong&gt;11-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về sự chuyển dịch sang mô hình khuếch tán và flow matching (phần chi tiết về VAE và GAN được trình bày riêng ở các chương sau).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, tiếng Anh. Bài giảng tổng quan cấu trúc của chương này với ba hướng chính: tự hồi quy, biến ẩn và huấn luyện đối kháng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, tiếng Anh. Phiên bản cập nhật năm 2024 của MIT, bám sát các họ mô hình đang được sử dụng phổ biến hiện nay.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=XepXtl9YKwc&quot;&gt;Maximum Likelihood, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Ôn lại khái niệm hàm hợp lý (&lt;em&gt;likelihood&lt;/em&gt;), mục tiêu tối ưu cốt lõi của nhiều mô hình sinh.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Suốt gần một thập kỷ, AdamW gần như không có đối thủ trong việc huấn luyện các mô hình nền tảng quy mô lớn — nhưng chi phí bộ nhớ khổng lồ của nó (lưu 2 bản sao trạng thái FP32 cho hàng trăm tỷ tham số) và khát vọng rút ngắn hàng triệu giờ GPU đã thúc đẩy một làn sóng bộ tối ưu mới đầy ấn tượng giai đoạn 2023–2025: từ &lt;strong&gt;Lion&lt;/strong&gt; (do AI tự tiến hóa tìm ra!), &lt;strong&gt;Sophia&lt;/strong&gt; (tận dụng thông tin bậc hai Hessian), cho tới &lt;strong&gt;Muon&lt;/strong&gt; (tối ưu hóa trực giao hóa ma trận theo phổ giá trị kỳ dị).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-đột-phá-bộ-tối-ưu-giai-đoạn-20232025&quot;&gt;Kiến thức cần nhớ: Bốn đột phá Bộ tối ưu giai đoạn 2023–2025&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lion (EvoLved Sign Momentum, Google Brain 2023)&lt;/strong&gt;:
Được tìm ra bằng thuật toán tìm kiếm tiến hóa chương trình! Lion bỏ hoàn toàn moment bậc 2 \(v_t\) (tiết kiệm ngay &lt;strong&gt;50% bộ nhớ trạng thái optimizer&lt;/strong&gt; so với AdamW) và cập nhật tham số chỉ bằng &lt;strong&gt;dấu&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sign(...)&lt;/code&gt; của tổ hợp quán tính — nên mọi tham số có độ lớn bước nhảy đồng đều tuyệt đối.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sophia (Second-Order Clipped Stochastic Optimization, Stanford 2023)&lt;/strong&gt;:
Thay vì dùng bình phương gradient \(g_t^2\) (vốn đo độ lớn gradient chứ không phải độ cong thật), Sophia ước lượng nhẹ đường chéo &lt;strong&gt;ma trận Hessian&lt;/strong&gt; \(h_t\) định kỳ (mỗi \(k=10\) bước) kết hợp cắt ngưỡng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clip&lt;/code&gt; để tăng tốc huấn luyện LLM gấp ~2 lần so với AdamW.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Muon (MomentUm Orthogonalized by Newton–Schulz, 2024–2025)&lt;/strong&gt;:
Nhận ra rằng trọng số trong mạng sâu là &lt;strong&gt;ma trận&lt;/strong&gt; chứ không phải một túi các số vô hướng rời rạc! Muon dùng vài vòng lặp Newton–Schulz siêu nhanh trên GPU để &lt;strong&gt;trực giao hóa&lt;/strong&gt; ma trận cập nhật quán tính (đưa mọi giá trị kỳ dị về 1), lập kỷ lục tốc độ huấn luyện NanoGPT và được ứng dụng trong các LLM thế hệ mới (như Kimi K2).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỹ thuật tiết kiệm bộ nhớ hệ thống (8-bit AdamW, Adafactor, GaLore)&lt;/strong&gt;:
Lượng tử hóa trạng thái optimizer xuống 8-bit (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bitsandbytes&lt;/code&gt;) hoặc chiếu gradient xuống không gian con hạng thấp (GaLore) giúp tinh chỉnh mô hình 7B–70B ngay trên một GPU tiêu dùng.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-bước-cập-nhật-bằng-dấu-của-lion-và-so-sánh-bộ-nhớ-trạng-thái-với-adamw&quot;&gt;Giải thích: Tính tay bước cập nhật bằng dấu của Lion và so sánh bộ nhớ trạng thái với AdamW&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Một bước cập nhật của Lion&lt;/strong&gt; (cho \(w = 1{,}0, \; m_0 = 0{,}5, \; g_1 = -2{,}0, \; \beta_1 = 0{,}9, \; \beta_2 = 0{,}99, \; \eta = 0{,}01, \; \lambda = 0{,}1\)):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Tính hướng cập nhật tạm (nội suy bằng \(\beta_1\)):
\(c_1 = \beta_1 m_0 + (1 - \beta_1) g_1 = 0{,}9(0{,}5) + 0{,}1(-2{,}0) = 0{,}45 - 0{,}20 = \mathbf{+0{,}25}\)&lt;/li&gt;
  &lt;li&gt;Cập nhật tham số chỉ dùng &lt;strong&gt;dấu&lt;/strong&gt; của \(c_1\) kèm weight decay tách rời:
\(w_1 = w_0 - \eta \big(\operatorname{sign}(c_1) + \lambda w_0\big) = 1{,}0 - 0{,}01\big(+1 + 0{,}1(1{,}0)\big) = \mathbf{0{,}989}\)&lt;/li&gt;
  &lt;li&gt;Cập nhật bộ nhớ quán tính duy nhất (bằng \(\beta_2\)):
\(m_1 = \beta_2 m_0 + (1 - \beta_2) g_1 = 0{,}99(0{,}5) + 0{,}01(-2{,}0) = \mathbf{0{,}475}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Phần B — So sánh bộ nhớ trạng thái Optimizer cho mô hình 10 tỷ tham số (FP32 = 4 byte/số)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;AdamW&lt;/strong&gt; (lưu cả \(m\) và \(v\)): \(2 \times 10^{10} \times 4\text{ B} = \mathbf{80\text{ GB VRAM}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lion / Muon&lt;/strong&gt; (chỉ lưu duy nhất 1 bảng quán tính \(m\)): \(1 \times 10^{10} \times 4\text{ B} = \mathbf{40\text{ GB VRAM}}\) (cắt giảm đúng một nửa!).&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;tùy-chọn-adamw-và-các-bộ-tối-ưu-giai-đoạn-20232025-lion-sophia-muon&quot;&gt;Tùy chọn: AdamW và các bộ tối ưu giai đoạn 2023–2025 (Lion, Sophia, Muon)&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế lý thuyết về momentum, RMSprop hay Adam. Các bài chính đã trình bày AdamW; bài này tóm tắt những phương pháp nổi bật ra đời &lt;em&gt;sau&lt;/em&gt; AdamW, đồng thời làm rõ khi nào vẫn nên tiếp tục dùng AdamW.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;AdamW hiện vẫn là lựa chọn mặc định trong Hugging Face và phần lớn các hệ thống huấn luyện LLM:&lt;/p&gt;

\[m_t = \beta_1 m_{t-1} + (1-\beta_1) g_t, \quad
v_t = \beta_2 v_{t-1} + (1-\beta_2) g_t^2,\]

\[\theta \leftarrow \theta - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\varepsilon} - \eta\lambda \theta.\]

&lt;p&gt;Số hạng cuối là weight decay &lt;strong&gt;tách rời&lt;/strong&gt; (không gộp L2 vào bước chuẩn hóa thích nghi). Các phương pháp dưới đây là những lựa chọn thay thế hoặc chuyên biệt hóa gần đây.&lt;/p&gt;

&lt;h2 id=&quot;1-lion-2023&quot;&gt;1. Lion (2023)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2302.06675&quot;&gt;Chen et al., 2023&lt;/a&gt; (phát hiện thông qua tìm kiếm ký hiệu tại Google) chỉ giữ lại &lt;strong&gt;dấu&lt;/strong&gt; của momentum nội suy:&lt;/p&gt;

\[\theta \leftarrow \theta - \eta\,\mathrm{sign}(\beta_1 m + (1-\beta_1)g) - \eta\lambda\theta.\]

&lt;p&gt;Thuật toán tốn ít bộ nhớ hơn Adam vì không phải lưu moment bậc hai. Lion được áp dụng trong một số bài toán thị giác và chưng cất mô hình, nhưng ít phổ biến hơn AdamW khi huấn luyện LLM.&lt;/p&gt;

&lt;h2 id=&quot;2-sophia-2023&quot;&gt;2. Sophia (2023)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.14342&quot;&gt;Liu et al., 2023&lt;/a&gt; ước lượng đường chéo của ma trận Hessian (bằng ước lượng Hutchinson hoặc Gauss–Newton có cắt ngưỡng) để tiền điều kiện bước cập nhật:&lt;/p&gt;

\[\theta \leftarrow \theta - \eta \cdot \mathrm{clip}\!\left(\frac{\hat{m}_t}{\max\{\gamma \hat{h}_t, \varepsilon\}}\right).\]

&lt;p&gt;Nhóm tác giả báo cáo giúp giảm đáng kể số bước huấn luyện trên mô hình kiểu GPT so với AdamW ở cùng mức chất lượng. Dù vậy, trong phần lớn các thư viện huấn luyện mã nguồn mở, Sophia vẫn chủ yếu dừng ở mức nghiên cứu.&lt;/p&gt;

&lt;h2 id=&quot;3-muon-2024&quot;&gt;3. Muon (2024)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://kellerjordan.github.io/posts/muon/&quot;&gt;Jordan et al., 2024&lt;/a&gt; áp dụng SGD kết hợp momentum lên các &lt;strong&gt;ma trận trọng số ẩn&lt;/strong&gt;, sau đó trực giao hóa bước cập nhật bằng vài vòng lặp Newton–Schulz (xấp xỉ thừa số cực &lt;em&gt;polar factor&lt;/em&gt; với chi phí thấp). Các tầng embedding và đầu ra ngôn ngữ thường vẫn giữ AdamW. &lt;a href=&quot;https://arxiv.org/abs/2502.16982&quot;&gt;Moonshot / Kimi, 2025&lt;/a&gt; báo cáo đã huấn luyện LLM quy mô lớn bằng Muon. Đây là bộ tối ưu ở cấp độ ma trận được quan tâm nhiều nhất trong giai đoạn 2024–2025.&lt;/p&gt;

&lt;h2 id=&quot;4-ứng-dụng-và-thư-viện&quot;&gt;4. Ứng dụng và thư viện&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tiếp tục dùng AdamW&lt;/strong&gt; cho các lần chạy đầu tiên với LLM hoặc ConvNeXt (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.optim.AdamW&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lion&lt;/strong&gt;: &lt;a href=&quot;https://github.com/lucidrains/lion-pytorch&quot;&gt;lucidrains/lion-pytorch&lt;/a&gt; và một số công thức huấn luyện trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timm&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sophia&lt;/strong&gt;: mã nguồn tham chiếu đi kèm bài báo.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Muon&lt;/strong&gt;: &lt;a href=&quot;https://github.com/KellerJordan/Muon&quot;&gt;KellerJordan/Muon&lt;/a&gt; và các thử nghiệm tốc độ trong &lt;a href=&quot;https://github.com/KellerJordan/modded-nanogpt&quot;&gt;modded-nanogpt&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Schedule-free AdamW&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2405.15682&quot;&gt;Defazio et al., 2024&lt;/a&gt;) — cho phép bỏ qua lịch trình warmup và cosine tường minh trong một số bài toán.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-tài-liệu-tham-khảo-20222026&quot;&gt;5. Tài liệu tham khảo (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2302.06675&quot;&gt;Lion (Chen et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.14342&quot;&gt;Sophia (Liu et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://kellerjordan.github.io/posts/muon/&quot;&gt;Muon (Jordan et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2502.16982&quot;&gt;Muon is Scalable for LLM Training (Liu et al., 2025)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2405.15682&quot;&gt;The Road Less Scheduled (Defazio et al., 2024)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;6-phần-bổ-sung-so-với-nội-dung-cốt-lõi&quot;&gt;6. Phần bổ sung so với nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên nắm vững Adam và phần so sánh trên hàm Rosenbrock trước. Bài này chỉ bổ sung các phương pháp &lt;strong&gt;sau AdamW&lt;/strong&gt; xuất hiện trong nghiên cứu và thử nghiệm giai đoạn 2023–2026, không thay thế phần cài đặt bộ tối ưu cốt lõi của chương.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, tiếng Anh. Lion, Sophia và Muon là các bước mở rộng tiếp theo từ nhóm momentum/Adam được trình bày trong video này.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Adam là mốc so sánh chuẩn để đánh giá các phương pháp giai đoạn 2023–2024.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 7&lt;/td&gt;
          &lt;td&gt;Training Neural Networks II](https://www.youtube.com/watch?v=_JB0AO7QxSA) — Stanford University School of Engineering, tiếng Anh. Đặt vai trò của bộ tối ưu trong bức tranh huấn luyện tổng thể cùng dữ liệu và lịch trình học.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-98 Luyện phỏng vấn (bộ tối ưu)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Trong phỏng vấn Machine Learning nâng cao, câu hỏi về bộ tối ưu hiếm khi dừng ở mức “Adam viết tắt của từ gì?”. Người phỏng vấn muốn kiểm tra xem bạn có giải thích được bằng trực giác toán học &lt;strong&gt;tại sao Adam cần bias correction&lt;/strong&gt;, &lt;strong&gt;điểm khác biệt chí mạng giữa Adam và AdamW&lt;/strong&gt;, và &lt;strong&gt;vì sao Transformer gần như không thể huấn luyện thiếu Learning Rate Warmup&lt;/strong&gt; hay không.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-chủ-đề-phỏng-vấn-trọng-tâm-về-bộ-tối-ưu&quot;&gt;Kiến thức cần nhớ: Bốn chủ đề phỏng vấn trọng tâm về Bộ tối ưu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giải thích hình học của Momentum trên thung lũng hẹp&lt;/strong&gt;:
Gradient trên trục dốc đổi dấu liên tục (\(+, -, +, -\)) nên khi cộng dồn vào vận tốc \(v_t\) chúng &lt;strong&gt;tự triệt tiêu nhau&lt;/strong&gt;; trong khi gradient dọc đáy thung lũng luôn cùng dấu nên &lt;strong&gt;cộng hưởng tăng tốc&lt;/strong&gt; lên tới hệ số \(\frac{1}{1 - \beta}\) (với \(\beta = 0{,}9\) là gấp 10 lần!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tại sao Adam cần Hiệu chỉnh độ lệch (Bias Correction)&lt;/strong&gt;:
Vì \(m_0 = v_0 = 0\), ước lượng EMA bị kéo lệch mạnh về 0 ở những bước đầu khi \(\beta_1 = 0{,}9, \; \beta_2 = 0{,}999\); chia cho \((1 - \beta^t)\) chuẩn hóa lại tổng trọng số của trung bình trượt về đúng 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adam vs. AdamW (Decoupled Weight Decay)&lt;/strong&gt;:
Chỉ ra đúng lỗi của L2 gộp vào gradient bị chia cho \(\sqrt{\hat{v}_t}\), làm mất tính đồng đều của trọng số phân rã.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vai trò của Learning Rate Warmup&lt;/strong&gt;:
Ở vài trăm–vài nghìn bước đầu, phương sai ước lượng \(\hat{v}_t\) của Adam rất nhiễu và các lớp chuẩn hóa chưa ổn định; giữ \(\eta\) nhỏ rồi tăng dần giúp các thống kê moment ổn định trước khi bước những bước lớn.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-hệ-số-khuếch-đại-vận-tốc-cực-đại-của-momentum-khi-gradient-không-đổi&quot;&gt;Giải thích: Tính tay hệ số khuếch đại vận tốc cực đại của Momentum khi gradient không đổi&lt;/h3&gt;

&lt;p&gt;Giả sử dọc theo đáy thung lũng phẳng, gradient luôn giữ nguyên một hướng với giá trị hằng số \(g_t = g\), và hệ số quán tính là \(\beta = 0{,}9\). Ta tính vận tốc \(v_t = \beta v_{t-1} + g\) (với \(v_0 = 0\)):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
\[v_1 = g\]
  &lt;/li&gt;
  &lt;li&gt;
\[v_2 = 0{,}9 g + g = 1{,}9 g\]
  &lt;/li&gt;
  &lt;li&gt;
\[v_3 = 0{,}9^2 g + 0{,}9 g + g = 2{,}71 g\]
  &lt;/li&gt;
  &lt;li&gt;Tổng quát sau \(t\) bước (tổng cấp số nhân):
\(v_t = g \sum_{k=0}^{t-1} \beta^k = g \cdot \frac{1 - \beta^t}{1 - \beta} \xrightarrow{t \to \infty} \mathbf{\frac{g}{1 - \beta}}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Thay \(\beta = 0{,}9\): vận tốc cuối cùng đạt \(\frac{1}{1 - 0{,}9} = \mathbf{10 \, g}\) — tăng tốc đúng &lt;strong&gt;10 lần&lt;/strong&gt; dọc theo đáy thung lũng mà không cần tăng learning rate (còn nếu \(\beta = 0{,}99\) thì tăng tới &lt;strong&gt;100 lần&lt;/strong&gt;)!&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-luyện-phỏng-vấn--bộ-tối-ưu&quot;&gt;Tùy chọn: Luyện phỏng vấn — Bộ tối ưu&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết về momentum, RMSprop hay Adam. Sau khi học xong các bài chính, bạn có thể dùng bộ câu hỏi dưới đây để tự kiểm tra, sau đó tham khảo thêm cuốn &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) để luyện các câu hỏi có lời giải chi tiết về phương pháp thích nghi, siêu tham số và động lực huấn luyện.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Các chủ đề tương ứng trong sách (đọc trong bản PDF, không tóm tắt lại ở đây):&lt;/strong&gt; thuật toán tối ưu (bao gồm các phép cập nhật họ Adam), lựa chọn siêu tham số và phần huấn luyện trong nhóm chủ đề học sâu mở rộng.&lt;/p&gt;

&lt;p&gt;Trang tổng hợp: &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;câu-hỏi-luyện-tập-tự-soạn&quot;&gt;Câu hỏi luyện tập (tự soạn)&lt;/h2&gt;

&lt;h3 id=&quot;q1-momentum-trên-thung-lũng-hẹp&quot;&gt;Q1. Momentum trên thung lũng hẹp&lt;/h3&gt;

&lt;p&gt;SGD thuần túy thường dao động qua lại ngang thung lũng hẹp và tiến rất chậm dọc theo trục dài. Hãy giải thích ngắn gọn (mỗi hướng một câu) bộ đệm vận tốc \(\mathbf{v}\leftarrow \beta\mathbf{v}+\nabla J\) làm thay đổi hành vi đó như thế nào?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Các thành phần đổi dấu liên tục sẽ tự triệt tiêu khi lấy trung bình, còn các gradient cùng chiều sẽ cộng dồn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Theo phương ngang thung lũng, dấu của gradient đảo liên tục nên trung bình vận tốc nhỏ đi và dao động tắt dần. Theo phương dọc thung lũng, gradient giữ nguyên dấu nên \(\mathbf{v}\) tích lũy lớn dần và giúp bước đi nhanh hơn. Khi phỏng vấn, chỉ cần trình bày trực giác này; không cần khai triển công thức theo \(\beta\) trừ khi được yêu cầu.&lt;/p&gt;

&lt;h3 id=&quot;q2-vì-sao-adam-cần-hiệu-chỉnh-độ-lệch-bias-correction&quot;&gt;Q2. Vì sao Adam cần hiệu chỉnh độ lệch (bias correction)&lt;/h3&gt;

&lt;p&gt;Moment bậc nhất trong Adam được tính theo công thức \(\mathbf{m}_t=\beta_1\mathbf{m}_{t-1}+(1-\beta_1)\mathbf{g}_t\) với \(\mathbf{m}_0=\mathbf{0}\). Vì sao \(\mathbf{m}_t\) lại quá nhỏ tại \(t=1\), và phép chia cho \(1-\beta_1^t\) có tác dụng gì?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Thay trực tiếp \(t=1\) vào công thức: \(\mathbf{m}_1=(1-\beta_1)\mathbf{g}_1\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Tại \(t=1\), \(\mathbf{m}_1\) chỉ giữ lại một phần tỷ lệ \((1-\beta_1)\) của gradient đầu tiên (chỉ bằng \(0.1\) khi \(\beta_1=0.9\)). Hệ số \(1-\beta_1^t\) chính là tổng trọng số của chuỗi hình học đã cộng tới bước \(t\); chia cho hệ số này giúp khử hiện tượng ước lượng bị co nhỏ lúc khởi đầu. Lập luận tương tự áp dụng cho moment bậc hai với \(\beta_2\). Sau vài trăm bước, \(\beta^t\approx 0\) nên tác động của phép hiệu chỉnh gần như không đáng kể, nhưng trong phỏng vấn bạn vẫn cần giải thích rõ trường hợp \(t=1\).&lt;/p&gt;

&lt;h3 id=&quot;q3-phân-biệt-adam-và-adamw&quot;&gt;Q3. Phân biệt Adam và AdamW&lt;/h3&gt;

&lt;p&gt;Giả sử bạn muốn áp dụng thành phần phạt L2 hiệu dụng \(\frac{\lambda}{2}\|\mathbf{w}\|_2^2\). Vì sao việc cộng \(\lambda\mathbf{w}\) vào gradient rồi để Adam tự điều chỉnh thang lại không tương đương với việc giảm trực tiếp \(\mathbf{w}\) một lượng \(\lambda\eta\) &lt;em&gt;nằm ngoài&lt;/em&gt; mẫu số thích nghi?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Adam chia toàn bộ gradient (kể cả phần bạn cộng thêm) cho \(\sqrt{\hat{\mathbf{v}}}+\epsilon\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Khi gắn weight decay vào gradient, cường độ phạt bị bóp méo theo từng tọa độ: các tham số có moment bậc hai lớn lại bị suy giảm &lt;em&gt;ít&lt;/em&gt; hơn. Ngược lại, AdamW áp dụng weight decay trực tiếp lên trọng số, giúp mọi tọa độ giảm đều theo tỷ lệ \(\lambda\eta\) (chưa tính lịch learning rate). Đây là lựa chọn mặc định trong các cấu hình huấn luyện CNN và Transformer hiện đại; câu hỏi này kiểm tra xem bạn có hiểu rõ &lt;em&gt;lý do&lt;/em&gt; đằng sau sự tách rời đó hay không.&lt;/p&gt;

&lt;h3 id=&quot;q4-khi-nào-sgdmomentum-có-thể-vượt-adam&quot;&gt;Q4. Khi nào SGD+momentum có thể vượt Adam&lt;/h3&gt;

&lt;p&gt;Một mạng tích chập huấn luyện trên tập ảnh lớn đạt khả năng tổng quát hóa kém hơn khi dùng Adam (dù đã tinh chỉnh) so với SGD+momentum chạy lâu hơn. Hãy đưa ra một giả thuyết từ góc độ tối ưu hóa và một giả thuyết từ góc độ chính quy hóa ẩn — tránh trả lời chung chung rằng “Adam bị lỗi”.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Phương pháp thích nghi liên tục thay đổi hệ số điều chỉnh theo từng tọa độ, trong khi SGD giữ một thang bước học chung trên toàn không gian.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Về mặt tối ưu hóa: Adam có thể nhanh chóng đi vào vùng cực tiểu nhọn của \(J\) và dừng lại ở đó do bước học theo từng tọa độ vẫn duy trì lớn ở các chiều có gradient nhỏ. Về mặt thiên kiến ẩn (&lt;em&gt;implicit bias&lt;/em&gt;): nhiễu mini-batch của SGD kết hợp với learning rate đồng nhất tạo ra phân phối dừng trên tập các cực tiểu khác với nhiễu đã qua tiền điều kiện của Adam. Cả hai đều là giả thuyết thực nghiệm chứ không phải định lý cần chứng minh trên bảng; trong thực tế, bạn nên nêu rõ cách kiểm chứng lại bằng cách chạy SGD đủ dài và đánh giá trên tập validation với nhiều hạt giống ngẫu nhiên (seed) khác nhau.&lt;/p&gt;

&lt;h3 id=&quot;q5-vai-trò-của-warmup-trong-một-ý&quot;&gt;Q5. Vai trò của Warmup trong một ý&lt;/h3&gt;

&lt;p&gt;Bạn khởi động huấn luyện Transformer bằng AdamW ngay tại learning rate đỉnh và hàm mất mát lập tức sinh ra NaN. Vì sao tăng tuyến tính \(\eta\) trong vài nghìn bước đầu lại có thể khắc phục, dù giá trị \(\eta\) &lt;em&gt;đỉnh&lt;/em&gt; không hề thay đổi?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Lúc mới khởi tạo, giá trị kích hoạt và logit của tầng attention chưa ổn định về thang đo; các bước cập nhật lớn lại diễn ra khi ước lượng \(\mathbf{m},\mathbf{v}\) chưa đáng tin cậy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Ở giai đoạn đầu, gradient thường rất lớn và biến động mạnh, đồng thời ước lượng moment bậc hai của Adam vẫn còn ít mẫu nên thiếu ổn định (liên hệ Q2). Giữ \(\eta\) nhỏ lúc đầu cho phép các ước lượng moment và luồng kết nối dư (&lt;em&gt;residual stream&lt;/em&gt;) ổn định trước khi áp dụng bước học lớn như trong huấn luyện ImageNet hay LLM. Tuy nhiên, warmup không thể cứu một cấu hình nếu bản thân learning rate đỉnh vốn đã quá lớn — khi đó mô hình vẫn sẽ phân kỳ ngay sau khi kết thúc warmup.&lt;/p&gt;

&lt;h2 id=&quot;ghi-công&quot;&gt;Ghi công&lt;/h2&gt;

&lt;p&gt;Kashani, S., và Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Bạn có thể tải bản PDF từ arXiv để xem toàn bộ bộ câu hỏi và lời giải. Các câu hỏi trên trang này được biên soạn riêng cho khóa học, không phải bản sao chép lại từ sách.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, tiếng Anh. Nên xem lại trước khi trả lời các câu phỏng vấn về bộ tối ưu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Ôn lại cách suy ra công thức cập nhật của Adam để viết lại chính xác khi phỏng vấn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Ôn lại bước cập nhật thuần túy khi bỏ các thành phần moment.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-01 Thuật toán Tối ưu Nâng cao</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_01_Advanced_Optimizers/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_01_Advanced_Optimizers</id>
   <content type="html">&lt;p&gt;Chọn đúng bộ tối ưu không chỉ quyết định mô hình hội tụ sau 2 giờ hay 2 ngày, mà còn ảnh hưởng trực tiếp tới &lt;strong&gt;khả năng tổng quát hóa&lt;/strong&gt; trên dữ liệu thực tế: tại sao ResNet trên ImageNet thường đạt đỉnh bằng SGD + Momentum, còn Transformer/LLM gần như bắt buộc phải dùng AdamW? Mục này hệ thống hóa trọn vẹn từ nền tảng toán học, cài đặt từ đầu cho đến bản đồ so sánh và cạm bẫy thực chiến.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-học-phần-thuật-toán-tối-ưu-nâng-cao&quot;&gt;Kiến thức cần nhớ: Ba trụ cột học phần Thuật toán Tối ưu Nâng cao&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phả hệ toán học của các bộ tối ưu&lt;/strong&gt;:
Hiểu rõ bước tiến hóa logic: SGD \(\to\) Momentum / Nesterov (thêm moment bậc 1 \(m_t\)) và AdaGrad \(\to\) RMSprop (thêm moment bậc 2 \(v_t\) có suy giảm mũ) \(\to\) Adam / AdamW (hợp nhất cả hai).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tự cài đặt từ đầu và trực quan hóa quỹ đạo&lt;/strong&gt;:
Viết tay lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Momentum&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RMSprop&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Adam&lt;/code&gt; trong vài chục dòng Python/NumPy và vẽ quỹ đạo di chuyển của chúng trên bề mặt thung lũng hẹp 2D (như hàm Rosenbrock) để thấy tận mắt sự khác biệt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chiến lược chọn Bộ tối ưu và Lịch Learning Rate&lt;/strong&gt;:
Biết phối hợp bộ tối ưu với Warmup + Cosine Annealing, hiểu lý do tách rời Weight Decay (AdamW) và tránh bẫy tuning sai siêu tham số \((\beta_1, \beta_2, \epsilon)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-bảng-tóm-tắt-4-phương-trình-cập-nhật-cốt-lõi-để-đối-chiếu-trong-một-cái-nhìn&quot;&gt;Giải thích: Bảng tóm tắt 4 phương trình cập nhật cốt lõi để đối chiếu trong một cái nhìn&lt;/h3&gt;

&lt;p&gt;Gọi \(g_t = \nabla_\theta \mathcal{L}(\theta_{t-1})\) là gradient tại bước \(t\) và \(\eta\) là tốc độ học:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Bộ tối ưu&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Biến trạng thái tích lũy&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Quy tắc cập nhật tham số \(\theta_t\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Bộ nhớ trạng thái thêm / 1 tham số&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;SGD&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Không có&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\theta_{t-1} - \eta g_t\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;0&lt;/strong&gt; số&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;SGD + Momentum&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(v_t = \beta v_{t-1} + g_t\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\theta_{t-1} - \eta v_t\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;1&lt;/strong&gt; số (\(v\))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;RMSprop&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(s_t = \rho s_{t-1} + (1-\rho) g_t^2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\theta_{t-1} - \frac{\eta}{\sqrt{s_t} + \epsilon} g_t\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;1&lt;/strong&gt; số (\(s\))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Adam&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(m_t\) (bậc 1) &amp;amp; \(v_t\) (bậc 2) kèm hiệu chỉnh \(\hat{m}_t, \hat{v}_t\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\theta_{t-1} - \frac{\eta}{\sqrt{\hat{v}_t} + \epsilon} \hat{m}_t\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;2&lt;/strong&gt; số (\(m, v\))&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chú ý cột cuối cùng rất quan trọng khi huấn luyện mô hình lớn: với mô hình 7 tỷ tham số (FP32 = 4 byte/số), riêng hai bảng trạng thái \((m, v)\) của Adam đã ngốn thêm &lt;strong&gt;56 GB VRAM&lt;/strong&gt;!&lt;/p&gt;

&lt;p&gt;Bài học này trình bày các bộ tối ưu hiện đại cải tiến từ hạ gradient thuần túy:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết Bộ tối ưu&lt;/strong&gt; — Momentum, NAG, AdaGrad, RMSprop, Adam, AdamW và trực giác hình học.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt Bộ tối ưu&lt;/strong&gt; — mã cài đặt so sánh, bài báo nền tảng, các cạm bẫy thường gặp và điểm then chốt.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, tiếng Anh. Tổng quan nhóm thuật toán được phân tích trong phần lý thuyết và phần cài đặt.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Giải thích hai ước lượng moment của Adam, đúng với phép cập nhật bạn sẽ tự cài đặt.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 7&lt;/td&gt;
          &lt;td&gt;Training Neural Networks II](https://www.youtube.com/watch?v=_JB0AO7QxSA) — Stanford University School of Engineering, tiếng Anh. Bài giảng về tối ưu hóa đặt cùng nhóm thuật toán này trong bối cảnh huấn luyện mạng nơ-ron đầy đủ.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-01-02 Cài đặt Bộ tối ưu</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_01_02_Optimizer_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_01_02_Optimizer_Implementation</id>
   <content type="html">&lt;p&gt;Đằng sau dòng lệnh quen thuộc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)&lt;/code&gt; chỉ là một vòng lặp rất ngắn cập nhật từng tensor tham số dựa trên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.grad&lt;/code&gt; và từ điển trạng thái &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;state&lt;/code&gt;. Khi tự viết lại các bộ tối ưu từ đầu và quan sát chúng chạy đua trên cùng một bề mặt hàm mất mát 2D, bạn sẽ phát triển được “cảm giác trực quan” để chẩn đoán ngay lập tức khi quá trình huấn luyện bị dao động hoặc đứng im.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-khi-triển-khai-và-đối-chiếu-bộ-tối-ưu&quot;&gt;Kiến thức cần nhớ: Ba trụ cột khi triển khai và đối chiếu Bộ tối ưu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Thiết kế giao diện chuẩn hóa (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;step()&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;zero_grad()&lt;/code&gt;)&lt;/strong&gt;:
Mỗi bộ tối ưu lưu từ điển trạng thái (vận tốc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;v&lt;/code&gt;, bình phương trượt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;s&lt;/code&gt;, bộ đếm bước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t&lt;/code&gt;) gắn liền với từng tensor tham số, và tuyệt đối phải xóa gradient cũ trước mỗi bước backward (trừ khi cố ý dùng gradient accumulation).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trực quan hóa quỹ đạo 2D trên hàm thách thức (Rosenbrock / Thung lũng hẹp)&lt;/strong&gt;:
So sánh trực diện SGD, Momentum, RMSprop và Adam trên cùng một xuất phát điểm để thấy cách từng thuật toán xử lý hướng dốc và hướng phẳng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân biệt L2 Regularization và Decoupled Weight Decay trong mã nguồn&lt;/strong&gt;:
Chỉ khác nhau đúng 1 dòng code — cộng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;wd * param&lt;/code&gt; vào &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad&lt;/code&gt; (Adam + L2) hay trừ trực tiếp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lr * wd * param&lt;/code&gt; vào &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;param&lt;/code&gt; (AdamW) — nhưng tạo ra sự khác biệt lớn về độ tổng quát hóa!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-sự-khác-biệt-giữa-adam--l2-và-adamw-trên-1-tham-số&quot;&gt;Giải thích: Tính tay sự khác biệt giữa Adam + L2 và AdamW trên 1 tham số&lt;/h3&gt;

&lt;p&gt;Giả sử \(w = 2{,}0\), gradient dữ liệu \(g = 0{,}0\) (chỉ còn hiệu ứng phân rã trọng số), \(\eta = 0{,}1\), hệ số weight decay \(\lambda = 0{,}5\), và ước lượng moment bậc 2 hiện tại là \(\sqrt{\hat{v}_t} = 4{,}0\) (một tham số có lịch sử gradient lớn):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Cách cài đặt&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Bước xử lý trọng số phạt&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Độ giảm thực tế của \(w\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Nhận xét&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Adam + L2 truyền thống&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Cộng \(\lambda w = 1{,}0\) vào gradient, rồi &lt;strong&gt;chia cho \(\sqrt{\hat{v}_t} = 4{,}0\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\eta \frac{\lambda w}{\sqrt{\hat{v}_t}} = 0{,}1 \times \frac{1{,}0}{4{,}0} = \mathbf{0{,}025}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Tham số có gradient lớn bị phạt &lt;strong&gt;yếu đi 4 lần&lt;/strong&gt; (mất tác dụng phạt!)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;AdamW (Tách rời)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Trừ trực tiếp \(\eta \lambda w\) &lt;strong&gt;không chia cho \(\sqrt{\hat{v}_t}\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\eta \lambda w = 0{,}1 \times 0{,}5 \times 2{,}0 = \mathbf{0{,}100}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Mọi tham số đều co đều đúng tỷ lệ \(\eta \lambda = 5\%\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chính sự khác biệt ở mẫu số \(\sqrt{\hat{v}_t}\) này giải thích vì sao Loshchilov &amp;amp; Hutter (2019) chỉ ra rằng &lt;strong&gt;Adam + L2 không hề tương đương với Weight Decay&lt;/strong&gt;, và AdamW lập tức trở thành tiêu chuẩn mới!&lt;/p&gt;

&lt;p&gt;Nội dung phần cài đặt bộ tối ưu gồm hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt Cốt lõi&lt;/strong&gt; — cài đặt từ đầu các bộ tối ưu từ Momentum đến AdamW.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh, Bài báo và Cạm bẫy&lt;/strong&gt; — minh họa quỹ đạo 2D, so sánh trên bài toán phân loại, tổng hợp bài báo nền tảng và các lưu ý thực hành.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Trình bày quy tắc cập nhật Adam sẽ được cài đặt trong bài mã.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, tiếng Anh. Đối chiếu với RMSprop và AdaGrad giúp dễ phát hiện sai sót khi cài đặt từng bộ đệm.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, tiếng Anh. Cách gọi bộ tối ưu trong vòng lặp huấn luyện PyTorch sau khi đã hiểu rõ phép cập nhật.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-01-02-02 So sánh Bộ tối ưu, Bài báo và Cạm bẫy</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_01_02_02_Optimizer_Comparisons_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_01_02_02_Optimizer_Comparisons_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Chạy cùng một mạng neuron trên cùng một bộ dữ liệu, tại sao có bài toán Adam chỉ mất 50 epoch để chạm đáy trong khi SGD mất 500 epoch — nhưng lại có những cuộc thi thị giác máy tính mà SGD + Momentum sau khi tinh chỉnh kỹ lịch Cosine Annealing lại vượt Adam 1–2% độ chính xác kiểm định? Bài học này đặt các bộ tối ưu lên bàn cân thực nghiệm, phân tích lý do đằng sau khoảng cách tổng quát hóa và liệt kê những cạm bẫy tinh chỉnh hay gặp nhất.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-bài-học-thực-nghiệm-khi-so-sánh-và-tinh-chỉnh-bộ-tối-ưu&quot;&gt;Kiến thức cần nhớ: Bốn bài học thực nghiệm khi so sánh và tinh chỉnh Bộ tối ưu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tốc độ hội tụ sớm vs. Chất lượng tổng quát hóa cuối cùng&lt;/strong&gt;:
Adam/AdamW thích nghi siêu nhanh ở giai đoạn đầu và rất ít nhạy cảm với tốc độ học khởi tạo, nên là lựa chọn số 1 cho NLP/Transformer và thử nghiệm nhanh; SGD + Momentum tuy cần chỉnh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lr&lt;/code&gt; kỹ hơn nhưng thường hội tụ vào các cực tiểu phẳng hơn trên CNN thị giác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định luật phối hợp Siêu tham số (LR × Batch Size × Weight Decay)&lt;/strong&gt;:
Khi tăng gấp \(k\) lần &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_size&lt;/code&gt;, phương sai nhiễu gradient giảm đi \(k\) lần — ta thường tăng learning rate theo quy tắc tuyến tính (Linear Scaling cho SGD) hoặc căn bậc hai (\(\sqrt{k}\) cho Adam), kèm giai đoạn warmup.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không áp dụng Weight Decay cho Bias và LayerNorm/BatchNorm&lt;/strong&gt;:
Phạt trọng số lên hệ số dịch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias&lt;/code&gt; hay hệ số co giãn \(\gamma\) của LayerNorm/BatchNorm không giúp chống overfitting mà còn làm suy yếu khả năng biểu diễn; thực tế luôn tách &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;param_groups&lt;/code&gt; để đặt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_decay=0.0&lt;/code&gt; cho các tham số 1D này.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cạm bẫy kinh điển khi huấn luyện với Bộ tối ưu thích nghi&lt;/strong&gt;:
Dùng chung một &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lr&lt;/code&gt; (ví dụ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.1&lt;/code&gt; của SGD mang sang Adam sẽ lập tức nổ loss!), quên giảm learning rate ở cuối quá trình (Cosine/Step Decay), hoặc chọn \(\beta_2 = 0{,}999\) quá cao trên bài toán gradient thay đổi đột ngột (như GAN hay RL, nơi \(\beta_2 = 0{,}95\) hoặc \(0{,}9\) ổn định hơn nhiều).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-quy-tắc-tách-nhóm-tham-số-weight-decay-và-tỷ-lệ-điều-chỉnh-learning-rate-theo-batch-size&quot;&gt;Giải thích: Tính tay quy tắc tách nhóm tham số Weight Decay và tỷ lệ điều chỉnh Learning Rate theo Batch Size&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Tách nhóm tham số Weight Decay cho 1 tầng Linear &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;128 -&amp;gt; 64&lt;/code&gt; kèm LayerNorm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;64&lt;/code&gt;&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nhóm 1 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_decay = 0.01&lt;/code&gt;): ma trận trọng số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;W&lt;/code&gt; có \(128 \times 64 = \mathbf{8{,}192}\) tham số (2D).&lt;/li&gt;
  &lt;li&gt;Nhóm 2 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_decay = 0.0&lt;/code&gt;): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias&lt;/code&gt; (64) + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LayerNorm.weight&lt;/code&gt; (64) + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LayerNorm.bias&lt;/code&gt; (64) = &lt;strong&gt;192&lt;/strong&gt; tham số (1D).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Điều chỉnh Learning Rate khi tăng Batch Size từ \(B_1 = 64\) lên \(B_2 = 256\) (gấp \(k = 4\) lần)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Với &lt;strong&gt;SGD + Momentum&lt;/strong&gt; (Linear Scaling Rule): \(\eta_2 = k \cdot \eta_1 = 4 \times 0{,}01 = \mathbf{0{,}04}\).&lt;/li&gt;
  &lt;li&gt;Với &lt;strong&gt;Adam / AdamW&lt;/strong&gt; (Square-Root Scaling Rule): \(\eta_2 = \sqrt{k} \cdot \eta_1 = \sqrt{4} \times 3\times 10^{-4} = \mathbf{6 \times 10^{-4}}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nắm vững hai quy tắc đơn giản này giúp bạn mở rộng huấn luyện từ 1 GPU lên 4–8 GPU mà giữ nguyên đường cong hội tụ!&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Demo so sánh bộ tối ưu trên bài toán tối ưu 2D
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;So sánh Bộ tối ưu trên Hàm Rosenbrock&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Rosenbrock: f(x,y) = (1-x)² + 100(y-x²)²&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cực tiểu tại (1, 1), nhưng thung lũng cong hẹp khiến tối ưu khó&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hàm kiểm thử tối ưu kinh điển với thung lũng cong hẹp&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient của hàm Rosenbrock&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;400&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Khởi tạo tham số (bắt đầu xa cực tiểu)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo bộ tối ưu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;opt_sgd&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]})()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;opt_momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SGDMomentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;opt_rmsprop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;opt_adam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Theo dõi quỹ đạo
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trajectories&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Momentum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tối ưu 500 bước
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# SGD thuần túy
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;opt_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trajectories&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Momentum
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;opt_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trajectories&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Momentum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# RMSprop
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;opt_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trajectories&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Adam
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;opt_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trajectories&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# So sánh vị trí cuối
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vị trí cuối sau 500 bước:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  SGD:      (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Momentum: (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  RMSprop:  (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Adam:     (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Cực tiểu thật: (1.0000, 1.0000)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Quan sát:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Momentum tăng tốc dọc thung lũng&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- RMSprop thích nghi với các độ cong khác nhau&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Adam kết hợp lợi ích của cả hai&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- SGD thuần túy chậm nhất (mắc kẹt trong dao động)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Tiếp theo là ví dụ minh họa trên quá trình huấn luyện một mạng nơ-ron thực tế:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.utils.data&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;TensorDataset&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo tác vụ phân loại đơn giản
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện Mạng Neuron với các Bộ tối ưu Khác nhau&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh dữ liệu tổng hợp: bài toán kiểu XOR
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# XOR
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TensorDataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Mạng đơn giản
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện với các bộ tối ưu khác nhau
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizers_to_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SGD+Momentum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; 
                                                   &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;AdamW&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AdamW&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                            &lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizer_fn&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizers_to_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện với &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tạo mô hình mới
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;optimizer_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BCELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Huấn luyện
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_batch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Xuôi
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Ngược
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Độ chính xác kiểm tra
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;final_loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# So sánh kết quả
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kết quả So sánh Bộ tối ưu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bộ tối ưu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Loss cuối&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Độ chính xác&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;45&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;final_loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;12.4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;10.2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Quan sát then chốt:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Momentum tăng tốc hội tụ so với SGD thuần túy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Phương pháp thích nghi (RMSprop, Adam) hội tụ nhanh hơn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- AdamW thường tổng quát hóa tốt nhất với weight decay&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Lựa chọn quan trọng: chênh lệch tốc độ 2–5× là phổ biến&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Ví dụ về lịch trình điều chỉnh learning rate:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CosineAnnealingSchedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Lịch trình learning rate cosine annealing.
    
    Giảm dần learning rate theo đường cong cosine.
    Thường kết hợp warm restart để cải thiện hiệu năng.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        lr_max: learning rate tối đa
        lr_min: learning rate tối thiểu
        T_max: chu kỳ của cosine (số vòng lặp)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_max&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;get_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lấy learning rate tại vòng lặp t&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; \
               &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CosineAnnealingSchedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_max&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lịch trình Learning Rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;iterations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;300&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lrs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tiến hóa learning rate (300 vòng lặp đầu):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Bắt đầu: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Sau 50 vòng: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Sau 100 vòng: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (hết chu kỳ, khởi động lại)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Sau 150 vòng: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cosine annealing giảm LR mượt, cho phép tinh chỉnh gần cực tiểu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Mối liên hệ giữa thuật toán tối ưu và hình học của bề mặt mất mát giải thích vì sao mỗi bộ tối ưu phát huy ưu thế trong những tình huống khác nhau. Bề mặt mất mát của mạng nơ-ron sâu có tính không lồi mạnh, chứa nhiều cực tiểu địa phương, điểm yên ngựa và vùng phẳng. Trong không gian nhiều chiều, điểm yên ngựa — nơi gradient bằng 0 nhưng không phải cực tiểu — xuất hiện phổ biến hơn nhiều so với cực tiểu địa phương. Momentum giúp vượt qua điểm yên ngựa nhờ vận tốc tích lũy đưa tham số qua vùng có gradient gần bằng 0. Trong khi đó, learning rate thích nghi phát huy hiệu quả khi độ cong giữa các chiều chênh lệch lớn, điều rất thường gặp trong mạng nơ-ron khi một số tham số (như bias) có gradient khá ổn định còn các tham số khác (như ma trận trọng số) có độ lớn gradient biến thiên mạnh.&lt;/p&gt;

&lt;p&gt;So sánh với các phương pháp tối ưu bậc hai giúp làm rõ nền tảng lý thuyết của nhóm thuật toán thích nghi. Phương pháp Newton sử dụng đạo hàm bậc hai (ma trận Hessian) để hiệu chỉnh trực tiếp theo độ cong, cho tốc độ hội tụ nhanh hơn. Tuy nhiên, với mạng có hàng triệu tham số, việc tính và nghịch đảo ma trận Hessian đòi hỏi bộ nhớ \(O(n^2)\) và chi phí tính toán \(O(n^3)\), vượt quá khả năng thực tế. Các phương pháp như Adam xấp xỉ thông tin bậc hai thông qua thống kê gradient (moment bậc hai \(\mathbf{v}_t\) liên hệ với các phần tử trên đường chéo của ma trận Hessian) mà vẫn giữ chi phí tính toán tuyến tính. Dù kém chính xác hơn phương pháp Newton đầy đủ, phép xấp xỉ này vẫn đủ để tăng tốc huấn luyện đáng kể trong thực tế.&lt;/p&gt;

&lt;p&gt;Bộ tối ưu cũng tương tác chặt chẽ với batch normalization và các kỹ thuật chuẩn hóa khác. Batch normalization làm bề mặt mất mát mượt hơn và giảm độ nhạy với learning rate. Khi có chuẩn hóa, lợi thế của một số bộ tối ưu có thể thay đổi: chẳng hạn, Adam đi kèm batch normalization đôi khi hội tụ tới điểm cực tiểu có khả năng tổng quát hóa kém hơn SGD kết hợp momentum — hiện tượng thường gọi là “khoảng cách tổng quát hóa” (&lt;em&gt;generalization gap&lt;/em&gt;). Do đó, việc chọn bộ tối ưu thường gắn liền với kiến trúc: các mô hình Transformer (sử dụng layer normalization) thường đạt kết quả tốt nhất với AdamW, trong khi các mạng ResNet (sử dụng batch normalization) thường ưu tiên SGD kết hợp momentum cho độ chính xác cuối cùng.&lt;/p&gt;

&lt;p&gt;Sự chuyển dịch từ learning rate chỉnh tay sang các phương pháp thích nghi phản ánh một xu hướng rộng hơn trong học sâu: giảm bớt công sức tinh chỉnh siêu tham số thủ công. Trước đây, việc huấn luyện mạng nơ-ron đòi hỏi điều chỉnh rất kỹ learning rate, lịch trình giảm và hệ số momentum. Các bộ tối ưu thích nghi như Adam giúp giảm đáng kể gánh nặng này vì bộ tham số mặc định đã hoạt động ổn định trên nhiều bài toán. Dù vậy, sử dụng bộ tối ưu như một “hộp đen” mà không hiểu các giả định đằng sau vẫn có thể gây giảm hiệu năng trong những trường hợp đặc thù.&lt;/p&gt;

&lt;p&gt;Lịch trình learning rate gắn trực tiếp với sự đánh đổi giữa khám phá và khai thác trong quá trình tối ưu. Ở giai đoạn đầu, bước học lớn giúp mô hình khám phá rộng để nhanh chóng tìm vùng tốt trong không gian tham số. Ở giai đoạn sau, bước học nhỏ hơn giúp tinh chỉnh tham số quanh điểm cực tiểu. Các lịch trình như cosine annealing hay step decay thực hiện cơ chế giảm dần này. Ngược lại, giai đoạn khởi động (&lt;em&gt;warm-up&lt;/em&gt;) bắt đầu từ learning rate rất nhỏ rồi tăng dần, giúp ổn định quá trình huấn luyện khi dùng batch size rất lớn hoặc ở các bước đầu khi trọng số khởi tạo ngẫu nhiên tạo ra gradient bất ổn. Lịch trình warm-up trong bài báo Transformer gốc \(\eta_t = d_{\text{model}}^{-0.5} \min(t^{-0.5}, t \cdot \text{warmup}^{-1.5})\) đã trở thành cấu hình tham chiếu phổ biến khi huấn luyện mô hình lớn.&lt;/p&gt;

&lt;h2 id=&quot;6-bài-báo-nền-tảng&quot;&gt;6. Bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://proceedings.mlr.press/v28/sutskever13.html&quot;&gt;“On the importance of initialization and momentum in deep learning” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ilya Sutskever, James Martens, George Dahl, Geoffrey Hinton&lt;br /&gt;
Bài báo này phân tích có hệ thống vai trò của momentum trong học sâu, cho thấy đây không chỉ là cải tiến phụ mà là yếu tố thiết yếu để huấn luyện mạng sâu. Các tác giả chứng minh rằng kết hợp momentum với cách khởi tạo trọng số phù hợp cho phép huấn luyện mạng sâu hơn nhiều so với SGD thuần túy, đồng thời giúp vượt qua điểm yên ngựa và giảm nhiễu từ gradient mini-batch. Bên cạnh phân tích lý thuyết nối momentum với tối ưu cổ điển, bài báo còn cho thấy Nesterov momentum đạt hiệu quả ổn định hơn momentum chuẩn trên nhiều thử nghiệm, qua đó khẳng định rằng thuật toán tối ưu cần được thiết kế phù hợp với đặc thù không lồi, nhiều chiều và có nhiễu của học sâu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1412.6980&quot;&gt;“Adam: A Method for Stochastic Optimization” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Diederik P. Kingma, Jimmy Ba&lt;br /&gt;
Bài báo giới thiệu Adam và chứng minh hiệu quả trên nhiều bài toán như phân loại ảnh, mô hình ngôn ngữ và suy luận biến phân. Đóng góp chính là kết hợp learning rate thích nghi (tương tự RMSprop) với momentum và cơ chế hiệu chỉnh độ lệch ở các bước đầu. Với các giá trị mặc định \(\beta_1=0.9, \beta_2=0.999\) hoạt động tốt trên nhiều bài toán, Adam giảm đáng kể yêu cầu tinh chỉnh siêu tham số và trở thành lựa chọn mặc định rộng rãi, đặc biệt trong NLP nơi đặc trưng từ vựng rất thưa. Bài báo cũng đề xuất biến thể AdaMax (dùng chuẩn \(L_\infty\) thay cho \(L_2\)) và cung cấp phân tích cận hối tiếc (&lt;em&gt;regret bound&lt;/em&gt;) trong khung tối ưu lồi trực tuyến.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1711.05101&quot;&gt;“Decoupled Weight Decay Regularization” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ilya Loshchilov, Frank Hutter&lt;br /&gt;
Bài báo chỉ ra điểm bất hợp lý trong cách Adam xử lý chính quy hóa L2 và đề xuất AdamW. Khi cộng weight decay vào gradient rồi đưa qua phép chuẩn hóa thích nghi của Adam, mức suy giảm trọng số thực tế thay đổi theo thống kê gradient — những tham số có gradient lớn lại bị phạt nhẹ hơn. AdamW tách weight decay ra khỏi bước cập nhật gradient và áp dụng trực tiếp lên tham số. Thực nghiệm cho thấy AdamW cải thiện rõ rệt khả năng tổng quát hóa, đặc biệt trên Transformer, và dần thay thế Adam trong huấn luyện các mô hình ngôn ngữ lớn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1908.03265&quot;&gt;“On the Variance of the Adaptive Learning Rate and Beyond” (2020)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Liyuan Liu, Haoming Jiang, Pengcheng He, Weizhu Chen, Xiaodong Liu, Jianfeng Gao, Jiawei Han&lt;br /&gt;
Bài báo phân tích nguyên nhân khiến Adam đôi khi tổng quát hóa kém hơn SGD dù hội tụ nhanh hơn (“khoảng cách tổng quát hóa”). Các tác giả chỉ ra rằng phương sai lớn của learning rate thích nghi ở giai đoạn đầu có thể đẩy mô hình vào các cực tiểu nhọn (tổng quát hóa kém), trong khi SGD với momentum thường tiến tới cực tiểu phẳng hơn. Từ đó, bài báo đề xuất RAdam (&lt;em&gt;Rectified Adam&lt;/em&gt;) với cơ chế hiệu chỉnh thận trọng hơn khi thống kê gradient chưa ổn định, góp phần làm rõ sự đánh đổi giữa tốc độ hội tụ và khả năng tổng quát hóa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1907.08610&quot;&gt;“Lookahead Optimizer: k steps forward, 1 step back” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Michael R. Zhang, James Lucas, Geoffrey Hinton, Jimmy Ba&lt;br /&gt;
Bài báo đề xuất một thuật toán tối ưu bọc ngoài (&lt;em&gt;meta-optimizer&lt;/em&gt;) có thể kết hợp với bất kỳ bộ tối ưu cơ sở nào như SGD hay Adam. Lookahead duy trì song song hai bộ trọng số: trọng số nhanh được cập nhật \(k\) bước (thường 5–10 bước) bởi bộ tối ưu cơ sở, sau đó trọng số chậm được nội suy tiến về phía trọng số nhanh rồi đặt lại trọng số nhanh về vị trí trọng số chậm. Cơ chế này giúp giảm phương sai quỹ đạo tối ưu, ổn định quá trình huấn luyện và thường cải thiện khả năng tổng quát hóa trên các bài toán thị giác lẫn ngôn ngữ.&lt;/p&gt;

&lt;h2 id=&quot;cạm-bẫy-thường-gặp-và-mẹo&quot;&gt;Cạm bẫy thường gặp và Mẹo&lt;/h2&gt;

&lt;p&gt;Một lỗi phổ biến khi dùng bộ tối ưu thích nghi như Adam là thay đổi batch size nhưng giữ nguyên các siêu tham số. Với SGD thuần túy, khi tăng gấp đôi batch size, ta thường cần tăng gần gấp đôi learning rate để giữ mức cập nhật tương đương. Với Adam, mối quan hệ phức tạp hơn vì bước cập nhật đã tự chuẩn hóa theo độ lớn gradient; quy tắc kinh nghiệm thường là tăng learning rate nhẹ hơn (chẳng hạn theo tỷ lệ \(\sqrt{2}\) thay vì \(2\)) và theo dõi kỹ kết quả trên tập validation. Khi batch size rất lớn (hàng nghìn mẫu), nên kết hợp thêm giai đoạn warm-up để tránh bất ổn ở các bước đầu.&lt;/p&gt;

&lt;p&gt;Một điểm cần lưu ý khác là trạng thái nội bộ của bộ tối ưu khi fine-tune mô hình tiền huấn luyện. Nếu tải trọng số tiền huấn luyện và bắt đầu chạy Adam mới, các bộ đệm momentum và phương sai đều khởi tạo bằng 0, chưa phản ánh đúng thang gradient của mô hình đã gần hội tụ, dễ gây nhiễu loạn trọng số ban đầu. Cách xử lý phù hợp là dùng learning rate nhỏ hơn khi fine-tune để bộ tối ưu tích lũy trạng thái dần dần, hoặc thiết lập lại trạng thái bộ tối ưu cùng lịch trình warm-up ngắn khi chuyển sang giai đoạn huấn luyện mới.&lt;/p&gt;

&lt;p&gt;Hệ số weight decay của AdamW cũng cần được chỉnh khác với SGD. Trong SGD, giá trị thường nằm quanh 0,0001–0,001; còn trong AdamW, do weight decay đã được tách khỏi bước chia thích nghi, giá trị phổ biến hơn nằm trong khoảng 0,01–0,1. Khi chuyển từ Adam hoặc SGD sang AdamW, không nên giữ nguyên giá trị cũ mà nên bắt đầu thử từ khoảng 0,01 rồi điều chỉnh dựa trên chênh lệch giữa tập huấn luyện và tập kiểm tra.&lt;/p&gt;

&lt;p&gt;Gradient clipping cũng tương tác trực tiếp với các bộ tối ưu thích nghi. Nếu cắt gradient trước khi đưa vào Adam, cả ước lượng moment bậc nhất lẫn bậc hai đều bị giới hạn theo ngưỡng cắt (ví dụ, nếu chuẩn gradient bị giới hạn ở 5 thì bình phương độ lớn tối đa là 25). Tác động này vừa có thể hữu ích (ngăn learning rate hiệu dụng sụt quá nhỏ), vừa có thể hạn chế khả năng thích nghi với thang gradient thật. Thông thường, nên dùng gradient clipping cho RNN và Transformer để đảm bảo ổn định, còn với các mạng đã ổn định thì có thể bỏ qua.&lt;/p&gt;

&lt;p&gt;Cuối cùng, lịch trình learning rate chu kỳ (&lt;em&gt;cyclical learning rate&lt;/em&gt;) — thay đổi learning rate luân phiên giữa hai ngưỡng trong quá trình huấn luyện — có thể giúp mô hình thoát khỏi cực tiểu địa phương và tìm được vùng nghiệm tốt hơn. Khi kết hợp với &lt;em&gt;snapshot ensembling&lt;/em&gt; (lưu lại các checkpoint ở cuối mỗi chu kỳ rồi kết hợp dự đoán của chúng), kỹ thuật này có thể cải thiện hiệu năng mà không tốn thêm đáng kể chi phí huấn luyện.&lt;/p&gt;

&lt;h2 id=&quot;điểm-then-chốt&quot;&gt;Điểm then chốt&lt;/h2&gt;

&lt;p&gt;Các thuật toán tối ưu nâng cao cải thiện hạ gradient thuần túy thông qua hai ý tưởng chính: tích lũy momentum để tăng tốc theo hướng nhất quán và giảm dao động, cùng với việc thích nghi learning rate cho từng tham số dựa trên lịch sử gradient. SGD kết hợp momentum xây dựng vận tốc từ trung bình trượt mũ của gradient, giúp vượt qua bề mặt dạng hẻm núi và các vùng phẳng. RMSprop thích nghi bước học theo trung bình trượt mũ của bình phương gradient, tự cân bằng cập nhật theo độ lớn gradient đặc trưng của từng tham số. Adam kết hợp cả hai cơ chế cùng bước hiệu chỉnh độ lệch ở giai đoạn đầu, trở thành lựa chọn mặc định đáng tin cậy nhờ ít nhạy với siêu tham số. AdamW hoàn thiện Adam bằng cách tách weight decay khỏi bước chuẩn hóa thích nghi, đảm bảo chính quy hóa đồng đều hơn và đặc biệt hiệu quả với Transformer lớn.&lt;/p&gt;

&lt;p&gt;Không có bộ tối ưu nào tốt nhất cho mọi bài toán; việc lựa chọn luôn đòi hỏi cân bằng giữa tốc độ hội tụ, khả năng tổng quát hóa, chi phí tính toán và mức độ nhạy cảm với siêu tham số. Trong thực tế, người làm mô hình thường dùng Adam hoặc AdamW để thử nghiệm nhanh, và có thể chuyển sang SGD kết hợp momentum ở lần huấn luyện cuối nếu ưu tiên khả năng tổng quát hóa trên các bài toán thị giác. Dù các biến thể ngày càng đa dạng, tất cả vẫn dựa trên cùng một nguyên lý: sử dụng gradient từ lan truyền ngược để tinh chỉnh tham số theo từng bước.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, tiếng Anh. Tổng quan so sánh trực tiếp nhóm bộ tối ưu mà bài học triển khai.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Giải thích các điểm dễ sai của Adam như hiệu chỉnh độ lệch và thang learning rate.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vMh0zPT0tLI&quot;&gt;Stochastic Gradient Descent, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Ôn lại SGD — mốc cơ sở để đánh giá mức cải thiện của các bộ tối ưu nâng cao.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-01-02-01 Cài đặt Cốt lõi Bộ tối ưu</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_01_02_01_Optimizer_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_01_02_01_Optimizer_Core_Code</id>
   <content type="html">&lt;p&gt;Viết lại trọn bộ SGD, Momentum, Nesterov, AdaGrad, RMSprop và Adam bằng NumPy thuần chỉ tốn chưa đầy 100 dòng code, nhưng giá trị nhận lại cực kỳ lớn: bạn sẽ hiểu chính xác biến đếm bước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self.t&lt;/code&gt; tăng ở đâu trong Adam, tại sao phép toán &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;in-place&lt;/code&gt; tiết kiệm bộ nhớ GPU, và cách viết dạng triển khai tương đương của Nesterov mà không phải gọi thêm một lượt forward/backward thứ hai!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-chi-tiết-kỹ-thuật-khi-viết-mã-lõi-bộ-tối-ưu&quot;&gt;Kiến thức cần nhớ: Bốn chi tiết kỹ thuật khi viết mã lõi Bộ tối ưu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Quản lý trạng thái per-parameter theo danh sách/từ điển&lt;/strong&gt;:
Mỗi tensor trọng số (ma trận \(W_1\), vector \(b_1\), \(W_2\), …) cần các bộ đệm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;m&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;v&lt;/code&gt; có cùng chính xác shape, khởi tạo bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.zeros_like(param)&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dạng cài đặt 1-pass của Nesterov Momentum&lt;/strong&gt;:
Thay vì tính gradient ở điểm dự đoán \(\theta - \eta \beta v\) (rất bất tiện với API tự động đạo hàm), các framework như PyTorch dùng phép đổi biến tương đương để chỉ cần gọi gradient tại điểm hiện tại nhưng vẫn tạo ra hiệu ứng “nhìn trước” giống hệt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thứ tự tăng bộ đếm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t += 1&lt;/code&gt; trong Adam&lt;/strong&gt;:
Phải tăng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self.t += 1&lt;/code&gt; &lt;strong&gt;trước&lt;/strong&gt; khi tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1 - beta1 ** self.t&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1 - beta2 ** self.t&lt;/code&gt;; nếu để &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t = 0&lt;/code&gt; ở bước đầu sẽ lập tức xảy ra lỗi chia cho 0 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ZeroDivisionError&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hằng số \(\epsilon\) đặt ngoài dấu căn bậc hai&lt;/strong&gt;:
Trong cài đặt Adam chuẩn (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;m_hat / (np.sqrt(v_hat) + eps)&lt;/code&gt;), \(\epsilon\) nằm ngoài dấu căn (mặc định &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-8&lt;/code&gt;, nhưng khi huấn luyện FP16/BF16 nên tăng lên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-6&lt;/code&gt; để tránh underflow làm tròn về 0).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-so-sánh-tốc-độ-giảm-bước-của-adagrad-và-rmsprop-sau-3-bước-gradient-lớn&quot;&gt;Giải thích: Tính tay so sánh tốc độ giảm bước của AdaGrad và RMSprop sau 3 bước gradient lớn&lt;/h3&gt;

&lt;p&gt;Giả sử một tham số liên tục nhận gradient \(g_1 = g_2 = g_3 = 10{,}0\), tốc độ học cơ sở \(\eta = 1{,}0\), và hệ số suy giảm của RMSprop là \(\rho = 0{,}9\) (bỏ qua \(\epsilon\) nhỏ):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Bước \(t\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Tích lũy AdaGrad \(G_t = \sum g_i^2\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Bước nhảy AdaGrad \(\frac{\eta g_t}{\sqrt{G_t}}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;EMA RMSprop \(s_t = 0{,}9 s_{t-1} + 0{,}1 g_t^2\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Bước nhảy RMSprop \(\frac{\eta g_t}{\sqrt{s_t}}\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(t = 1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(100\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\frac{10}{\sqrt{100}} = \mathbf{1{,}000}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(10{,}0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\frac{10}{\sqrt{10}} \approx \mathbf{3{,}162}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(t = 2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(200\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\frac{10}{\sqrt{200}} \approx \mathbf{0{,}707}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(19{,}0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\frac{10}{\sqrt{19}} \approx \mathbf{2{,}294}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(t = 3\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(300\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\frac{10}{\sqrt{300}} \approx \mathbf{0{,}577}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(27{,}1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\frac{10}{\sqrt{27{,}1}} \approx \mathbf{1{,}921}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(t \to \infty\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\to \infty\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(\to 0\) (tắt hẳn!)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Hội tụ về \(100{,}0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Hội tụ về \(1{,}000\) (ổn định!)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Khi \(t\) lớn, mẫu số của AdaGrad phình vô hạn kéo tốc độ học về 0, còn mẫu số của RMSprop tự cân bằng đúng về giá trị bình phương gradient hiện hành (\(10^2 = 100\)) giúp mô hình tiếp tục học bền bỉ!&lt;/p&gt;

&lt;h2 id=&quot;4-đoạn-mã&quot;&gt;4. Đoạn mã&lt;/h2&gt;

&lt;p&gt;Dưới đây là phần cài đặt các bộ tối ưu từ đầu bằng NumPy để minh họa trực tiếp cơ chế cập nhật của từng thuật toán:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SGDMomentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Stochastic Gradient Descent với Momentum.
    
    Duy trì trung bình có trọng số mũ của gradient (vận tốc)
    và dùng nó cho cập nhật thay vì gradient thô. Tăng tốc
    theo hướng nhất quán, dập dao động.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        params: danh sách mảng tham số cần tối ưu
        lr: learning rate
        momentum: hệ số cho vận tốc (β trong phương trình)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Khởi tạo vận tốc bằng zero
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Mỗi tham số có vận tốc riêng cùng shape
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;velocities&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Cập nhật tham số bằng momentum.
        
        grads: danh sách gradient (cùng cấu trúc với params)
        
        Cập nhật vận tốc v_t = β*v_{t-1} + g_t tạo trọng số mũ:
        gradient gần đây đóng góp đầy đủ, gradient cũ hơn
        đóng góp với trọng số β^k. β=0.9 điển hình nghĩa là ta
        hiệu quả trung bình ~10 gradient gần nhất.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật vận tốc: trung bình trượt mũ của gradient
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;velocities&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;velocities&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật tham số bằng vận tốc
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Lưu ý: một số công thức dùng (1-β)*g thay vì g
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Ta theo quy ước PyTorch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;velocities&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    RMSprop: Root Mean Square Propagation.
    
    Thích nghi learning rate theo từng tham số dựa trên trung bình
    trượt mũ của bình phương gradient. Tham số với gradient
    liên tục lớn nhận learning rate hiệu dụng nhỏ hơn.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        beta: tỷ lệ suy giảm cho trung bình bình phương gradient
        epsilon: hằng số nhỏ cho ổn định số
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Khởi tạo trung bình bình phương gradient
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sq_grads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Cập nhật bằng learning rate thích nghi.
        
        Phép chia bởi √E[g²] nghĩa là tham số với gradient điển hình lớn
        nhận cập nhật nhỏ hơn (để ngăn bất ổn), trong khi tham số với
        gradient điển hình nhỏ nhận cập nhật lớn hơn (để tiến).
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật trung bình trượt bình phương gradient
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# E[g²]_t = β*E[g²]_{t-1} + (1-β)*g²_t
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sq_grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sq_grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; 
                               &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Learning rate thích nghi: lr / √E[g²]
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Thêm epsilon ngăn chia cho zero
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;adapted_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sq_grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật tham số
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adapted_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Adam: Adaptive Moment Estimation.
    
    Kết hợp momentum (moment bậc nhất) và RMSprop (moment bậc hai).
    Bao gồm hiệu chỉnh độ lệch cho hành vi đúng đầu huấn luyện.
    Bộ tối ưu chuẩn thực tế cho nhiều tác vụ học sâu.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        beta1: tỷ lệ suy giảm moment bậc nhất (momentum)
        beta2: tỷ lệ suy giảm moment bậc hai (RMSprop)
        
        Giá trị mặc định hoạt động tốt trên nhiều tác vụ — sức mạnh
        của Adam là độ vững với lựa chọn siêu tham số.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Khởi tạo moment
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Moment bậc nhất
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Moment bậc hai
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Bước thời gian (cho hiệu chỉnh độ lệch)
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Cập nhật Adam với hiệu chỉnh độ lệch.
        
        Hiệu chỉnh độ lệch then chốt đầu huấn luyện khi m_t và v_t
        lệch về zero. Không hiệu chỉnh, cập nhật sớm quá nhỏ,
        làm chậm huấn luyện ban đầu. Hệ số hiệu chỉnh 1/(1-β^t)
        lớn ở các bước đầu và giảm dần về 1 khi t tăng.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Tăng bước thời gian
&lt;/span&gt;        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật ước lượng moment bậc nhất lệch (momentum)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật ước lượng moment bậc hai lệch (RMSprop)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Tính moment đã hiệu chỉnh độ lệch
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Các hiệu chỉnh này lớn nhất sớm (khi t nhỏ)
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# và tiến về 1 khi t → ∞
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;m_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;v_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật tham số
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Kết hợp hướng momentum (m_hat) với scale thích nghi (√v_hat)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;AdamW&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    AdamW: Adam với weight decay tách rời.
    
    Tách chính quy hóa L2 khỏi tối ưu dựa trên gradient.
    Tổng quát hóa tốt hơn Adam, đặc biệt với Transformer.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                 &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Cập nhật Adam với weight decay tách rời.
        
        Khác biệt then chốt so với Adam: weight decay được áp dụng trực tiếp
        lên tham số (θ ← θ - ηλθ) thay vì được cộng vào gradient.
        Điều này đảm bảo cường độ chính quy hóa độc lập với scale
        learning rate thích nghi.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật moment (giống Adam)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Hiệu chỉnh độ lệch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;m_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;v_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật với weight decay tách rời
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Weight decay xảy ra ngoài scale thích nghi
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; 
                               &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Nắm rõ hai bước cập nhật moment trước khi dùng các lớp cài đặt sẵn trong framework.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, tiếng Anh. Giúp phân biệt rõ hai bộ đệm riêng biệt của momentum và RMSprop khi tự cài đặt.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, tiếng Anh. Cách gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;step()&lt;/code&gt; trong PyTorch thay cho đoạn cập nhật viết tay sau khi đã hiểu cơ chế bên trong.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-01-01 Lý thuyết Bộ tối ưu</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_01_01_Optimizer_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_01_01_Optimizer_Theory</id>
   <content type="html">&lt;p&gt;Vào năm 2014, Diederik Kingma và Jimmy Ba công bố bài báo về &lt;strong&gt;Adam&lt;/strong&gt; (&lt;em&gt;Adaptive Moment Estimation&lt;/em&gt;) — một trong những bài báo được trích dẫn nhiều nhất mọi thời đại trong khoa học máy tính (hơn 180.000 lượt trích dẫn). Nhưng để không dùng Adam như một chiếc “hộp đen”, ta cần giải phẫu từng mảnh ghép toán học đã tạo nên nó: từ lực quán tính của Momentum, cú “nhìn trước” của Nesterov, bài toán triệt tiêu tốc độ học của AdaGrad, cách RMSprop sửa lỗi bằng trung bình trượt hàm mũ, cho đến bước hiệu chỉnh độ lệch thiên về 0 ở những vòng lặp đầu tiên.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-toán-học-của-các-bộ-tối-ưu&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột toán học của các Bộ tối ưu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Momentum và Nesterov Accelerated Gradient (NAG)&lt;/strong&gt;:
Momentum cộng dồn vận tốc \(v_t = \beta v_{t-1} + g_t\) (giống hòn bi nặng lăn xuống dốc). Nesterov tinh tế hơn: nó tính gradient tại &lt;strong&gt;vị trí dự đoán phía trước&lt;/strong&gt; \(\theta_{t-1} - \eta \beta v_{t-1}\) để kịp “hãm phanh” khi sắp vượt qua đáy thung lũng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;AdaGrad và điểm yếu tích lũy đơn điệu&lt;/strong&gt;:
AdaGrad cộng dồn toàn bộ bình phương gradient từ bước 1: \(G_t = G_{t-1} + g_t^2\). Rất hay cho đặc trưng thưa (NLP cổ điển, hệ gợi ý), nhưng trong mạng sâu \(G_t\) tăng mãi không giảm khiến tốc độ học hiệu dụng \(\frac{\eta}{\sqrt{G_t} + \epsilon} \to 0\) quá sớm!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;RMSprop — Quên dần quá khứ bằng Trung bình trượt mũ (EMA)&lt;/strong&gt;:
Thay tổng tích lũy bằng \(v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\) (thường \(\beta_2 = 0{,}99\) hoặc \(0{,}999\)) để chỉ đo độ lớn gradient gần đây, giữ tốc độ học không bao giờ bị chết hẳn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adam và Hiệu chỉnh độ lệch (Bias Correction)&lt;/strong&gt;:
Vì \(m_0 = 0\) và \(v_0 = 0\), ở bước \(t = 1\) ta có \(v_1 = (1 - 0{,}999) g_1^2 = 0{,}001 g_1^2\) — nhỏ hơn giá trị thật tới &lt;strong&gt;1.000 lần&lt;/strong&gt;! Chia cho \((1 - \beta_1^t)\) và \((1 - \beta_2^t)\) đưa kỳ vọng ước lượng về đúng không chệch ngay từ bước đầu tiên.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-trọn-vẹn-2-bước-đầu-tiên-của-adam-để-thấy-phép-màu-của-bias-correction&quot;&gt;Giải thích: Tính tay trọn vẹn 2 bước đầu tiên của Adam để thấy phép màu của Bias Correction&lt;/h3&gt;

&lt;p&gt;Cho tham số khởi đầu \(\theta_0 = 1{,}0\), tốc độ học \(\eta = 0{,}1\), các hệ số chuẩn \(\beta_1 = 0{,}9, \; \beta_2 = 0{,}999, \; \epsilon = 10^{-8}\), và giả sử gradient đo được ở hai bước đầu đều là \(g_1 = g_2 = 2{,}0\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước \(t = 1\) (khởi tạo \(m_0 = 0, \; v_0 = 0\))&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Cập nhật moment thô:
\(m_1 = 0{,}9(0) + 0{,}1(2{,}0) = \mathbf{0{,}20}, \qquad v_1 = 0{,}999(0) + 0{,}001(2{,}0^2) = \mathbf{0{,}004}\)&lt;/li&gt;
  &lt;li&gt;Hiệu chỉnh độ lệch (&lt;em&gt;Bias Correction&lt;/em&gt;):
\(\hat{m}_1 = \frac{0{,}20}{1 - 0{,}9^1} = \mathbf{2{,}00}, \qquad \hat{v}_1 = \frac{0{,}004}{1 - 0{,}999^1} = \mathbf{4{,}00}\)&lt;/li&gt;
  &lt;li&gt;Cập nhật tham số:
\(\theta_1 = 1{,}0 - 0{,}1 \cdot \frac{2{,}00}{\sqrt{4{,}00} + 10^{-8}} = 1{,}0 - 0{,}1(1{,}0) = \mathbf{0{,}90}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Thử hình dung nếu BỎ hiệu chỉnh độ lệch ở bước 1&lt;/strong&gt;: bước nhảy sẽ là \(0{,}1 \times \frac{0{,}20}{\sqrt{0{,}004}} \approx 0{,}316\) — vọt gấp &lt;strong&gt;3,16 lần&lt;/strong&gt; tốc độ học \(\eta = 0{,}1\)! Nhờ Bias Correction, bước đầu tiên có biên độ chính xác bằng \(\eta = 0{,}1\), bất kể gradient lớn hay nhỏ!&lt;/p&gt;

&lt;h1 id=&quot;tối-ưu-nâng-cao-vượt-qua-hạ-gradient-thuần-túy&quot;&gt;Tối ưu Nâng cao: Vượt qua Hạ Gradient Thuần túy&lt;/h1&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Dù hạ gradient cung cấp nguyên lý nền tảng để huấn luyện mạng nơ-ron — cập nhật tham số theo hướng làm giảm hàm mất mát — dạng thuần túy của nó tồn tại nhiều hạn chế khiến việc huấn luyện mạng sâu trở nên kém hiệu quả. Trước hết, learning rate phải được điều chỉnh rất cẩn thận: quá lớn sẽ gây dao động hoặc phân kỳ, còn quá nhỏ lại khiến quá trình hội tụ diễn ra rất chậm. Bên cạnh đó, thuật toán áp dụng cùng một learning rate cho mọi tham số, mặc dù các tham số khác nhau thường có thang độ lớn gradient và tần suất cập nhật tối ưu khác nhau. Hạ gradient thuần túy cũng đối xử với mọi hướng trong không gian tham số như nhau, trong khi bề mặt mất mát thường có dạng “hẻm núi” (dốc đứng theo một chiều nhưng rất thoải theo chiều kia), đòi hỏi bước đi khác nhau theo từng phương. Cuối cùng, vì không lưu giữ lịch sử các gradient trước đó, phương pháp này không thể tích lũy động lượng để vượt qua các cực tiểu địa phương nông hoặc điểm yên ngựa.&lt;/p&gt;

&lt;p&gt;Các thuật toán tối ưu nâng cao khắc phục những hạn chế trên thông qua ba cơ chế chính: duy trì động lượng (&lt;em&gt;momentum&lt;/em&gt;) để tăng tốc theo các hướng nhất quán đồng thời hạn chế dao động; điều chỉnh learning rate thích nghi cho từng tham số dựa trên lịch sử gradient, cho phép cập nhật mạnh hơn với các đặc trưng thưa và thận trọng hơn với các đặc trưng có gradient lớn xuất hiện thường xuyên; và khai thác thông tin bậc hai xấp xỉ về độ cong của bề mặt mất mát mà không phải chịu chi phí tính toán quá lớn của việc tính toàn bộ ma trận Hessian. Đây không phải là những tinh chỉnh thứ yếu mà là các kỹ thuật cốt lõi giúp huấn luyện những mô hình ngày càng sâu và lớn — các mô hình ngôn ngữ hiện đại với hàng tỷ tham số khó có thể huấn luyện hiệu quả chỉ bằng hạ gradient thuần túy.&lt;/p&gt;

&lt;p&gt;Hiểu rõ các bộ tối ưu nghĩa là nhận ra chúng không loại trừ lẫn nhau mà phù hợp với từng bối cảnh khác nhau. Stochastic Gradient Descent (SGD) kết hợp momentum hoạt động hiệu quả và ít tốn chi phí tính toán khi bề mặt mất mát có hướng gradient nhất quán, nên thường được dùng trong các bài toán thị giác máy tính với batch size lớn. RMSprop điều chỉnh learning rate dựa trên độ lớn gradient gần đây, đặc biệt hữu ích với mạng hồi quy khi thang gradient thay đổi mạnh qua các bước thời gian. Adam kết hợp cả momentum và learning rate thích nghi, cho hiệu năng mặc định ổn định trên nhiều bài toán và trở thành lựa chọn phổ biến trong thực tế. AdamW cải tiến cách Adam xử lý weight decay, đóng vai trò quan trọng khi huấn luyện các mô hình Transformer lớn. Mỗi bộ tối ưu dựa trên những giả định khác nhau về bề mặt mất mát và động lực gradient; chọn đúng thuật toán có thể quyết định mô hình hội tụ nhanh hay chậm, thậm chí thành công hay thất bại.&lt;/p&gt;

&lt;p&gt;Sự phát triển của các thuật toán tối ưu luôn song hành với tiến hóa kiến trúc mạng nơ-ron. Khi mạng trở nên sâu hơn và đối mặt với hiện tượng gradient biến mất hoặc bùng nổ, các bộ tối ưu được cải tiến để tích lũy động lượng và thích nghi learning rate. Khi mô hình lớn dần và buộc phải huấn luyện với batch nhỏ hơn do giới hạn bộ nhớ, các thuật toán lại cần hoạt động ổn định trước ước lượng gradient nhiễu. Khi phạm vi ứng dụng mở rộng từ thị giác sang xử lý ngôn ngữ tự nhiên (NLP) và học tăng cường, bộ tối ưu ngày càng phải thích nghi tốt hơn với nhiều dạng bề mặt gradient khác nhau. Quá trình đồng tiến hóa này vẫn đang tiếp diễn: kiến trúc mới thường kéo theo nhu cầu về bộ tối ưu mới, và ngược lại.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, dù các thuật toán ngày càng tinh vi, nguyên lý cốt lõi vẫn không đổi: ta vẫn tính gradient thông qua lan truyền ngược và cập nhật tham số ngược hướng gradient. Các bộ tối ưu nâng cao chỉ thay đổi cách xác định kích thước và hướng bước đi bằng cách tận dụng lịch sử và thống kê gradient. Vì vậy, hiểu vững hạ gradient thuần túy là nền tảng để nắm bắt mọi biến thể sau này — nên xem chúng như những cải tiến có chủ đích nhằm xử lý các chế độ thất bại cụ thể hơn là các phương pháp tách biệt hoàn toàn.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Ta sẽ xây dựng cơ sở toán học của các bộ tối ưu nâng cao theo trình tự từ đơn giản đến phức tạp, bắt đầu từ momentum để thấy rõ vai trò của từng thành phần.&lt;/p&gt;

&lt;h3 id=&quot;momentum-tích-lũy-vận-tốc&quot;&gt;Momentum: Tích lũy vận tốc&lt;/h3&gt;

&lt;p&gt;Hạ gradient thuần túy cập nhật tham số chỉ dựa trên gradient tại bước hiện tại:&lt;/p&gt;

\[\theta_t = \theta_{t-1} - \eta \nabla_\theta \mathcal{L}(\theta_{t-1})\]

&lt;p&gt;Momentum bổ sung một biến vận tốc để tích lũy gradient theo thời gian:&lt;/p&gt;

\[\mathbf{v}_t = \beta \mathbf{v}_{t-1} + \nabla_\theta \mathcal{L}(\theta_{t-1})\]

\[\theta_t = \theta_{t-1} - \eta \mathbf{v}_t\]

&lt;p&gt;trong đó \(\beta \in [0, 1)\) là hệ số momentum (thường chọn bằng 0,9). Vận tốc \(\mathbf{v}_t\) là tổng có trọng số giảm dần theo hàm mũ của các gradient. Khai triển đệ quy cho thấy ảnh hưởng của các gradient quá khứ lên bước cập nhật hiện tại:&lt;/p&gt;

\[\mathbf{v}_t = \nabla_\theta \mathcal{L}(\theta_{t-1}) + \beta \nabla_\theta \mathcal{L}(\theta_{t-2}) + \beta^2 \nabla_\theta \mathcal{L}(\theta_{t-3}) + \ldots\]

&lt;p&gt;Gradient gần nhất giữ nguyên trọng số, trong khi các gradient cũ hơn giảm dần theo hệ số \(\beta^k\). Cơ chế này mang lại ba lợi ích chính. Thứ nhất, nếu gradient liên tục cùng chiều, vận tốc sẽ tích lũy và tăng tốc quá trình dịch chuyển — tương tự một quả bóng lăn xuống dốc. Thứ hai, nếu gradient liên tục đổi dấu, các thành phần ngược chiều sẽ triệt tiêu một phần, giúp giảm dao động. Thứ ba, momentum giúp quá trình tối ưu vượt qua các cực tiểu địa phương nông hoặc vùng phẳng nơi gradient hiện tại gần bằng 0 nhưng các gradient trước đó vẫn duy trì hướng đi hợp lý.&lt;/p&gt;

&lt;p&gt;Về mặt hình học, momentum chuyển vai trò của gradient từ bước dịch chuyển trực tiếp sang thành phần cộng vào vận tốc. Dù phép tương tự với cơ học cổ điển không hoàn toàn tuyệt đối, nó phản ánh chính xác tính quán tính: tham số tiếp tục đi theo hướng tốt đã tích lũy ngay cả khi gradient tại một bước riêng lẻ hơi lệch hướng.&lt;/p&gt;

&lt;h3 id=&quot;nesterov-accelerated-gradient-nag&quot;&gt;Nesterov Accelerated Gradient (NAG)&lt;/h3&gt;

&lt;p&gt;NAG là một cải tiến của momentum, trong đó gradient không được tính tại vị trí hiện tại mà tại vị trí dự kiến sau bước trượt theo quán tính:&lt;/p&gt;

\[\mathbf{v}_t = \beta \mathbf{v}_{t-1} + \nabla_\theta \mathcal{L}(\theta_{t-1} - \eta \beta \mathbf{v}_{t-1})\]

\[\theta_t = \theta_{t-1} - \eta \mathbf{v}_t\]

&lt;p&gt;Điểm khác biệt nằm ở số hạng \(\nabla_\theta \mathcal{L}(\theta_{t-1} - \eta \beta \mathbf{v}_{t-1})\) thay cho \(\nabla_\theta \mathcal{L}(\theta_{t-1})\). Ta đánh giá gradient tại điểm mà động lượng sắp đưa tới, rồi dùng thông tin đó để hiệu chỉnh hướng đi. Nhờ cơ chế “nhìn trước” này, nếu quán tính đang đẩy tham số vào vùng có loss tăng, gradient tại vị trí dự kiến sẽ kịp thời phản hồi để giảm tốc hoặc đổi hướng.&lt;/p&gt;

&lt;p&gt;So với momentum chuẩn, NAG thường hội tụ nhanh hơn và ít bị vượt quá điểm cực tiểu hơn. Có thể hình dung momentum chuẩn mang tính phản ứng (điều chỉnh dựa trên vị trí hiện tại), còn NAG mang tính chủ động (dự đoán vị trí kế tiếp để hiệu chỉnh sớm). Trong thực tế, chênh lệch hiệu năng giữa hai phương pháp đôi khi không lớn, nhưng NAG có cơ sở lý thuyết chặt chẽ hơn và thường đem lại cải thiện ổn định.&lt;/p&gt;

&lt;h3 id=&quot;adagrad-learning-rate-thích-nghi&quot;&gt;AdaGrad: Learning Rate thích nghi&lt;/h3&gt;

&lt;p&gt;AdaGrad điều chỉnh learning rate riêng cho từng tham số dựa trên tổng bình phương các gradient đã tích lũy:&lt;/p&gt;

\[\mathbf{G}_t = \mathbf{G}_{t-1} + (\nabla_\theta \mathcal{L}(\theta_{t-1}))^2\]

\[\theta_t = \theta_{t-1} - \frac{\eta}{\sqrt{\mathbf{G}_t + \epsilon}} \odot \nabla_\theta \mathcal{L}(\theta_{t-1})\]

&lt;p&gt;trong đó phép bình phương và căn bậc hai được thực hiện theo từng phần tử, \(\mathbf{G}_t\) lưu tổng bình phương gradient, và \(\epsilon\) (thường là \(10^{-8}\)) giúp tránh chia cho 0. Việc chia cho \(\sqrt{\mathbf{G}_t + \epsilon}\) khiến các tham số có gradient tích lũy lớn nhận bước cập nhật nhỏ hơn, còn các tham số có gradient tích lũy nhỏ nhận bước cập nhật lớn hơn.&lt;/p&gt;

&lt;p&gt;Cơ chế này giải quyết tốt bài toán dữ liệu thưa — chẳng hạn trong NLP, nơi phần lớn từ vựng chỉ xuất hiện rất ít trong tập tài liệu. Với các đặc trưng hiếm gặp, tham số tương ứng ít được cập nhật nên \(\mathbf{G}_t\) nhỏ, giúp chúng nhận bước cập nhật lớn hơn mỗi khi xuất hiện; ngược lại, các đặc trưng phổ biến sẽ nhận bước cập nhật nhỏ và ổn định hơn.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, AdaGrad có nhược điểm lớn khi huấn luyện kéo dài: \(\mathbf{G}_t\) là tổng các số không âm nên chỉ tăng chứ không bao giờ giảm. Theo thời gian, \(\sqrt{\mathbf{G}_t}\) trở nên rất lớn, kéo learning rate hiệu dụng về gần 0 và làm quá trình học dừng lại quá sớm. Điều này có thể chấp nhận được trong tối ưu lồi, nhưng với bề mặt mất mát không lồi của mạng nơ-ron (nhiều cực tiểu địa phương, vùng phẳng và điểm yên ngựa), việc suy giảm bước học quá nhanh sẽ ngăn mô hình thoát khỏi các vùng nghiệm kém.&lt;/p&gt;

&lt;h3 id=&quot;rmsprop-trung-bình-trượt-có-trọng-số-mũ&quot;&gt;RMSprop: Trung bình trượt có trọng số mũ&lt;/h3&gt;

&lt;p&gt;RMSprop khắc phục sự suy giảm quá mức của AdaGrad bằng cách thay tổng tích lũy bằng trung bình trượt có trọng số mũ của bình phương gradient:&lt;/p&gt;

\[\mathbf{E}[g^2]_t = \beta \mathbf{E}[g^2]_{t-1} + (1-\beta)(\nabla_\theta \mathcal{L}(\theta_{t-1}))^2\]

\[\theta_t = \theta_{t-1} - \frac{\eta}{\sqrt{\mathbf{E}[g^2]_t + \epsilon}} \odot \nabla_\theta \mathcal{L}(\theta_{t-1})\]

&lt;p&gt;Với giá trị phổ biến \(\beta = 0.9\), thuật toán xét trọng số chủ yếu trên khoảng \(1/(1-\beta) = 10\) bước cập nhật gần nhất. Nhờ khả năng “quên” các gradient quá cũ, learning rate thích nghi có thể tự điều chỉnh lại khi thang gradient thay đổi qua các vùng khác nhau của bề mặt mất mát. RMSprop đặc biệt hữu ích khi huấn luyện mạng hồi quy (RNN), nơi độ lớn gradient biến thiên mạnh, và vẫn là lựa chọn tốt khi phân phối thống kê của gradient thay đổi trong suốt quá trình huấn luyện.&lt;/p&gt;

&lt;h3 id=&quot;adam-ước-lượng-moment-thích-nghi&quot;&gt;Adam: Ước lượng Moment thích nghi&lt;/h3&gt;

&lt;p&gt;Adam kết hợp ý tưởng momentum và learning rate thích nghi của RMSprop bằng cách duy trì đồng thời ước lượng moment bậc nhất (trung bình) và moment bậc hai (phương sai chưa trừ trung bình) của gradient:&lt;/p&gt;

&lt;p&gt;\(\mathbf{m}_t = \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \nabla_\theta \mathcal{L}(\theta_{t-1})\) (thành phần momentum)&lt;/p&gt;

&lt;p&gt;\(\mathbf{v}_t = \beta_2 \mathbf{v}_{t-1} + (1-\beta_2) (\nabla_\theta \mathcal{L}(\theta_{t-1}))^2\) (thành phần RMSprop)&lt;/p&gt;

&lt;p&gt;Vì khởi tạo \(\mathbf{m}_0 = \mathbf{v}_0 = 0\), hai ước lượng này ban đầu bị lệch về 0. Adam khắc phục bằng bước hiệu chỉnh độ lệch (&lt;em&gt;bias correction&lt;/em&gt;):&lt;/p&gt;

\[\hat{\mathbf{m}}_t = \frac{\mathbf{m}_t}{1-\beta_1^t}, \quad \hat{\mathbf{v}}_t = \frac{\mathbf{v}_t}{1-\beta_2^t}\]

&lt;p&gt;Quy tắc cập nhật tham số kết hợp cả hai ước lượng đã hiệu chỉnh:&lt;/p&gt;

\[\theta_t = \theta_{t-1} - \frac{\eta}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon} \odot \hat{\mathbf{m}}_t\]

&lt;p&gt;Các siêu tham số mặc định \(\beta_1 = 0.9, \beta_2 = 0.999, \epsilon = 10^{-8}\) hoạt động ổn định trên nhiều bài toán, khiến Adam trở thành bộ tối ưu được ưa chuộng vì ít đòi hỏi tinh chỉnh. Thuật toán vừa thích nghi theo thang độ lớn gradient (qua \(\mathbf{v}_t\)), vừa duy trì động lượng (qua \(\mathbf{m}_t\)).&lt;/p&gt;

&lt;p&gt;Cơ chế hiệu chỉnh độ lệch có vai trò rất cụ thể ở giai đoạn đầu huấn luyện. Do khởi tạo bằng 0, tại bước đầu tiên ta có \(\mathbf{m}_1 = (1-\beta_1)g_1\), nhỏ hơn nhiều so với kỳ vọng thật \(\mathbb{E}[g]\) khi \(\beta_1 = 0.9\). Phép chia cho \(1-\beta_1^t\) đưa ước lượng về đúng thang: \(\hat{\mathbf{m}}_1 = \frac{(1-\beta_1)g_1}{1-\beta_1} = g_1\). Khi \(t \to \infty\), \(\beta_1^t \to 0\) nên mẫu số tiến về 1 và phép hiệu chỉnh tự động mờ dần, giúp thuật toán ổn định ngay từ bước đầu tiên mà không ảnh hưởng đến hành vi tiệm cận.&lt;/p&gt;

&lt;h3 id=&quot;adamw-weight-decay-tách-rời&quot;&gt;AdamW: Weight Decay tách rời&lt;/h3&gt;

&lt;p&gt;Một điểm tinh tế ở Adam chuẩn là cách xử lý chính quy hóa L2 (weight decay). Thông thường, weight decay được thêm trực tiếp vào gradient:&lt;/p&gt;

\[\nabla \mathcal{L}_{\text{reg}} = \nabla \mathcal{L} + \lambda \theta\]

&lt;p&gt;Tuy nhiên, trong Adam, thành phần này sau đó lại đi qua phép chia cho \(\sqrt{\hat{\mathbf{v}}_t} + \epsilon\), làm cường độ chính quy hóa bị biến dạng theo thang gradient của từng tham số. AdamW giải quyết bằng cách tách weight decay ra khỏi bước cập nhật thích nghi dựa trên gradient:&lt;/p&gt;

\[\mathbf{m}_t = \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \nabla_\theta \mathcal{L}(\theta_{t-1})\]

\[\mathbf{v}_t = \beta_2 \mathbf{v}_{t-1} + (1-\beta_2) (\nabla_\theta \mathcal{L}(\theta_{t-1}))^2\]

\[\theta_t = \theta_{t-1} - \eta \left(\frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon} + \lambda \theta_{t-1}\right)\]

&lt;p&gt;Số hạng weight decay \(\lambda \theta_{t-1}\) được áp dụng độc lập sau bước chuẩn hóa thích nghi, giúp cường độ suy giảm trọng số đồng đều hơn và không phụ thuộc vào thống kê gradient. Thay đổi nhỏ này cải thiện rõ rệt khả năng tổng quát hóa, đặc biệt trên Transformer và các mô hình quy mô lớn.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;p&gt;Để hình dung sự khác biệt giữa các bộ tối ưu, hãy xét một bề mặt mất mát 2D có dạng hẻm núi: hai sườn rất dốc (độ cong cao) nhưng đáy hẻm lại thoải (độ cong thấp), với điểm cực tiểu nằm sâu dọc theo đáy hẻm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hạ Gradient Thuần túy:&lt;/strong&gt; Gradient luôn vuông góc với các đường đồng mức của hàm mất mát. Trong hẻm núi, gradient chủ yếu hướng thẳng về hai sườn dốc và chỉ có thành phần rất nhỏ dọc theo đáy hẻm. Do đó, thuật toán liên tục nhảy qua lại giữa hai sườn và nhích rất chậm về phía cực tiểu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SGD với Momentum:&lt;/strong&gt; Các thành phần gradient cùng chiều dọc theo đáy hẻm cộng dồn thành vận tốc lớn, trong khi các thành phần đổi dấu liên tục giữa hai sườn dốc tự triệt tiêu lẫn nhau. Nhờ vậy, quỹ đạo tăng tốc dọc theo đáy hẻm và giảm hẳn dao động ngang. Tương tự quả bóng lăn xuống dốc, quán tính cũng giúp quá trình tối ưu băng qua các vùng phẳng hoặc vùng lõm nông.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AdaGrad / RMSprop:&lt;/strong&gt; Thuật toán nhận thấy gradient theo phương dốc luôn lớn còn theo phương thoải luôn nhỏ, từ đó tự động giảm bước học theo phương dốc (hạn chế dao động) và giữ bước học lớn hơn theo phương thoải (tăng tốc tiến về cực tiểu). Việc tự cân bằng theo độ cong từng chiều giúp đường đi hiệu quả hơn nhiều so với dùng một learning rate duy nhất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adam:&lt;/strong&gt; Kết hợp cả hai lợi thế trên — momentum tăng tốc dọc theo đáy hẻm còn learning rate thích nghi triệt tiêu dao động ngang. Ngoài ra, khi tiến dần từ vùng xa cực tiểu (gradient lớn) về gần cực tiểu (gradient nhỏ), cơ chế thích nghi tự động điều chỉnh thang bước cập nhật tương ứng.&lt;/p&gt;

&lt;p&gt;Xét thêm một tình huống thực tế: huấn luyện mạng nơ-ron trên tập dữ liệu có những đặc trưng hiếm nhưng mang thông tin quan trọng. SGD thuần túy dùng chung một learning rate nên các tham số gắn với đặc trưng hiếm được cập nhật rất ít và học chậm. Trong khi đó, AdaGrad và Adam cấp cho các tham số này learning rate hiệu dụng lớn hơn (do \(\mathbf{v}_t\) tích lũy nhỏ), giúp chúng học nhanh từ số ít mẫu xuất hiện; còn các đặc trưng phổ biến nhận learning rate hiệu dụng nhỏ hơn để tránh phản ứng quá mạnh trước từng mẫu riêng lẻ. Đây là lý do Adam thường hội tụ nhanh hơn SGD trong các bài toán NLP có từ vựng thưa.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, tiếng Anh. Giải thích cách mỗi thuật toán lấy trung bình các gradient quá khứ, bám sát phần lý thuyết của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Ôn lại bước cập nhật cơ bản trước khi bổ sung trung bình hóa và moment.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, tiếng Anh. Trực giác hình học về việc tối thiểu hóa hàm chi phí trước khi đi vào các thuật toán theo dõi moment.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10 Thuật toán Học sâu</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter10/10_00_Introduction</id>
   <content type="html">&lt;p&gt;Hãy hình dung bề mặt hàm mất mát của một mạng neuron 100 triệu tham số không phải là một chiếc bát trơn nhẵn, mà là một dãy núi hiểm trở có vô số &lt;strong&gt;hẻm núi hẹp dốc đứng hai bên nhưng thoai thoải dọc theo đáy&lt;/strong&gt;, xen lẫn hàng triệu &lt;strong&gt;điểm yên ngựa (saddle points)&lt;/strong&gt; phẳng lỳ. Nếu thả thuật toán Hạ Gradient thuần túy (Vanilla SGD) vào địa hình đó, nó sẽ nảy zíc-zắc liên tục giữa hai vách núi mà gần như không nhích về phía đích. Chương này mở ra hộp công cụ các &lt;strong&gt;bộ tối ưu nâng cao&lt;/strong&gt; giúp mô hình băng qua địa hình đó nhanh hơn hàng chục lần.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-thuật-toán-tối-ưu-hiện-đại&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Thuật toán Tối ưu Hiện đại&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Vấn đề điều kiện xấu (Ill-Conditioning) và Điểm yên ngựa&lt;/strong&gt;:
Khi độ cong (giá trị riêng Hessian) theo các trục chênh lệch hàng trăm lần, một tốc độ học cố định duy nhất hoặc quá lớn cho trục dốc (gây dao động phân kỳ), hoặc quá nhỏ cho trục phẳng (đi chậm như rùa).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhánh Quán tính (Momentum &amp;amp; Nesterov)&lt;/strong&gt;:
Tích lũy “vận tốc” từ các gradient quá khứ để triệt tiêu dao động vuông góc giữa hai vách hẻm núi và cộng hưởng tăng tốc dọc theo hướng đáy thung lũng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhánh Tốc độ học Thích nghi (AdaGrad, RMSprop)&lt;/strong&gt;:
Tự động cấp &lt;strong&gt;tốc độ học riêng cho từng tham số&lt;/strong&gt; bằng cách chia gradient cho căn bậc hai của tổng bình phương gradient quá khứ — giảm bước cho trục dốc, phóng đại bước cho trục phẳng/thưa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hợp nhất trong Adam và AdamW&lt;/strong&gt;:
Kết hợp cả moment bậc 1 (quán tính) lẫn moment bậc 2 (tốc độ học thích nghi) kèm hiệu chỉnh độ lệch (&lt;em&gt;bias correction&lt;/em&gt;) và phân rã trọng số tách rời (&lt;em&gt;decoupled weight decay&lt;/em&gt;) — bộ tối ưu mặc định của phần lớn Deep Learning hiện đại.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-minh-họa-bằng-số-hiện-tượng-nảy-zíc-zắc-của-sgd-trong-hẻm-núi-hẹp&quot;&gt;Giải thích: Minh họa bằng số hiện tượng nảy zíc-zắc của SGD trong hẻm núi hẹp&lt;/h3&gt;

&lt;p&gt;Xét hàm mất mát dạng thung lũng hẹp (tỷ lệ độ cong \(20 : 1\)): \(f(x, y) = 0{,}5 x^2 + 10 y^2\) (cực tiểu tại \((0, 0)\)), bắt đầu tại \((x_0, y_0) = (10, \; 1)\) với tốc độ học \(\eta = 0{,}09\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Gradient tại \((x, y)\) là \(\nabla f = (x, \; 20y)\).&lt;/li&gt;
  &lt;li&gt;Sau bước 1 của SGD thuần:
    &lt;ul&gt;
      &lt;li&gt;\(x_1 = 10 - 0{,}09(10) = \mathbf{9{,}10}\) (tiến về 0 rất chậm, chỉ giảm 9%).&lt;/li&gt;
      &lt;li&gt;\(y_1 = 1 - 0{,}09(20 \times 1) = 1 - 1{,}8 = \mathbf{-0{,}80}\) (bắn vọt sang hẳn vách đối diện!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Sau bước 2:
    &lt;ul&gt;
      &lt;li&gt;\(x_2 = 9{,}10(0{,}91) = \mathbf{8{,}28}\).&lt;/li&gt;
      &lt;li&gt;\(y_2 = -0{,}80 - 0{,}09(-16) = \mathbf{+0{,}64}\) (lại bật ngược sang vách bên kia!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Nếu ta cố tăng \(\eta\) lên \(0{,}11\) để trục \(x\) đi nhanh hơn, trục \(y\) lập tức nổ tung ($$&lt;/td&gt;
      &lt;td&gt;1 - 20\eta&lt;/td&gt;
      &lt;td&gt;= 1{,}2 &amp;gt; 1$$)! Đó chính là lý do ta cần Momentum và Adam.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Các thuật toán tối ưu nâng cao giúp tăng tốc độ huấn luyện và cải thiện khả năng hội tụ của mạng nơ-ron. Chương này trình bày các phương pháp momentum, RMSprop, Adam, AdamW và lịch trình điều chỉnh learning rate. Nắm vững các bộ tối ưu này là nền tảng quan trọng để huấn luyện mạng nơ-ron sâu ổn định và hiệu quả.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau khi tìm hiểu Adam và AdamW, bạn có thể xem &lt;strong&gt;10-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; để biết thêm về Lion, Sophia, Muon và huấn luyện không cần lịch trình learning rate tường minh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (luyện phỏng vấn):&lt;/strong&gt; Sau phần lý thuyết về bộ tối ưu, xem &lt;strong&gt;10-98 Luyện phỏng vấn&lt;/strong&gt; với các câu hỏi tự soạn về Adam, momentum và warmup; bộ câu hỏi kèm lời giải tham khảo thêm là &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hub LLM:&lt;/strong&gt; Danh sách kiểm tra các nhóm tham số nên áp dụng weight decay của AdamW trong mô hình ngôn ngữ dạng decoder nằm ở &lt;strong&gt;26-01&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Giới thiệu Adam, bộ tối ưu trọng tâm của chương này.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, tiếng Anh. So sánh trực quan giữa Momentum, RMSprop, AdaGrad và Adam.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Trình bày hạ gradient thuần túy, điểm xuất phát mà các phương pháp sau này cải tiến.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Nếu thập niên 2010 là sân khấu của Dropout và BatchNorm, thì giai đoạn 2022–2026 chứng kiến sự dịch chuyển ngoạn mục trong cách chính quy hóa các mô hình khổng lồ: Vision Transformer thay Dropout bằng &lt;strong&gt;Stochastic Depth (DropPath)&lt;/strong&gt;, các mô hình LLM nghìn tỷ token gần như &lt;strong&gt;tắt hẳn Dropout&lt;/strong&gt; để tận dụng dữ liệu khổng lồ kết hợp &lt;strong&gt;RMSNorm + Weight Decay tách rời&lt;/strong&gt;, còn giới tối ưu hóa đón nhận &lt;strong&gt;SAM (Sharpness-Aware Minimization)&lt;/strong&gt; để chủ động săn lùng các vùng cực tiểu phẳng!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-xu-hướng-chính-quy-hóa-hiện-đại-20222026&quot;&gt;Kiến thức cần nhớ: Bốn xu hướng Chính quy hóa Hiện đại (2022–2026)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sharpness-Aware Minimization (SAM)&lt;/strong&gt;:
Thay vì chỉ tìm điểm \(w\) có mất mát thấp, SAM tìm điểm \(w\) sao cho &lt;strong&gt;cả vùng lân cận bán kính \(\rho\)&lt;/strong&gt; quanh nó đều có mất mát thấp: \(\min_w \max_{\|\epsilon\|_2 \le \rho} \mathcal{L}(w + \epsilon)\). Cực tiểu phẳng (&lt;em&gt;flat minima&lt;/em&gt;) tổng quát hóa tốt hơn hẳn cực tiểu nhọn (&lt;em&gt;sharp minima&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stochastic Depth / DropPath&lt;/strong&gt;:
Thay vì tắt từng neuron rời rạc như Dropout, DropPath tắt ngẫu nhiên &lt;strong&gt;cả một nhánh khối Residual&lt;/strong&gt; (\(y = x + \text{DropPath}(F(x))\)) theo tỷ lệ tăng dần theo chiều sâu — chuẩn mực bắt buộc khi huấn luyện ViT, Swin Transformer và ConvNeXt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Công thức chính quy hóa của LLM hiện đại (Pre-training vs. Fine-tuning)&lt;/strong&gt;:
Khi tiền huấn luyện trên hàng nghìn tỷ token (mỗi văn bản chỉ đi qua 1 lần — 1 epoch), bản thân dữ liệu khổng lồ đã ngăn overfitting nên hầu hết LLM lớn (Llama 3, Qwen, DeepSeek) đặt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dropout = 0.0&lt;/code&gt; và dựa vào &lt;strong&gt;decoupled weight decay (AdamW)&lt;/strong&gt;, gradient clipping và z-loss; chỉ bật lại Dropout nhẹ khi tinh chỉnh (LoRA/SFT) trên tập nhỏ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa ổn định ở quy mô lớn (RMSNorm &amp;amp; QK-Norm)&lt;/strong&gt;:
Bên cạnh RMSNorm thay LayerNorm, nhiều mô hình đa phương thức và LLM mới áp dụng thêm &lt;strong&gt;QK-Norm&lt;/strong&gt; (chuẩn hóa riêng Query và Key trước khi nhân \(Q K^T\)) để dập tắt hoàn toàn các đột biến &lt;em&gt;loss spike&lt;/em&gt; khi huấn luyện FP16/BF16 sâu hàng trăm tầng.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-2-bước-cập-nhật-của-thuật-toán-sam-sharpness-aware-minimization&quot;&gt;Giải thích: Tính tay 2 bước cập nhật của thuật toán SAM (Sharpness-Aware Minimization)&lt;/h3&gt;

&lt;p&gt;Xét hàm mất mát 1 chiều \(\mathcal{L}(w) = (w - 1)^2\) tại điểm hiện tại \(w = 2{,}0\), bán kính nhiễu SAM \(\rho = 0{,}5\) và tốc độ học \(\eta = 0{,}2\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Leo lên đỉnh xấu nhất trong bán kính \(\rho\) (Ascent Step)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Gradient tại \(w = 2{,}0\): \(g = \mathcal{L}&apos;(2{,}0) = 2(2{,}0 - 1) = \mathbf{2{,}0}\).&lt;/li&gt;
      &lt;li&gt;
        &lt;table&gt;
          &lt;tbody&gt;
            &lt;tr&gt;
              &lt;td&gt;Vector nhiễu hướng xấu nhất: $$\hat{\epsilon} = \rho \frac{g}{&lt;/td&gt;
              &lt;td&gt;g&lt;/td&gt;
              &lt;td&gt;} = 0{,}5 \times \frac{2{,}0}{2{,}0} = \mathbf{+0{,}5}$$.&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/li&gt;
      &lt;li&gt;Điểm bị nhiễu: \(w_{\text{adv}} = w + \hat{\epsilon} = 2{,}0 + 0{,}5 = \mathbf{2{,}5}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Tính gradient tại điểm xấu nhất \(w_{\text{adv}}\), rồi cập nhật cho điểm gốc \(w\) (Descent Step)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Gradient tại \(w_{\text{adv}} = 2{,}5\): \(g_{\text{adv}} = \mathcal{L}&apos;(2{,}5) = 2(2{,}5 - 1) = \mathbf{3{,}0}\).&lt;/li&gt;
      &lt;li&gt;Cập nhật \(w\): \(w_{\text{new}} = w - \eta g_{\text{adv}} = 2{,}0 - 0{,}2(3{,}0) = \mathbf{1{,}40}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So với SGD thường (\(w_{\text{new}} = 2{,}0 - 0{,}2(2{,}0) = 1{,}60\)), SAM “nhìn trước” độ dốc ở lân cận \(w + \hat{\epsilon}\) nên đẩy mạnh hơn khỏi các thung lũng hẹp có độ cong lớn — đánh đổi là tốn &lt;strong&gt;gấp 2 lần&lt;/strong&gt; lượt forward/backward mỗi bước!&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-chính-quy-hóa-hiện-đại--sam-droppath-và-công-thức-huấn-luyện-llm&quot;&gt;Tùy chọn: Chính quy hóa hiện đại — SAM, DropPath và công thức huấn luyện LLM&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết về dropout hay BatchNorm. Nội dung tổng hợp các kỹ thuật chính quy hóa thường xuất hiện trong quy trình huấn luyện giai đoạn 2022–2026.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Công thức inverted dropout:&lt;/p&gt;

\[\tilde{\mathbf{h}} = \frac{\mathbf{m} \odot \mathbf{h}}{1-p}, \quad m_i \sim \mathrm{Bernoulli}(1-p)\]

&lt;p&gt;vẫn là mô hình tư duy nền tảng. Tuy nhiên, trong các kiến trúc Transformer và mạng thị giác lớn, thực hành hiện đại thường ưu tiên bỏ ngẫu nhiên &lt;strong&gt;nhánh phần dư&lt;/strong&gt; (&lt;em&gt;stochastic depth&lt;/em&gt; / DropPath) thay vì từng neuron riêng lẻ, đồng thời dựa nhiều hơn vào &lt;strong&gt;weight decay kết hợp quy mô dữ liệu&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;1-sharpness-aware-minimization-sam&quot;&gt;1. Sharpness-Aware Minimization (SAM)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2010.01412&quot;&gt;Foret et al., 2021&lt;/a&gt; đề xuất SAM (được ứng dụng rộng rãi trong thị giác máy tính từ sau năm 2022) nhằm tìm bộ tham số nằm trong vùng cực tiểu phẳng, vẫn đạt mất mát thấp trên cả một lân cận:&lt;/p&gt;

\[\min_\theta \max_{\|\boldsymbol{\varepsilon}\|_2 \le \rho} \mathcal{L}(\theta + \boldsymbol{\varepsilon}).\]

&lt;p&gt;Trong thực tế, mỗi bước cập nhật cần hai lượt truyền xuôi–ngược: trước hết dịch tới điểm xấu nhất trong lân cận \(\theta + \rho \frac{\nabla \mathcal{L}}{\|\nabla \mathcal{L}\|}\), sau đó dùng gradient tại điểm đó để cập nhật tham số gốc. Đây là cách chính quy hóa trực tiếp &lt;strong&gt;quỹ đạo tối ưu&lt;/strong&gt;, bổ trợ cho nhiễu kích hoạt kiểu dropout.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-thực-tế-tiêu-biểu&quot;&gt;2. Ứng dụng thực tế tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;stochastic-depth-và-droppath&quot;&gt;Stochastic Depth và DropPath&lt;/h3&gt;

&lt;p&gt;Các cấu hình huấn luyện tiêu biểu của ConvNeXt và ViT (như mặc định trong thư viện &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timm&lt;/code&gt; giai đoạn 2022–2026) thường ngẫu nhiên bỏ qua toàn bộ một khối phần dư trong quá trình huấn luyện. Thay vì vô hiệu hóa từng đơn vị ẩn, kỹ thuật này hoạt động như dropout theo &lt;strong&gt;đường dẫn&lt;/strong&gt;, tạo hiệu ứng tổ hợp ẩn của các mạng có độ sâu khác nhau.&lt;/p&gt;

&lt;h3 id=&quot;cách-các-mô-hình-ngôn-ngữ-lớn-llm-chính-quy-hóa&quot;&gt;Cách các mô hình ngôn ngữ lớn (LLM) chính quy hóa&lt;/h3&gt;

&lt;p&gt;Quy trình tiền huấn luyện kiểu LLaMA chủ yếu dựa vào &lt;strong&gt;weight decay&lt;/strong&gt; (với AdamW), hầu như không dùng dropout ở cấp độ token hoặc chỉ dùng tỷ lệ rất nhỏ trên các mô hình cỡ nhỏ. Ở quy mô từ 7 tỷ tham số trở lên, yếu tố kiểm soát tổng quát hóa quan trọng nhất là &lt;strong&gt;tổ hợp dữ liệu huấn luyện, đóng gói chuỗi (packing) và weight decay&lt;/strong&gt;, theo sau bởi giai đoạn căn chỉnh RLHF/DPO (Chương 21) — khác hẳn mức dropout \(p=0.5\) quen thuộc ở các bài tập MLP cổ điển.&lt;/p&gt;

&lt;h3 id=&quot;các-biến-thể-chuẩn-hóa&quot;&gt;Các biến thể chuẩn hóa&lt;/h3&gt;

&lt;p&gt;LayerNorm và RMSNorm thay thế BatchNorm trong hầu hết mô hình chuỗi hiện đại. Kết hợp giữa kết nối phần dư và chuẩn hóa lớp giúp giữ ổn định thang kích hoạt để mô hình có thể huấn luyện sâu và dài mà không bị phân kỳ.&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-mã-nguồn-phổ-biến&quot;&gt;3. Thư viện và mã nguồn phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DropPath&lt;/code&gt; trong thư viện &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timm&lt;/code&gt;, cùng các cài đặt SAM trong &lt;a href=&quot;https://github.com/jettify/pytorch-optimizer&quot;&gt;pytorch-optimizer&lt;/a&gt; và &lt;a href=&quot;https://github.com/davda54/sam&quot;&gt;sam&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.optim.AdamW&lt;/code&gt; với tham số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_decay&lt;/code&gt; trong PyTorch (xem thêm Chương 10).&lt;/li&gt;
  &lt;li&gt;Các công thức huấn luyện mặc định của Hugging Face (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Trainer&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trl&lt;/code&gt;) thường ưu tiên weight decay và dùng rất ít hidden dropout.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2010.01412&quot;&gt;SAM (Foret et al., 2021)&lt;/a&gt; — mục tiêu tối ưu vùng phẳng được áp dụng rộng rãi trong thị giác máy tính.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2201.03545&quot;&gt;ConvNeXt (Liu et al., 2022)&lt;/a&gt; — sử dụng stochastic depth như thành phần tiêu chuẩn trong cấu hình huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1711.05101&quot;&gt;AdamW (Loshchilov &amp;amp; Hutter, 2019)&lt;/a&gt; — tách riêng weight decay khỏi bước cập nhật thích nghi, vẫn là bộ tối ưu mặc định cho LLM.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-vai-trò-bổ-trợ-cho-nội-dung-cốt-lõi&quot;&gt;5. Vai trò bổ trợ cho nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên nắm vững cơ chế inverted dropout và vị trí đặt BatchNorm trong phần cốt lõi trước. Bài đọc thêm này cập nhật thêm &lt;strong&gt;SAM&lt;/strong&gt; và &lt;strong&gt;DropPath&lt;/strong&gt;, đồng thời làm rõ sự dịch chuyển của các mô hình nền tảng rời xa dropout nặng trên từng đơn vị ẩn.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=k6-jJ58MFKU&quot;&gt;Sharpness-Aware Minimization (SAM) in 7 minutes&lt;/a&gt; — Yuxiang “Shawn” Wang (tiếng Anh). Giới thiệu ngắn gọn phương pháp SAM giúp tìm cực tiểu phẳng và cải thiện khả năng tổng quát hóa.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=DEMmkFC6IGM&quot;&gt;Overfitting in a Neural Network explained&lt;/a&gt; — deeplizard (tiếng Anh). Ôn lại vấn đề quá khớp mà SAM và DropPath tiếp tục giải quyết.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Kết nối góc nhìn độ sắc của cực tiểu với khung lý thuyết bias–variance quen thuộc.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-98 Luyện phỏng vấn (overfitting và chính quy)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Trong các buổi phỏng vấn kỹ sư AI, chủ đề &lt;strong&gt;quá khớp (overfitting) và chính quy hóa&lt;/strong&gt; là phép thử nhanh nhất để phân biệt người chỉ biết gọi thư viện với người thực sự hiểu toán học huấn luyện. Chỉ cần một câu hỏi như &lt;em&gt;“Tại sao phạt \(L_1\) tạo ra trọng số bằng đúng 0 còn \(L_2\) thì không?”&lt;/em&gt; hay &lt;em&gt;“Điều gì xảy ra nếu bạn quên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; trên mạng có cả Dropout và BatchNorm?”&lt;/em&gt;, người phỏng vấn sẽ đánh giá ngay độ sâu tư duy của bạn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nhóm-câu-hỏi-phỏng-vấn-kinh-điển-về-chính-quy-hóa&quot;&gt;Kiến thức cần nhớ: Bốn nhóm câu hỏi phỏng vấn kinh điển về Chính quy hóa&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán đường cong học tập (Learning Curves)&lt;/strong&gt;:
Phân biệt rõ &lt;em&gt;overfitting&lt;/em&gt; (train loss giảm sâu, val loss quay đầu tăng), &lt;em&gt;underfitting&lt;/em&gt; (cả hai đều cao) và &lt;em&gt;data leakage/distribution shift&lt;/em&gt;, cùng thứ tự ưu tiên xử lý (thêm dữ liệu/augmentation \(\to\) giảm độ phức tạp/tăng regularization \(\to\) chỉnh early stopping).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hình học của \(L_1\) (Lasso) vs. \(L_2\) (Ridge / Weight Decay)&lt;/strong&gt;:
Đạo hàm của \(\lambda |w|\) có độ lớn hằng số \(\lambda\) kéo thẳng các trọng số nhỏ về đúng \(0\) (tạo độ thưa — sparsity); trong khi đạo hàm của \(\frac{\lambda}{2} w^2\) là \(\lambda w\) giảm dần khi \(w\) nhỏ nên chỉ nén trọng số về gần 0 chứ hiếm khi triệt tiêu tuyệt đối.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế Train vs. Eval của Dropout và BatchNorm&lt;/strong&gt;:
Nêu rõ cả hai điểm: Dropout tắt mặt nạ ngẫu nhiên và bỏ hệ số \(1/(1-p)\); BatchNorm chuyển từ thống kê mini-batch sang &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;running_mean&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;running_var&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Data Augmentation và Implicit Regularization&lt;/strong&gt;:
Giải thích vì sao cắt xoay ảnh, Mixup, hay ngay cả nhiễu ngẫu nhiên của Mini-batch SGD cũng đóng vai trò chính quy hóa mạnh mẽ bằng cách ép mô hình bất biến theo phép biến đổi và tìm vùng cực tiểu phẳng.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-bằng-số-bước-co-trọng-số-của-l_1-và-l_2-khi-trọng-số-đã-nhỏ-w--005&quot;&gt;Giải thích: So sánh bằng số bước co trọng số của \(L_1\) và \(L_2\) khi trọng số đã nhỏ (\(w = 0{,}05\))&lt;/h3&gt;

&lt;p&gt;Giả sử đạo hàm từ dữ liệu bằng \(0\) (trọng số này không giúp giảm loss), ta xét lực kéo về 0 của \(L_1\) và \(L_2\) với cùng \(\lambda = 0{,}1\) và \(\eta = 0{,}5\) tại \(w = 0{,}05\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Loại phạt&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Công thức lực kéo (gradient phạt)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Độ lớn bước kéo \(\eta \cdot \text{grad}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Giá trị \(w_{\text{new}}\) sau 1 bước&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hệ quả hình học&lt;/th&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt; &lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Phạt \(L_2\)&lt;/strong&gt; (\(\frac{\lambda}{2}w^2\))&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\lambda w = 0{,}1(0{,}05) = 0{,}005\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}0025\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}05 - 0{,}0025 = \mathbf{0{,}0475}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Lực kéo yếu dần theo \(w\) \(\to\) chỉ tiệm cận 0&lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
      &lt;td&gt; &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Phạt \(L_1\)&lt;/strong&gt; ($$\lambda&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;w&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;$$)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\lambda \operatorname{sign}(w) = 0{,}1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0{,}0500\)&lt;/td&gt;
      &lt;td&gt;\(0{,}05 - 0{,}05 = \mathbf{0{,}0000}\)&lt;/td&gt;
      &lt;td&gt;Lực kéo không đổi \(\to\) chạm chính xác &lt;strong&gt;0&lt;/strong&gt; (thưa!)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ bằng 2 dòng tính tay như vậy trong buổi phỏng vấn, bạn đã giải thích trọn vẹn bản chất toán học của độ thưa \(L_1\) mà không cần vẽ hình phức tạp!&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-luyện-phỏng-vấn--quá-khớp-và-chính-quy-hóa&quot;&gt;Tùy chọn: Luyện phỏng vấn — Quá khớp và chính quy hóa&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế các bài lý thuyết về dropout, BatchNorm hay các kỹ thuật chính quy hóa khác. Sau khi học xong phần cốt lõi, hãy dùng các câu hỏi dưới đây để tự kiểm tra, đồng thời tham khảo thêm bộ câu hỏi có lời giải trong &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Chủ đề tương ứng trong sách (đọc trong bản PDF):&lt;/strong&gt; quá khớp và tổng quát hóa, đánh giá kiểm định (validation) và các kỹ thuật kiểm soát dung lượng mô hình.&lt;/p&gt;

&lt;p&gt;Trang tổng hợp lộ trình: &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;bộ-câu-hỏi-tự-luyện&quot;&gt;Bộ câu hỏi tự luyện&lt;/h2&gt;

&lt;h3 id=&quot;q1-mất-mát-huấn-luyện-giảm-nhưng-mất-mát-kiểm-định-tăng&quot;&gt;Q1. Mất mát huấn luyện giảm nhưng mất mát kiểm định tăng&lt;/h3&gt;

&lt;p&gt;Giá trị cross-entropy trên tập huấn luyện vẫn tiếp tục giảm sau epoch 40, trong khi trên tập kiểm định lại bắt đầu tăng từ epoch 25. Hãy nêu hai biện pháp can thiệp &lt;em&gt;khác nhau&lt;/em&gt; (không phải “tăng thêm GPU”) và phân tích giả định đằng sau mỗi cách.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý:&lt;/strong&gt; Một hướng thay đổi không gian giả thuyết hoặc hàm mục tiêu hiệu dụng; hướng còn lại điều chỉnh &lt;em&gt;thời điểm&lt;/em&gt; dừng huấn luyện.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận:&lt;/strong&gt; (1) Tăng cường chính quy hóa (tăng weight decay, bổ sung dropout hoặc data augmentation) dựa trên giả định mô hình có đủ khả năng khớp tập huấn luyện nhưng đang quá linh hoạt so với dữ liệu. (2) Áp dụng dừng sớm (&lt;em&gt;early stopping&lt;/em&gt;) và chọn checkpoint tốt nhất trên tập kiểm định hợp lệ dựa trên giả định mô hình đã đi qua điểm tổng quát hóa tối ưu. Ngoài ra, thu thập thêm dữ liệu gán nhãn giúp thu hẹp khoảng cách từ phía cỡ mẫu, còn thu nhỏ kiến trúc mạng là thay đổi trực tiếp dung lượng thay vì chính quy hóa trong quá trình huấn luyện.&lt;/p&gt;

&lt;h3 id=&quot;q2-so-sánh-chính-quy-hóa-l2-và-l1-trên-tầng-tuyến-tính&quot;&gt;Q2. So sánh chính quy hóa L2 và L1 trên tầng tuyến tính&lt;/h3&gt;

&lt;p&gt;Với một tầng tuyến tính, so sánh việc cộng thêm \(\frac{\lambda}{2}\|\mathbf{w}\|_2^2\) và \(\lambda\|\mathbf{w}\|_1\) vào hàm mất mát. Dạng nào dễ đẩy trọng số về &lt;em&gt;đúng&lt;/em&gt; bằng 0 hơn, và vì sao điều đó mới chỉ là một phần câu chuyện trong mạng ReLU sâu?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý:&lt;/strong&gt; Đạo hàm dưới (&lt;em&gt;subgradient&lt;/em&gt;) của L1 chứa một đoạn tại 0, còn gradient của L2 tỷ lệ tuyến tính với \(\mathbf{w}\) nên thu nhỏ dần nhưng hiếm khi chạm đúng 0 trong SGD.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận:&lt;/strong&gt; Chính quy hóa L1 (tương tự Lasso) tạo nghiệm thưa với nhiều trọng số bằng đúng 0, trong khi L2 kéo trọng số về gần gốc tọa độ mà không ép về 0 tuyệt đối. Trong mạng ReLU nhiều tầng, một “đặc trưng” bị tắt tương ứng với cả một đường dẫn kích hoạt chứ không chỉ một tọa độ riêng lẻ của \(\mathbf{w}\), nên áp L1 trực tiếp lên trọng số thô có hiệu quả hạn chế. Do đó, weight decay (L2) vẫn là lựa chọn mặc định nhờ chi phí tính toán thấp và tính bất biến theo phép quay (&lt;em&gt;rotation-invariant&lt;/em&gt;) trong trường hợp tuyến tính.&lt;/p&gt;

&lt;h3 id=&quot;q3-dropout-giữa-hai-chế-độ-train-và-eval&quot;&gt;Q3. Dropout giữa hai chế độ train và eval&lt;/h3&gt;

&lt;p&gt;Nếu một đơn vị bị loại bỏ với xác suất \(p=0.5\) khi huấn luyện, cần xử lý thế nào lúc đánh giá để giá trị kỳ vọng trước kích hoạt khớp với lúc huấn luyện? Hậu quả sẽ ra sao nếu quên bước này?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý:&lt;/strong&gt; So sánh giữa &lt;em&gt;inverted dropout&lt;/em&gt; và cách chia tỉ lệ cổ điển.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận:&lt;/strong&gt; Với &lt;em&gt;inverted dropout&lt;/em&gt; (mặc định trong các framework hiện đại), các đơn vị được giữ lại sẽ nhân với \(1/(1-p)\) ngay trong lúc huấn luyện, còn lúc đánh giá dùng nguyên toàn mạng. Với dropout cổ điển, lúc huấn luyện không chia tỉ lệ và khi đánh giá phải nhân trọng số với \((1-p)\). Nếu tắt ngẫu nhiên lúc huấn luyện mà bỏ qua bước cân chỉnh tỉ lệ, giá trị kích hoạt lúc suy luận sẽ lớn hơn có hệ thống so với lúc huấn luyện, làm suy giảm cả độ chính xác lẫn độ hiệu chuẩn xác suất. Bên cạnh cách diễn giải “ensemble \(2^n\) mạng con”, điểm vận hành thiết yếu nhất trong cài đặt chính là hệ số chia tỉ lệ này.&lt;/p&gt;

&lt;h3 id=&quot;q4-batchnorm-giữa-hai-chế-độ-train-và-test&quot;&gt;Q4. BatchNorm giữa hai chế độ train và test&lt;/h3&gt;

&lt;p&gt;Vì sao BatchNorm phải duy trì trung bình và phương sai trượt, và điều gì xảy ra nếu đánh giá một checkpoint vừa nạp ở chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train&lt;/code&gt; với kích thước batch bằng 1?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý:&lt;/strong&gt; Phân biệt nguồn thống kê giữa chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận:&lt;/strong&gt; Các giá trị thống kê chạy lưu lại ước lượng quần thể của \(\mathbb{E}[\mathbf{h}]\) và \(\mathrm{Var}(\mathbf{h})\) để dùng ổn định khi suy luận. Nếu chạy ở chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train&lt;/code&gt; với batch size bằng 1, phương sai theo batch bằng 0 (hoặc rất nhiễu với batch quá nhỏ), làm hỏng hoàn toàn phép chuẩn hóa. Hạn chế với batch nhỏ cũng là lý do LayerNorm và GroupNorm được dùng thay thế trong nhiều kiến trúc khác.&lt;/p&gt;

&lt;h3 id=&quot;q5-tăng-cường-dữ-liệu-data-augmentation-như-một-dạng-chính-quy-hóa&quot;&gt;Q5. Tăng cường dữ liệu (Data Augmentation) như một dạng chính quy hóa&lt;/h3&gt;

&lt;p&gt;Giả sử bạn không thể tăng hệ số phạt \(\lambda\) vì mất mát trên tập huấn luyện vốn đã cao. Hãy đề xuất một phương pháp chính quy hóa từ phía dữ liệu không cộng thêm số hạng phạt vào \(J(\mathbf{w})\), kèm theo một tình huống thất bại của nó.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý:&lt;/strong&gt; Tăng cường dữ liệu làm mịn phân phối đầu vào theo các phép biến đổi bảo toàn nhãn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận:&lt;/strong&gt; Các phép biến đổi như cắt ảnh ngẫu nhiên (random crop), lật ảnh hoặc thay đổi màu sắc đưa tính bất biến mong muốn trực tiếp vào dữ liệu huấn luyện mà không thêm hạng phạt lên trọng số. Tuy nhiên, nếu phép tăng cường làm biến đổi cả nhãn gốc (ví dụ cắt mất đối tượng cần nhận diện hoặc lật ngang chữ số), nó sẽ đưa thêm &lt;em&gt;nhiễu nhãn&lt;/em&gt; thay vì tính bất biến hữu ích, khiến sai số tăng trên cả tập huấn luyện lẫn tập kiểm định. Dừng sớm cũng là một dạng chính quy hóa không dùng hạng phạt, nhưng không thể bù đắp cho chiến lược tăng cường dữ liệu sai lệch.&lt;/p&gt;

&lt;h2 id=&quot;ghi-công&quot;&gt;Ghi công&lt;/h2&gt;

&lt;p&gt;Kashani, S., &amp;amp; Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Bạn có thể tải bản PDF từ arXiv để xem đầy đủ ngân hàng câu hỏi kèm lời giải; nội dung trên đây là bộ câu hỏi tự luyện do khóa học biên soạn.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Hệ thống hóa khái niệm nền tảng cho các câu hỏi về quá khớp.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Q81RR3yKn30&quot;&gt;Regularization Part 1: Ridge (L2) Regression&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Ôn tập trực quan về chính quy hóa L2 thường xuất hiện trong phỏng vấn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=D8PJAL-MZv8&quot;&gt;Dropout Regularization (C2W1L06)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Củng cố cơ chế dropout để đối chiếu với L2 và các kỹ thuật khác.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-02 Chuẩn hóa Batch</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_02_Batch_Normalization/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_02_Batch_Normalization</id>
   <content type="html">&lt;p&gt;Trước năm 2015, huấn luyện một mạng CNN trên 10 tầng giống như việc cân bằng một chồng đĩa sứ cao ngất: chỉ cần chỉnh nhích learning rate lên một chút hoặc khởi tạo trọng số hơi lệch, các tầng sâu lập tức nhận đầu vào trôi dạt vào vùng bão hòa và toàn bộ quá trình huấn luyện đổ vỡ. Sự ra đời của &lt;strong&gt;Batch Normalization&lt;/strong&gt; (Ioffe &amp;amp; Szegedy, 2015) đã thay đổi cuộc chơi mãi mãi — biến việc huấn luyện mạng cực sâu trở nên ổn định, nhanh gấp nhiều lần và mở đường cho cả họ chuẩn hóa hiện đại (LayerNorm, GroupNorm, RMSNorm).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-của-chuẩn-hóa-batch-và-họ-chuẩn-hóa&quot;&gt;Kiến thức cần nhớ: Ba trụ cột của Chuẩn hóa Batch và Họ Chuẩn hóa&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế chuẩn hóa 4 bước kèm tham số khôi phục \((\gamma, \beta)\)&lt;/strong&gt;:
Tính trung bình \(\mu_B\) và phương sai \(\sigma_B^2\) trên mini-batch, chuẩn hóa về phân phối chuẩn \((0, 1)\), rồi cho phép mạng tự học lại tỷ lệ \(\gamma\) và độ dịch \(\beta\) để không làm mất sức biểu đạt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hành vi khác biệt giữa Train (thống kê batch) và Eval (Running Mean/Var)&lt;/strong&gt;:
Lúc suy luận (đôi khi chỉ có 1 ảnh duy nhất!), ta không thể tính phương sai của batch 1 mẫu; thay vào đó BatchNorm dùng trung bình trượt hàm mũ (&lt;em&gt;running statistics&lt;/em&gt;) đã tích lũy suốt quá trình huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bản đồ chọn lớp Chuẩn hóa theo miền dữ liệu&lt;/strong&gt;:
BatchNorm cho CNN với batch đủ lớn (\(\ge 16\)), GroupNorm cho phát hiện vật thể/phân đoạn có batch rất nhỏ (1–4 ảnh), InstanceNorm cho chuyển đổi phong cách ảnh, và LayerNorm/RMSNorm cho Transformer/NLP.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-phân-biệt-trục-tính-trung-bình--phương-sai-của-4-họ-chuẩn-hóa-trên-tensor-n-c-h-w&quot;&gt;Giải thích: Phân biệt trục tính trung bình &amp;amp; phương sai của 4 họ Chuẩn hóa trên tensor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, C, H, W)&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;Giả sử ta có một batch ảnh kích thước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N=8, C=64, H=16, W=16)&lt;/code&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Lớp chuẩn hóa&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Tính \(\mu, \sigma^2\) gộp trên các trục nào?&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Số cặp \((\mu, \sigma^2)\) tính ra mỗi lượt&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Phụ thuộc kích thước batch \(N\)?&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;BatchNorm&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, H, W)&lt;/code&gt; — riêng từng kênh \(C\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(C = 64\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Có&lt;/strong&gt; (hỏng khi \(N\) rất nhỏ)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;LayerNorm&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(C, H, W)&lt;/code&gt; — riêng từng mẫu \(N\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(N = 8\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Không&lt;/strong&gt; (chuẩn của Transformer)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;InstanceNorm&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(H, W)&lt;/code&gt; — riêng từng mẫu và từng kênh&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(N \times C = 512\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Không&lt;/strong&gt; (chuẩn Style Transfer)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;GroupNorm&lt;/strong&gt; (\(G=8\) nhóm)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(C/G, H, W)&lt;/code&gt; — từng nhóm kênh của mỗi mẫu&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(N \times G = 64\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Không&lt;/strong&gt; (tốt cho Detection batch nhỏ)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Nắm chắc bảng 4 dòng này giúp bạn chọn đúng chuẩn hóa cho mọi kiến trúc Deep Learning chỉ trong 3 giây!&lt;/p&gt;

&lt;p&gt;Mục này trình bày kỹ thuật chuẩn hóa theo lô (&lt;em&gt;Batch Normalization&lt;/em&gt;) qua hai bài:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế&lt;/strong&gt; — khái niệm, công thức lượt xuôi/lượt ngược, cài đặt bằng NumPy và lý do kỹ thuật này ổn định quá trình huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vị trí đặt, Biến thể và Mẹo&lt;/strong&gt; — BatchNorm2D cho CNN, các biến thể thay thế (LayerNorm, InstanceNorm, GroupNorm), vấn đề thường gặp và kinh nghiệm thực hành.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=nUUqwaxLnWs&quot;&gt;Why Does Batch Norm Work? (C2W3L06)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Giải thích lý do chuẩn hóa theo mini-batch cải thiện đáng kể quá trình huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=P6sfmUTpUmc&quot;&gt;Building makemore Part 3: Activations &amp;amp; Gradients, BatchNorm&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Cài đặt thực tế BatchNorm trong vòng huấn luyện và phân tích tương tác với hàm kích hoạt.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 6&lt;/td&gt;
          &lt;td&gt;Training Neural Networks I](https://www.youtube.com/watch?v=wEoyxE0GP2M) — Stanford University School of Engineering (tiếng Anh). Đặt BatchNorm trong hệ thống các kỹ thuật tối ưu và huấn luyện mạng sâu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-02-02 Vị trí BN, Biến thể và Mẹo</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_02_02_BatchNorm_Placement_and_Variants/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_02_02_BatchNorm_Placement_and_Variants</id>
   <content type="html">&lt;p&gt;Khi thiết kế một khối CNN hoặc Transformer thực tế, hai câu hỏi kỹ thuật luôn xuất hiện: &lt;em&gt;nên đặt BatchNorm trước hay sau hàm kích hoạt ReLU?&lt;/em&gt; và &lt;em&gt;khi VRAM GPU chỉ đủ chạy batch size = 2 (như trong bài toán phân đoạn ảnh y khoa 3D hoặc Object Detection độ phân giải cao), vì sao BatchNorm sụp đổ và phải thay bằng gì?&lt;/em&gt; Bài học này giải quyết dứt điểm cả hai bài toán thiết kế đó.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-quyết-định-thiết-kế-về-vị-trí-và-biến-thể-chuẩn-hóa&quot;&gt;Kiến thức cần nhớ: Bốn quyết định thiết kế về Vị trí và Biến thể Chuẩn hóa&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Vị trí đặt BatchNorm (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv -&amp;gt; BN -&amp;gt; ReLU&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv -&amp;gt; ReLU -&amp;gt; BN&lt;/code&gt;)&lt;/strong&gt;:
Quy ước chuẩn công nghiệp (ResNet, EfficientNet) là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv(bias=False) -&amp;gt; BN -&amp;gt; ReLU&lt;/code&gt; nhằm chuẩn hóa tín hiệu tiền kích hoạt (gần phân phối Gaussian đối xứng quanh 0) trước khi cắt phần âm bởi ReLU; riêng thiết kế Pre-Activation ResNet v2 đặt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BN -&amp;gt; ReLU -&amp;gt; Conv&lt;/code&gt; để giữ đường residual sạch hoàn toàn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cách BatchNorm2d tính thống kê trên ảnh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, C, H, W)&lt;/code&gt;&lt;/strong&gt;:
Với mỗi kênh \(c\), trung bình và phương sai được tính trên tổng cộng \(N \times H \times W\) điểm ảnh — nhờ vậy tính chất chia sẻ trọng số không gian của CNN được bảo toàn trọn vẹn, và lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BatchNorm2d(C)&lt;/code&gt; chỉ có đúng \(2C\) tham số học được (\(\gamma, \beta\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điểm gãy của BatchNorm ở Batch Size nhỏ và giải pháp GroupNorm&lt;/strong&gt;:
Khi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_size&lt;/code&gt; giảm xuống 1–4, ước lượng \(\mu_B, \sigma_B^2\) nhiễu dữ dội khiến sai số tăng vọt (Wu &amp;amp; He, 2018). &lt;strong&gt;Group Normalization&lt;/strong&gt; chia \(C\) kênh thành \(G\) nhóm (thường \(G = 32\)) và chuẩn hóa &lt;em&gt;độc lập trên từng ảnh&lt;/em&gt;, giữ sai số ổn định ngay cả khi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_size = 1&lt;/code&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hợp nhất tầng lúc suy luận (Conv–BN Folding)&lt;/strong&gt;:
Vì ở chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval()&lt;/code&gt;, BatchNorm chỉ là một phép biến đổi tuyến tính cố định, ta có thể gộp trực tiếp trọng số của nó vào ma trận trọng số và bias của tầng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d&lt;/code&gt; đứng ngay trước — giúp suy luận nhanh hơn mà &lt;strong&gt;không tốn thêm một phép tính nào&lt;/strong&gt; cho BatchNorm!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-phép-gộp-tầng-conv--batchnorm-lúc-suy-luận-convbn-folding&quot;&gt;Giải thích: Tính tay phép Gộp tầng Conv + BatchNorm lúc suy luận (Conv–BN Folding)&lt;/h3&gt;

&lt;p&gt;Giả sử một kênh tích chập có trọng số \(w = 2{,}0\) (không có bias), theo sau là BatchNorm ở chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval()&lt;/code&gt; với \(\mu_{\text{run}} = 1{,}0, \; \sigma_{\text{run}} = 2{,}0, \; \gamma = 4{,}0, \; \beta = 0{,}5\).&lt;/p&gt;

&lt;p&gt;Đầu ra khi chạy tuần tự 2 tầng là:
\(y = \gamma \frac{w x - \mu_{\text{run}}}{\sigma_{\text{run}}} + \beta = \left(\frac{\gamma}{\sigma_{\text{run}}} w\right) x + \left(\beta - \frac{\gamma \mu_{\text{run}}}{\sigma_{\text{run}}}\right)\)&lt;/p&gt;

&lt;p&gt;Thay số để gộp thành &lt;strong&gt;một tầng Conv duy nhất&lt;/strong&gt; có trọng số \(w_{\text{fold}}\) và bias \(b_{\text{fold}}\):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Trọng số gộp&lt;/strong&gt;: \(w_{\text{fold}} = \frac{4{,}0}{2{,}0} \times 2{,}0 = \mathbf{4{,}0}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bias gộp&lt;/strong&gt;: \(b_{\text{fold}} = 0{,}5 - \frac{4{,}0 \times 1{,}0}{2{,}0} = 0{,}5 - 2{,}0 = \mathbf{-1{,}5}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng với \(x = 3{,}0\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Chạy 2 tầng rời: \(w x = 6{,}0 \to \frac{6{,}0 - 1{,}0}{2{,}0} = 2{,}5 \to 4{,}0(2{,}5) + 0{,}5 = \mathbf{10{,}5}\).&lt;/li&gt;
      &lt;li&gt;Chạy 1 tầng gộp: \(w_{\text{fold}} x + b_{\text{fold}} = 4{,}0(3{,}0) - 1{,}5 = \mathbf{10{,}5}\) — khớp tuyệt đối từng chữ số thập phân mà loại bỏ hoàn toàn tầng BatchNorm khi triển khai!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;vị-trí-đặt-batchnorm&quot;&gt;Vị trí đặt BatchNorm&lt;/h2&gt;

&lt;h3 id=&quot;trước-hay-sau-hàm-kích-hoạt&quot;&gt;Trước hay sau hàm kích hoạt?&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Cách bố trí trong bài báo gốc (trước hàm kích hoạt):&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Cách bố trí thay thế (sau hàm kích hoạt):&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Cả hai cách đều hoạt động tốt tùy kiến trúc; trong các mạng tích chập chuẩn như ResNet hay MobileNet, thứ tự &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv → BN → ReLU&lt;/code&gt; vẫn rất phổ biến, trong khi một số thực nghiệm lại chọn đặt sau hàm kích hoạt.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-mạng-cnn-kết-hợp-batchnorm&quot;&gt;Ví dụ mạng CNN kết hợp BatchNorm&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvNetWithBatchNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Convolution + BatchNorm + Activation
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Conv2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Conv2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Conv2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm1D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Khối 1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Khối 2
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Khối 3
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Kết nối đầy đủ
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;chuẩn-hóa-batch-cho-cnn-batchnorm2d&quot;&gt;Chuẩn hóa Batch cho CNN (BatchNorm2D)&lt;/h2&gt;

&lt;p&gt;Với tầng tích chập có đầu vào dạng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(batch, channels, height, width)&lt;/code&gt;, thống kê trung bình và phương sai được tính trên chiều batch cùng hai chiều không gian, giữ riêng cho từng kênh:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tham số: một cho mỗi kênh
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Thống kê chạy
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: dạng (batch, channels, height, width)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Tính mean và var trên batch và các chiều không gian
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Giữ chiều kênh
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Chuẩn hóa
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Scale và dịch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật thống kê chạy
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
                               &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
                              &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt;
            
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; \
                    &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;các-biến-thể-chuẩn-hóa-thay-thế&quot;&gt;Các biến thể chuẩn hóa thay thế&lt;/h2&gt;

&lt;h3 id=&quot;1-chuẩn-hóa-lớp-layer-normalization&quot;&gt;1. Chuẩn hóa lớp (&lt;em&gt;Layer Normalization&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Chuẩn hóa dọc theo chiều đặc trưng của từng mẫu độc lập thay vì dọc theo batch:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;layer_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    x: dạng (batch, features)
    Chuẩn hóa mỗi mẫu độc lập
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Ứng dụng tiêu biểu:&lt;/strong&gt; RNN và Transformer (nơi độ dài chuỗi thay đổi hoặc batch size nhỏ).&lt;/p&gt;

&lt;h3 id=&quot;2-chuẩn-hóa-theo-từng-mẫu-và-kênh-instance-normalization&quot;&gt;2. Chuẩn hóa theo từng mẫu và kênh (&lt;em&gt;Instance Normalization&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Chuẩn hóa độc lập theo hai chiều không gian cho từng mẫu và từng kênh:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;instance_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    x: dạng (batch, channels, height, width)
    Chuẩn hóa mỗi instance và kênh
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Ứng dụng tiêu biểu:&lt;/strong&gt; chuyển đổi phong cách ảnh (&lt;em&gt;style transfer&lt;/em&gt;) và GAN.&lt;/p&gt;

&lt;h3 id=&quot;3-chuẩn-hóa-theo-nhóm-group-normalization&quot;&gt;3. Chuẩn hóa theo nhóm (&lt;em&gt;Group Normalization&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Chia các kênh thành nhiều nhóm rồi chuẩn hóa trong từng nhóm, nằm giữa LayerNorm và InstanceNorm:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;group_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_groups&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    x: dạng (batch, channels, height, width)
    Chia kênh thành nhóm và chuẩn hóa
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_groups&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_groups&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Ứng dụng tiêu biểu:&lt;/strong&gt; bài toán phát hiện đối tượng và các hệ thống bị giới hạn batch size nhỏ.&lt;/p&gt;

&lt;h2 id=&quot;các-vấn-đề-thường-gặp-và-hướng-xử-lý&quot;&gt;Các vấn đề thường gặp và hướng xử lý&lt;/h2&gt;

&lt;h3 id=&quot;vấn-đề-1-batch-size-quá-nhỏ&quot;&gt;Vấn đề 1: Batch size quá nhỏ&lt;/h3&gt;

&lt;p&gt;Khi kích thước mini-batch nhỏ, ước lượng trung bình và phương sai theo batch trở nên nhiễu và kém tin cậy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hướng khắc phục:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chuyển sang Group Normalization hoặc Layer Normalization.&lt;/li&gt;
  &lt;li&gt;Tăng batch size nếu bộ nhớ cho phép.&lt;/li&gt;
  &lt;li&gt;Giảm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;momentum&lt;/code&gt; (theo quy ước PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;running = (1 - m) * running + m * batch&lt;/code&gt;) để thống kê chạy cập nhật mượt hơn qua nhiều batch.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;vấn-đề-2-quên-chuyển-chế-độ-huấn-luyện-và-kiểm-tra&quot;&gt;Vấn đề 2: Quên chuyển chế độ huấn luyện và kiểm tra&lt;/h3&gt;

&lt;p&gt;BatchNorm sử dụng thống kê của batch hiện tại khi huấn luyện nhưng dùng thống kê chạy khi suy luận, nên bắt buộc phải đặt đúng chế độ:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# hoặc training=True
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# hoặc training=False
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;evaluate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;vấn-đề-3-kết-hợp-batchnorm-và-dropout&quot;&gt;Vấn đề 3: Kết hợp BatchNorm và Dropout&lt;/h3&gt;

&lt;p&gt;Do cả hai cùng tác động lên phân phối và phương sai kích hoạt, việc kết hợp tùy tiện có thể làm giảm hiệu năng. Thông thường chỉ cần dùng BatchNorm ở các tầng tích chập; nếu vẫn muốn thêm dropout, nên đặt dropout sau BatchNorm và hàm kích hoạt.&lt;/p&gt;

&lt;h2 id=&quot;mẹo-thực-hành&quot;&gt;Mẹo thực hành&lt;/h2&gt;

&lt;h3 id=&quot;1-độ-nhạy-với-khởi-tạo-trọng-số&quot;&gt;1. Độ nhạy với khởi tạo trọng số&lt;/h3&gt;

&lt;p&gt;BatchNorm giúp mạng ít nhạy cảm hơn với thang độ lớn của trọng số khởi tạo:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Không BatchNorm: khởi tạo cẩn thận
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Có BatchNorm: ít nhạy cảm hơn với thang khởi tạo
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.05&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;2-tốc-độ-học-learning-rate&quot;&gt;2. Tốc độ học (&lt;em&gt;Learning Rate&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Nhờ bề mặt tối ưu ổn định hơn, mạng có BatchNorm thường cho phép dùng tốc độ học lớn hơn:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Không BatchNorm
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Có BatchNorm
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Có thể thử cao hơn đáng kể
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;3-hệ-số-momentum-cho-thống-kê-chạy&quot;&gt;3. Hệ số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;momentum&lt;/code&gt; cho thống kê chạy&lt;/h3&gt;

&lt;p&gt;Với quy ước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;running = (1 - momentum) * running + momentum * batch&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Thích nghi nhanh theo batch mới (mặc định PyTorch)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Mượt hơn, giảm nhiễu khi batch nhỏ
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Rất ổn định khi cập nhật trên luồng dữ liệu dài
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;batchnorm-trong-các-kiến-trúc-phổ-biến&quot;&gt;BatchNorm trong các kiến trúc phổ biến&lt;/h2&gt;

&lt;h3 id=&quot;resnet&quot;&gt;ResNet&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet_block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Conv -&amp;gt; BN -&amp;gt; ReLU
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Conv -&amp;gt; BN
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Cộng kết nối bỏ qua trước ReLU cuối
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;mobilenet&quot;&gt;MobileNet&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;depthwise_separable_block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Depthwise conv
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;depthwise_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Pointwise conv
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_1x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Batch Normalization&lt;/strong&gt; chuẩn hóa kích hoạt theo mini-batch để ổn định phân phối giữa các tầng và hỗ trợ tốc độ học lớn hơn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu ứng chính quy hóa nhẹ&lt;/strong&gt; giúp giảm nhu cầu dùng dropout trong nhiều mạng CNN.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các biến thể thay thế&lt;/strong&gt; gồm LayerNorm (RNN, Transformer), InstanceNorm (chuyển phong cách, GAN) và GroupNorm (batch size nhỏ).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lưu ý quan trọng&lt;/strong&gt;: luôn chuyển đúng chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.train()&lt;/code&gt; khi huấn luyện và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; khi đánh giá.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Các kỹ thuật chính quy hóa khác như L1/L2, dừng sớm và tăng cường dữ liệu kết hợp cùng dropout và chuẩn hóa tạo thành bộ công cụ hoàn chỉnh để cải thiện khả năng tổng quát hóa.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=nUUqwaxLnWs&quot;&gt;Why Does Batch Norm Work? (C2W3L06)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Cơ chế nền tảng giúp đánh giá việc đặt BatchNorm trước hay sau hàm kích hoạt.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=P6sfmUTpUmc&quot;&gt;Building makemore Part 3: Activations &amp;amp; Gradients, BatchNorm&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Trình bày vị trí đặt chuẩn hóa trong khối mạng hiện đại và hiện tượng suy giảm khi batch quá nhỏ.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 7&lt;/td&gt;
          &lt;td&gt;Training Neural Networks II](https://www.youtube.com/watch?v=_JB0AO7QxSA) — Stanford University School of Engineering (tiếng Anh). Giới thiệu LayerNorm và các biến thể chuẩn hóa trong phần kiến trúc mạng hiện đại.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-02-01 Cơ chế Chuẩn hóa Batch</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_02_01_BatchNorm_Mechanics/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_02_01_BatchNorm_Mechanics</id>
   <content type="html">&lt;p&gt;Ban đầu, nhóm tác giả Batch Normalization tin rằng kỹ thuật này hiệu quả vì nó triệt tiêu hiện tượng “dịch chuyển hiệp biến nội” (&lt;em&gt;Internal Covariate Shift&lt;/em&gt;). Nhưng đến năm 2018, nhóm nghiên cứu MIT (Santurkar et al.) phát hiện ra một nguyên nhân sâu sắc hơn nữa: &lt;strong&gt;BatchNorm làm cho bề mặt hàm mất mát và gradient trở nên mượt mà (Lipschitz-smooth) hơn hẳn&lt;/strong&gt;, giúp bước nhảy gradient descent trở nên cực kỳ dự đoán được và cho phép dùng tốc độ học lớn hơn nhiều lần!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-cơ-chế-toán-học-bên-trong-batch-normalization&quot;&gt;Kiến thức cần nhớ: Bốn cơ chế toán học bên trong Batch Normalization&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa z-score và hằng số ổn định \(\epsilon\)&lt;/strong&gt;:
\(\hat{x}_i = \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}}\) đưa mọi đặc trưng về trung bình \(0\) và phương sai \(\approx 1\), trong đó \(\epsilon \approx 10^{-5}\) ngăn chia cho 0 khi các giá trị trong batch giống hệt nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biến đổi Affine học được \(y_i = \gamma \hat{x}_i + \beta\)&lt;/strong&gt;:
Tại sao đã chuẩn hóa về \((0, 1)\) lại phải nhân \(\gamma\) cộng \(\beta\)? Vì nếu kích hoạt nằm trước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sigmoid&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tanh&lt;/code&gt;, việc ép toàn bộ vào vùng tuyến tính quanh 0 sẽ làm mất tính phi tuyến; \(\gamma, \beta\) trao lại cho mạng quyền tự khôi phục phân phối tối ưu nếu cần.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật thống kê trượt (Exponential Moving Average) cho lúc suy luận&lt;/strong&gt;:
Sau mỗi mini-batch huấn luyện: \(\mu_{\text{run}} \leftarrow (1 - m)\mu_{\text{run}} + m \mu_B\) (trong PyTorch mặc định &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;momentum=0.1&lt;/code&gt; ứng với \(m = 0{,}1\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính bất biến theo tỷ lệ trọng số (Scale Invariance) và dư thừa Bias&lt;/strong&gt;:
Nhân trọng số tầng trước với hằng số \(a &amp;gt; 0\) hay cộng thêm bias \(b\) đều bị triệt tiêu hoàn toàn bởi bước trừ \(\mu_B\) và chia \(\sigma_B\)! Đó là lý do các tầng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear&lt;/code&gt; đứng ngay trước BatchNorm luôn nên đặt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias=False&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-trọn-vẹn-4-bước-forward-của-batchnorm-trên-một-mini-batch-4-mẫu&quot;&gt;Giải thích: Tính tay trọn vẹn 4 bước Forward của BatchNorm trên một mini-batch 4 mẫu&lt;/h3&gt;

&lt;p&gt;Cho giá trị kích hoạt của 1 kênh trên mini-batch 4 mẫu là \(\mathbf{x} = [2{,}0, \; 4{,}0, \; 6{,}0, \; 8{,}0]\), với tham số học được \(\gamma = 2{,}0, \; \beta = 1{,}0\) và \(\epsilon = 0\) (để tính tay gọn):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Tính trung bình batch \(\mu_B\)&lt;/strong&gt;:
\(\mu_B = \frac{2 + 4 + 6 + 8}{4} = \mathbf{5{,}0}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Tính phương sai batch \(\sigma_B^2\)&lt;/strong&gt; (chia cho \(m = 4\) trong lượt forward):
\(\sigma_B^2 = \frac{(2-5)^2 + (4-5)^2 + (6-5)^2 + (8-5)^2}{4} = \frac{9 + 1 + 1 + 9}{4} = \mathbf{5{,}0} \implies \sigma_B = \sqrt{5} \approx \mathbf{2{,}236}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Chuẩn hóa \(\hat{x}_i = (x_i - 5{,}0) / 2{,}236\)&lt;/strong&gt;:
\(\hat{\mathbf{x}} \approx \mathbf{[-1{,}342, \; -0{,}447, \; +0{,}447, \; +1{,}342]}\)
(Kiểm tra nhanh: trung bình bằng \(0\), trung bình bình phương bằng \(1{,}00\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 4 — Co giãn và dịch chuyển \(y_i = 2{,}0 \hat{x}_i + 1{,}0\)&lt;/strong&gt;:
\(\mathbf{y} \approx \mathbf{[-1{,}683, \; +0{,}106, \; +1{,}894, \; +3{,}683]}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nếu lúc khởi tạo ban đầu \(\gamma = 1, \beta = 0\), đầu ra chính là phân phối chuẩn hóa \(\hat{\mathbf{x}}\); rồi qua các bước SGD, mạng tự điều chỉnh \(\gamma, \beta\) đến đúng biên độ tối ưu cho tầng kế tiếp!&lt;/p&gt;

&lt;h2 id=&quot;chuẩn-hóa-batch-là-gì&quot;&gt;Chuẩn hóa Batch là gì?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Chuẩn hóa Batch&lt;/strong&gt; (&lt;em&gt;Batch Normalization&lt;/em&gt; — BatchNorm hay BN), do Ioffe và Szegedy giới thiệu năm 2015, chuẩn hóa đầu vào của từng tầng theo mỗi mini-batch về trung bình 0 và phương sai 1, sau đó áp dụng phép biến đổi tỉ lệ và tịnh tiến có tham số học được. Đây là một trong những kỹ thuật ổn định huấn luyện được sử dụng rộng rãi nhất trong học sâu.&lt;/p&gt;

&lt;h3 id=&quot;vấn-đề-đặt-ra-dịch-chuyển-hiệp-biến-nội-internal-covariate-shift&quot;&gt;Vấn đề đặt ra: Dịch chuyển hiệp biến nội (&lt;em&gt;Internal Covariate Shift&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Trong quá trình huấn luyện mạng sâu, khi trọng số ở các tầng trước liên tục cập nhật:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Phân phối đầu vào của các tầng phía sau thay đổi theo từng bước.&lt;/li&gt;
  &lt;li&gt;Mỗi tầng phải liên tục thích nghi với phân phối mới.&lt;/li&gt;
  &lt;li&gt;Quá trình hội tụ chậm hơn và mạng nhạy cảm với cách khởi tạo trọng số.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Cách tiếp cận của BatchNorm:&lt;/strong&gt; chuẩn hóa trực tiếp đầu vào tầng để giữ thang đo và phân phối ổn định hơn xuyên suốt quá trình huấn luyện.&lt;/p&gt;

&lt;h2 id=&quot;cách-batchnorm-hoạt-động&quot;&gt;Cách BatchNorm hoạt động&lt;/h2&gt;

&lt;h3 id=&quot;lượt-truyền-xuôi-khi-huấn-luyện&quot;&gt;Lượt truyền xuôi khi huấn luyện&lt;/h3&gt;

&lt;p&gt;Với một mini-batch kích hoạt \(\mathbf{x} = \{x_1, x_2, \ldots, x_m\}\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 1: Tính trung bình và phương sai của mini-batch&lt;/strong&gt;&lt;/p&gt;

\[\mu_{\mathcal{B}} = \frac{1}{m} \sum_{i=1}^{m} x_i\]

\[\sigma^2_{\mathcal{B}} = \frac{1}{m} \sum_{i=1}^{m} (x_i - \mu_{\mathcal{B}})^2\]

&lt;p&gt;&lt;strong&gt;Bước 2: Chuẩn hóa&lt;/strong&gt;&lt;/p&gt;

\[\hat{x}_i = \frac{x_i - \mu_{\mathcal{B}}}{\sqrt{\sigma^2_{\mathcal{B}} + \epsilon}}\]

&lt;p&gt;trong đó \(\epsilon\) (ví dụ \(10^{-5}\)) là hằng số nhỏ tránh chia cho 0.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 3: Co giãn và tịnh tiến (tham số học được)&lt;/strong&gt;&lt;/p&gt;

\[y_i = \gamma \hat{x}_i + \beta\]

&lt;p&gt;trong đó \(\gamma\) (hệ số co giãn) và \(\beta\) (độ dịch) được học qua lan truyền ngược để mạng vẫn giữ khả năng biểu diễn ban đầu khi cần.&lt;/p&gt;

&lt;h3 id=&quot;khi-suy-luận-kiểm-tra&quot;&gt;Khi suy luận (kiểm tra)&lt;/h3&gt;

&lt;p&gt;Thay vì tính trên batch kiểm tra, mô hình dùng thống kê tích lũy (trung bình trượt theo hàm mũ thu được trong lúc huấn luyện):&lt;/p&gt;

\[\hat{x} = \frac{x - \mu_{\text{pop}}}{\sqrt{\sigma^2_{\text{pop}} + \epsilon}}\]

\[y = \gamma \hat{x} + \beta\]

&lt;h2 id=&quot;cài-đặt-bằng-numpy&quot;&gt;Cài đặt bằng NumPy&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm1D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        num_features: số đặc trưng/kênh
        eps: hằng số nhỏ cho ổn định số
        momentum: cho cập nhật trung bình/phương sai chạy
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tham số học được
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Thống kê chạy (cho suy luận)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Cache cho backprop
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: đầu vào dạng (batch_size, num_features)
        training: có đang ở chế độ huấn luyện không
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Tính thống kê batch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;batch_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;batch_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Chuẩn hóa
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Scale và dịch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật thống kê chạy
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
                               &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_mean&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
                              &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_var&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cache cho lượt ngược
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Dùng thống kê chạy
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; \
                          &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Lan truyền ngược qua chuẩn hóa batch
        dout: gradient từ tầng sau
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;D&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient của tham số
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dgamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dbeta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient của x đã chuẩn hóa
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dx_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient của phương sai
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dx_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; \
                     &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient của trung bình
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dmean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dx_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
                &lt;span class=&quot;n&quot;&gt;dvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient của x
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dx_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
             &lt;span class=&quot;n&quot;&gt;dvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
             &lt;span class=&quot;n&quot;&gt;dmean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ sử dụng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm1D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;out_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trung bình đầu ra train: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Độ lệch chuẩn đầu ra train: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;out_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Test dùng thống kê chạy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;vì-sao-chuẩn-hóa-batch-hiệu-quả&quot;&gt;Vì sao Chuẩn hóa Batch hiệu quả&lt;/h2&gt;

&lt;h3 id=&quot;1-ổn-định-phân-phối-kích-hoạt-giữa-các-tầng&quot;&gt;1. Ổn định phân phối kích hoạt giữa các tầng&lt;/h3&gt;
&lt;p&gt;Giữ cho thang đo đầu vào của từng tầng nhất quán hơn qua các bước cập nhật, giảm bớt tác động của sự thay đổi phân phối ở các tầng trước.&lt;/p&gt;

&lt;h3 id=&quot;2-cho-phép-dùng-tốc-độ-học-lớn-hơn&quot;&gt;2. Cho phép dùng tốc độ học lớn hơn&lt;/h3&gt;
&lt;p&gt;Luồng gradient ổn định hơn giúp tăng tốc độ học và rút ngắn thời gian hội tụ đáng kể, đồng thời giảm độ nhạy cảm với cách khởi tạo trọng số.&lt;/p&gt;

&lt;h3 id=&quot;3-tạo-hiệu-ứng-chính-quy-hóa-nhẹ&quot;&gt;3. Tạo hiệu ứng chính quy hóa nhẹ&lt;/h3&gt;
&lt;p&gt;Thống kê trung bình và phương sai ước lượng trên từng mini-batch mang một lượng nhiễu nhỏ, góp phần hạn chế quá khớp và giảm nhu cầu dùng dropout ở một số kiến trúc.&lt;/p&gt;

&lt;h3 id=&quot;4-làm-trơn-bề-mặt-hàm-mất-mát&quot;&gt;4. Làm trơn bề mặt hàm mất mát&lt;/h3&gt;
&lt;p&gt;Các phân tích lý thuyết và thực nghiệm cho thấy BatchNorm làm bề mặt tối ưu mượt hơn, giúp hướng gradient ổn định và dễ dự đoán hơn trong quá trình tối ưu hóa.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=nUUqwaxLnWs&quot;&gt;Why Does Batch Norm Work? (C2W3L06)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Trình bày công thức chuẩn hóa theo trung bình–phương sai và cơ chế co giãn lại bằng \(\gamma, \beta\).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=P6sfmUTpUmc&quot;&gt;Building makemore Part 3: Activations &amp;amp; Gradients, BatchNorm&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Minh họa trực tiếp cách tính thống kê batch theo từng kênh trong mã nguồn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 6&lt;/td&gt;
          &lt;td&gt;Training Neural Networks I](https://www.youtube.com/watch?v=wEoyxE0GP2M) — Stanford University School of Engineering (tiếng Anh). Phân tích vai trò ổn định huấn luyện của BatchNorm trong bài giảng mạng sâu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-01 Chính quy hóa Dropout</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_01_Dropout/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_01_Dropout</id>
   <content type="html">&lt;p&gt;Geoffrey Hinton từng kể lại nguồn cảm hứng kỳ lạ đằng sau &lt;strong&gt;Dropout&lt;/strong&gt;: khi đến ngân hàng, ông nhận thấy các giao dịch viên liên tục bị luân chuyển bàn làm việc — bởi nếu ai cũng chỉ làm mãi một vị trí cố định, một nhóm nhân viên có thể thông đồng gian lận; việc luân chuyển ngẫu nhiên buộc mỗi người phải tự làm việc độc lập. Tương tự, việc “cho nghỉ phép ngẫu nhiên” một nửa số neuron ở mỗi bước huấn luyện đã trở thành một trong những ý tưởng đơn giản nhưng hiệu quả nhất lịch sử học sâu.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-để-nắm-vững-chính-quy-hóa-dropout&quot;&gt;Kiến thức cần nhớ: Ba trụ cột để nắm vững Chính quy hóa Dropout&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế Inverted Dropout (Train vs. Eval)&lt;/strong&gt;:
Trong lúc huấn luyện, các neuron sống sót được chia cho \((1 - p)\) để giữ nguyên kỳ vọng đầu ra; nhờ vậy lúc suy luận (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt;) ta không cần nhân thêm bất kỳ hệ số nào mà chạy thẳng mạng đầy đủ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diễn giải Quần thể Mạng (Implicit Ensemble)&lt;/strong&gt;:
Một mạng có \(N\) neuron ẩn áp dụng Dropout thực chất đang huấn luyện đồng thời một quần thể gồm tới \(2^N\) mạng con chia sẻ chung trọng số, và lúc suy luận ta lấy trung bình hình học xấp xỉ của cả quần thể đó.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng đúng chỗ trong thực tế&lt;/strong&gt;:
Dùng tỷ lệ lớn hơn (\(p = 0{,}3\text{–}0{,}5\)) cho tầng Dense nhiều tham số, tỷ lệ nhỏ hơn (\(p = 0{,}1\text{–}0{,}2\)) cho tầng Attention/Embedding, và thay bằng Spatial Dropout (Dropout2d) hoặc DropPath cho CNN/ViT.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-kiểm-chứng-bằng-số-vì-sao-inverted-dropout-bảo-toàn-đúng-giá-trị-kỳ-vọng&quot;&gt;Giải thích: Kiểm chứng bằng số vì sao Inverted Dropout bảo toàn đúng giá trị kỳ vọng&lt;/h3&gt;

&lt;p&gt;Giả sử một tầng ẩn có đầu ra \(\mathbf{a} = [2{,}0, \; 4{,}0, \; 6{,}0, \; 8{,}0]\) (trung bình bằng \(5{,}0\)), và ta dùng Dropout với tỷ lệ tắt \(p = 0{,}5\) (tỷ lệ giữ \(1 - p = 0{,}5\)). Giả sử mặt nạ ngẫu nhiên giữ lại phần tử thứ 2 và thứ 4: \(\mathbf{m} = [0, \; 1, \; 0, \; 1]\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Chế độ&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Công thức tính&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Vector đầu ra&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Tổng các phần tử&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Không Dropout (Eval)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathbf{a}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([2{,}0,\; 4{,}0,\; 6{,}0,\; 8{,}0]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;20,0&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Dropout không chia \((1-p)\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\mathbf{a} \odot \mathbf{m}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([0{,}0,\; 4{,}0,\; 0{,}0,\; 8{,}0]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;12,0&lt;/strong&gt; (bị hụt một nửa biên độ!)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Inverted Dropout (Train chuẩn)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\frac{\mathbf{a} \odot \mathbf{m}}{1 - p}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([0{,}0,\; 8{,}0,\; 0{,}0,\; 16{,}0]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;24,0&lt;/strong&gt; (kỳ vọng toán học đúng bằng &lt;strong&gt;20,0&lt;/strong&gt;)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Tính kỳ vọng cho từng phần tử \(a_i\): \(\mathbb{E}\!\left[\frac{a_i m_i}{1 - p}\right] = \frac{a_i}{1-p} \cdot \mathbb{E}[m_i] = \frac{a_i}{1-p} \cdot (1 - p) = a_i\) — trùng khớp hoàn toàn với lúc chạy suy luận!&lt;/p&gt;

&lt;p&gt;Mục này trình bày kỹ thuật chính quy hóa dropout qua hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết và Trực giác&lt;/strong&gt; — cơ chế mặt nạ ngẫu nhiên, inverted dropout và lý do giảm quá khớp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt và Cạm bẫy&lt;/strong&gt; — mã nguồn PyTorch/NumPy, các bài báo nền tảng, lỗi thường gặp và điểm chính.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=D8PJAL-MZv8&quot;&gt;Dropout Regularization (C2W1L06)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Giải thích cơ chế vô hiệu hóa ngẫu nhiên các đơn vị trong mạng.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=6g0t3Phly2M&quot;&gt;Regularization (C2W1L04)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Đặt dropout cạnh các kỹ thuật chính quy hóa phổ biến khác.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Ôn lại khái niệm phương sai mà dropout giúp kiểm soát.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-01-02 Cài đặt Dropout và Cạm bẫy</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_01_02_Dropout_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_01_02_Dropout_Implementation</id>
   <content type="html">&lt;p&gt;Một trong những lỗi “âm thầm nhưng chí mạng” hay gặp nhất trong các dự án PyTorch thực tế là &lt;strong&gt;quên gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; trước khi chạy vòng đánh giá validation/test&lt;/strong&gt;. Kết quả là Dropout vẫn tiếp tục tắt ngẫu nhiên 50% neuron trong lúc chấm điểm, khiến độ chính xác tập kiểm định vừa tụt thảm hại vừa nhảy loạn xạ sau mỗi lần chạy! Bài thực hành này giúp bạn làm chủ cả cài đặt chuẩn PyTorch, bản viết tay NumPy (cả forward lẫn backward) và các quy tắc kết hợp với BatchNorm.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-điểm-kỹ-thuật-cốt-tử-khi-cài-đặt-dropout&quot;&gt;Kiến thức cần nhớ: Bốn điểm kỹ thuật cốt tử khi cài đặt Dropout&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền ngược qua lớp Dropout&lt;/strong&gt;:
Trong lượt backward, gradient chỉ được truyền ngược qua &lt;strong&gt;đúng những neuron đã sống sót&lt;/strong&gt; trong lượt forward (nhân lại với chính mặt nạ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mask / (1 - p)&lt;/code&gt; đã lưu ở cache); các neuron bị tắt nhận gradient bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quản lý chặt chẽ hai chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.train()&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt;&lt;/strong&gt;:
Luôn bọc vòng đánh giá trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; kết hợp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;with torch.no_grad():&lt;/code&gt;, và nhớ gọi lại &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.train()&lt;/code&gt; trước khi sang epoch huấn luyện kế tiếp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân biệt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Dropout&lt;/code&gt; (phần tử) và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Dropout2d&lt;/code&gt; (toàn kênh)&lt;/strong&gt;:
Trên bản đồ đặc trưng CNN, các điểm ảnh kề nhau tương quan rất mạnh nên tắt lẻ từng pixel hầu như vô tác dụng; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Dropout2d&lt;/code&gt; tắt nguyên cả kênh đặc trưng để ép CNN thực sự học đặc trưng độc lập.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tránh xung đột giữa Dropout và BatchNorm&lt;/strong&gt;:
Đặt Dropout ngay &lt;em&gt;trước&lt;/em&gt; BatchNorm làm thay đổi phương sai giữa train và eval (hiện tượng &lt;em&gt;variance shift&lt;/em&gt;, Li et al. 2019). Quy tắc an toàn: đặt Dropout sau BatchNorm hoặc chỉ dùng ở tầng phân loại cuối.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-cả-forward-và-backward-của-một-lớp-inverted-dropout-bằng-numpy&quot;&gt;Giải thích: Tính tay cả Forward và Backward của một lớp Inverted Dropout bằng NumPy&lt;/h3&gt;

&lt;p&gt;Giả sử đầu vào \(\mathbf{x} = [1{,}0, \; -2{,}0, \; 4{,}0, \; 3{,}0]\), tỷ lệ tắt \(p = 0{,}2\) (tỷ lệ giữ \(1 - p = 0{,}8\)), mặt nạ ngẫu nhiên rút được là \(\mathbf{m} = [1, \; 0, \; 1, \; 1]\), và gradient từ tầng trên truyền xuống là \(\mathbf{g}_{\text{out}} = [0{,}4, \; 0{,}8, \; -0{,}4, \; 1{,}6]\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước Forward (hệ số khuếch đại \(\frac{1}{1 - p} = \frac{1}{0{,}8} = 1{,}25\))&lt;/strong&gt;:
\(\mathbf{y} = \mathbf{x} \odot \mathbf{m} \times 1{,}25 = [1{,}0\cdot 1,\; -2{,}0\cdot 0,\; 4{,}0\cdot 1,\; 3{,}0\cdot 1] \times 1{,}25 = \mathbf{[1{,}25, \; 0{,}00, \; 5{,}00, \; 3{,}75]}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước Backward (dùng lại CHÍNH xác mặt nạ \(\mathbf{m}\) và hệ số \(1{,}25\))&lt;/strong&gt;:
\(\mathbf{g}_{\text{in}} = \mathbf{g}_{\text{out}} \odot \mathbf{m} \times 1{,}25 = [0{,}4\cdot 1,\; 0{,}8\cdot 0,\; -0{,}4\cdot 1,\; 1{,}6\cdot 1] \times 1{,}25 = \mathbf{[0{,}50, \; 0{,}00, \; -0{,}50, \; 2{,}00]}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chú ý phần tử thứ 2: dù gradient từ trên truyền xuống là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.8&lt;/code&gt;, vì neuron này đã bị tắt ở lượt forward nên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;g_in[1] = 0.00&lt;/code&gt; — nó hoàn toàn không bị cập nhật trọng số ở bước này!&lt;/p&gt;

&lt;h2 id=&quot;4-đoạn-mã&quot;&gt;4. Đoạn Mã&lt;/h2&gt;

&lt;h3 id=&quot;cài-đặt-bằng-pytorch&quot;&gt;Cài đặt bằng PyTorch&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MLPWithDropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MLPWithDropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Tầng 1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropout1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Dropout sau kích hoạt
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Tầng 2
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropout2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tầng đầu ra (không dropout)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MLPWithDropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Bật dropout
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Batch 32
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape đầu ra huấn luyện: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (32, 10)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Kiểm tra
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Tắt dropout
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;output_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape đầu ra kiểm tra: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (10, 10)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Kiểm tra hiệu ứng dropout
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cùng đầu vào
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện (có dropout) - đầu ra biến thiên:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;outputs_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cùng đầu vào
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kiểm tra (không dropout) - đầu ra giống hệt:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;cài-đặt-dropout-thủ-công-bằng-numpy&quot;&gt;Cài đặt Dropout thủ công bằng NumPy&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DropoutManual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        X: (batch, features)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Sinh mặt nạ: 1 với xác suất (1-p), 0 với xác suất p
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;keep_prob&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keep_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Áp dụng mặt nạ và scale
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keep_prob&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient chỉ chảy qua các neuron được giữ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;keep_prob&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keep_prob&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DropoutManual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đơn vị bị loại: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra  
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đơn vị bị loại lúc test: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;spatial-dropout-cho-cnn&quot;&gt;Spatial Dropout cho CNN&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SpatialDropout2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (batch, channels, height, width)
        Loại bỏ toàn bộ bản đồ đặc trưng
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Shape mặt nạ: (batch, channels, 1, 1)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Cùng mặt nạ cho mọi vị trí không gian trong một kênh
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bernoulli&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; 
                              &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spatial_dropout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SpatialDropout2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Batch=2, 64 kênh, 32×32
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;spatial_dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Toàn bộ kênh bị loại: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;h3 id=&quot;chuẩn-hóa-batch-batch-normalization&quot;&gt;Chuẩn hóa Batch (&lt;em&gt;Batch Normalization&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Cũng mang lại hiệu ứng chính quy hóa nhẹ nhờ nhiễu thống kê mini-batch.&lt;/li&gt;
  &lt;li&gt;Trong nhiều kiến trúc CNN hiện đại, BatchNorm giúp giảm nhu cầu dùng dropout.&lt;/li&gt;
  &lt;li&gt;Nếu kết hợp cả hai, thường đặt dropout sau BatchNorm và hàm kích hoạt.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tăng-cường-dữ-liệu-data-augmentation&quot;&gt;Tăng cường dữ liệu (&lt;em&gt;Data Augmentation&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Chính quy hóa từ phía dữ liệu bằng cách tạo thêm biến thể hợp lệ cho tập huấn luyện.&lt;/li&gt;
  &lt;li&gt;Bổ trợ tốt cho dropout.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;dừng-sớm-early-stopping&quot;&gt;Dừng sớm (&lt;em&gt;Early Stopping&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Dừng huấn luyện khi hàm mất mát trên tập kiểm định bắt đầu tăng liên tục, có thể kết hợp song song với dropout.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;phương-pháp-tổ-hợp-ensemble&quot;&gt;Phương pháp tổ hợp (&lt;em&gt;Ensemble&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Huấn luyện nhiều mô hình độc lập rồi lấy trung bình dự đoán; dropout xấp xỉ ý tưởng này trong một mạng duy nhất.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;dropconnect&quot;&gt;DropConnect&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Vô hiệu hóa ngẫu nhiên các kết nối (trọng số) thay vì toàn bộ neuron; ý tưởng tương đồng nhưng ít phổ biến hơn dropout.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://jmlr.org/papers/v15/srivastava14a.html&quot;&gt;“Dropout: A Simple Way to Prevent Neural Networks from Overfitting” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Nitish Srivastava, Geoffrey Hinton, Alex Krizhevsky, Ilya Sutskever, Ruslan Salakhutdinov&lt;br /&gt;
Bài báo tiêu chuẩn về dropout, phân tích cơ chế ngăn đồng thích nghi giữa các neuron và chứng minh cải thiện rõ rệt trên nhiều tập chuẩn như MNIST, CIFAR và ImageNet.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1207.0580&quot;&gt;“Improving neural networks by preventing co-adaptation of feature detectors” (2012)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Geoffrey E. Hinton, Nitish Srivastava, Alex Krizhevsky, và cộng sự&lt;br /&gt;
Công trình sớm giới thiệu ý tưởng dropout và diễn giải kỹ thuật này như một tổ hợp gồm số lượng lớn theo hàm mũ các mạng con chia sẻ tham số.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://proceedings.mlr.press/v28/wan13.html&quot;&gt;“Regularization of Neural Networks using DropConnect” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Li Wan, Matthew Zeiler, Sixin Zhang, Yann LeCun, Rob Fergus&lt;br /&gt;
Đề xuất DropConnect — tổng quát hóa cơ chế loại bỏ ngẫu nhiên từ cấp độ neuron sang cấp độ từng kết nối trọng số.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1411.4280&quot;&gt;“Spatial Dropout” (2015) — một phần của “Efficient Object Localization Using CNNs”&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Jonathan Tompson, Ross Goroshin, Arjun Jain, Yann LeCun, Christoph Bregler&lt;br /&gt;
Giới thiệu &lt;em&gt;spatial dropout&lt;/em&gt; cho tầng tích chập bằng cách loại bỏ nguyên bản đồ đặc trưng thay vì từng điểm ảnh rời rạc, phù hợp với tính tương quan không gian của CNN.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.05287&quot;&gt;“A Theoretically Grounded Application of Dropout in RNNs” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Yarin Gal, Zoubin Ghahramani&lt;br /&gt;
Phân tích cách dùng dropout trong RNN (đề xuất &lt;em&gt;variational dropout&lt;/em&gt; giữ cố định mặt nạ qua các bước thời gian) và thiết lập liên hệ lý thuyết giữa dropout với suy luận Bayes xấp xỉ để ước lượng độ bất định.&lt;/p&gt;

&lt;h2 id=&quot;cạm-bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;Cạm bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;h3 id=&quot;️-cạm-bẫy-1-quên-tắt-dropout-khi-kiểm-tra&quot;&gt;⚠️ Cạm bẫy 1: Quên tắt dropout khi kiểm tra&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Vấn đề:&lt;/strong&gt; Dropout vẫn hoạt động lúc đánh giá khiến kết quả dự đoán biến động ngẫu nhiên.&lt;br /&gt;
&lt;strong&gt;Giải pháp:&lt;/strong&gt; Luôn chuyển sang chế độ đánh giá bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Sai
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Dropout vẫn bật nếu model ở chế độ train!
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Đúng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;️-cạm-bẫy-2-tỷ-lệ-dropout-quá-cao&quot;&gt;⚠️ Cạm bẫy 2: Tỷ lệ dropout quá cao&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Vấn đề:&lt;/strong&gt; Đặt tỷ lệ quá lớn làm mất quá nhiều dung lượng biểu diễn của mạng.&lt;br /&gt;
&lt;strong&gt;Giải pháp:&lt;/strong&gt; Chọn tỷ lệ phù hợp với từng loại tầng (khoảng 0.5 cho tầng kết nối đầy đủ, thấp hơn cho tầng tích chập hoặc đầu vào).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Quá mạnh - có thể hại hiệu năng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Loại 90%!
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Điểm xuất phát tốt hơn
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# Kết nối đầy đủ
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Tích chập
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# Tầng đầu vào
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;️-cạm-bẫy-3-kết-hợp-không-phù-hợp-với-batch-normalization&quot;&gt;⚠️ Cạm bẫy 3: Kết hợp không phù hợp với Batch Normalization&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Vấn đề:&lt;/strong&gt; Dropout làm thay đổi phương sai kích hoạt giữa hai chế độ train và eval, dễ tương tác kém với thống kê chạy của BatchNorm.&lt;br /&gt;
&lt;strong&gt;Giải pháp:&lt;/strong&gt; Thường ưu tiên dùng BatchNorm riêng lẻ; nếu cần kết hợp, đặt dropout sau lớp BatchNorm và hàm kích hoạt.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Thực hành hiện đại: Dùng BN, bỏ dropout
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Không cần dropout!
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Nếu dùng cả hai: dropout sau BN
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Sau kích hoạt
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;-mẹo-1-dùng-tỷ-lệ-khác-nhau-cho-từng-tầng&quot;&gt;✅ Mẹo 1: Dùng tỷ lệ khác nhau cho từng tầng&lt;/h3&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SmartDropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Bảo thủ
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Chuẩn
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_deep&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Thấp hơn cho tầng sâu
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;-mẹo-2-monte-carlo-dropout-ước-lượng-độ-bất-định&quot;&gt;✅ Mẹo 2: Monte Carlo Dropout (ước lượng độ bất định)&lt;/h3&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mc_dropout_predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Nhiều lượt xuôi ngẫu nhiên để ước lượng bất định
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Giữ dropout BẬT
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mean_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;uncertainty&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;uncertainty&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Lấy dự đoán kèm bất định
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mc_dropout_predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dự đoán: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Bất định: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;-mẹo-3-dropout-theo-lịch-trình-scheduled-dropout&quot;&gt;✅ Mẹo 3: Dropout theo lịch trình (&lt;em&gt;Scheduled Dropout&lt;/em&gt;)&lt;/h3&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ScheduledDropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tăng dần tỷ lệ dropout trong quá trình huấn luyện&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;final_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total_epochs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_rate&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;final_rate&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total_epochs&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;get_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;progress&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progress&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;điểm-chính&quot;&gt;Điểm chính&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Dropout&lt;/strong&gt; vô hiệu hóa ngẫu nhiên một phần neuron trong lúc huấn luyện để ngăn đồng thích nghi và tạo hiệu ứng tổ hợp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tỷ lệ tham khảo&lt;/strong&gt;: khoảng 0.5 cho tầng kết nối đầy đủ, 0.1–0.3 cho tầng tích chập và khoảng 0.1–0.2 cho tầng đầu vào.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chia tỉ lệ (inverted dropout)&lt;/strong&gt;: nhân các đơn vị giữ lại với \(\frac{1}{1-p}\) khi huấn luyện để giữ nguyên kỳ vọng khi suy luận.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chế độ vận hành&lt;/strong&gt;: luôn nhớ chuyển &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.train()&lt;/code&gt; khi huấn luyện và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; khi đánh giá.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bối cảnh hiện đại&lt;/strong&gt;: ít dùng nặng ở các tầng tích chập đã có BatchNorm, nhưng vẫn là kỹ thuật nền tảng cần nắm vững.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tiếp theo là bài về &lt;strong&gt;Chuẩn hóa Batch (Batch Normalization)&lt;/strong&gt; — kỹ thuật chuẩn hóa kích hoạt giúp ổn định và tăng tốc quá trình huấn luyện mạng sâu.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=D8PJAL-MZv8&quot;&gt;Dropout Regularization (C2W1L06)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Giải thích cách tạo mặt nạ và hệ số inverted dropout trước khi cài đặt.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 6&lt;/td&gt;
          &lt;td&gt;Training Neural Networks I](https://www.youtube.com/watch?v=wEoyxE0GP2M) — Stanford University School of Engineering (tiếng Anh). Minh họa cách tích hợp dropout đúng chế độ train/eval trong vòng huấn luyện.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=6g0t3Phly2M&quot;&gt;Regularization (C2W1L04)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Nêu rõ lưu ý khi đánh giá mô hình có sử dụng dropout.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-01-01 Lý thuyết và Trực giác Dropout</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_01_01_Dropout_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_01_01_Dropout_Theory</id>
   <content type="html">&lt;p&gt;Tại sao một phép toán thô bạo như việc &lt;strong&gt;nhân ngẫu nhiên 50% neuron với số 0&lt;/strong&gt; ở mỗi mini-batch không hề phá hủy quá trình học, mà trái lại còn giúp mạng sâu đạt độ chính xác kiểm định cao hơn? Câu trả lời nằm ở giao điểm giữa xác suất thống kê (bảo toàn kỳ vọng qua Inverted Dropout), lý thuyết tổ hợp (lấy mẫu \(2^N\) mạng con) và phép xấp xỉ Bayes (MC Dropout để ước lượng độ bất định).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-khía-cạnh-lý-thuyết-của-dropout&quot;&gt;Kiến thức cần nhớ: Bốn khía cạnh lý thuyết của Dropout&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chống đồng thích nghi (Preventing Co-adaptation)&lt;/strong&gt;:
Nếu không có Dropout, neuron A có thể học sửa sai cho lỗi riêng của neuron B — tạo ra sự phụ thuộc mong manh chỉ đúng trên tập train. Dropout buộc mỗi neuron phải học đặc trưng hữu ích ngay cả khi “đồng đội” của nó biến mất bất ngờ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sự tương đương với Chính quy hóa \(L_2\) thích nghi (Adaptive \(L_2\))&lt;/strong&gt;:
Trên mô hình hồi quy tuyến tính, kỳ vọng của hàm mất mát có Dropout tương đương chính xác với hàm mất mát chuẩn cộng thêm số hạng phạt \(L_2\) được cân theo phương sai của từng đặc trưng đầu vào!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hành vi theo tỷ lệ tắt \(p\) (Underfitting vs. Overfitting)&lt;/strong&gt;:
\(p = 0\) là không chính quy hóa; \(p \in [0{,}1, 0{,}5]\) là vùng hiệu quả nhất; khi \(p \to 0{,}8\text{–}0{,}9\), mạng mất quá nhiều dung lượng nên rơi vào &lt;em&gt;underfitting&lt;/em&gt; và thời gian hội tụ kéo dài gấp bội.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Monte Carlo (MC) Dropout — Ước lượng độ bất định khi suy luận&lt;/strong&gt;:
Nếu cố ý bật Dropout ở chế độ suy luận và chạy \(K\) lần forward trên cùng một ảnh, phương sai của \(K\) dự đoán cho biết mô hình đang “tự tin” hay “đoán mò” (rất hữu ích trong y khoa và xe tự lái).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-chứng-minh-bằng-số-mối-liên-hệ-giữa-dropout-và-phạt-l_2-trên-hồi-quy-tuyến-tính-1-chiều&quot;&gt;Giải thích: Chứng minh bằng số mối liên hệ giữa Dropout và Phạt \(L_2\) trên hồi quy tuyến tính 1 chiều&lt;/h3&gt;

&lt;p&gt;Xét dự đoán tuyến tính với đầu vào \(x = 3\), trọng số \(w\), nhãn \(y = 6\). Khi áp Inverted Dropout với xác suất giữ \(q = 1 - p = 0{,}5\), đầu vào ngẫu nhiên là \(\tilde{x} = \frac{m}{q} x\) (nhận giá trị \(6\) với xác suất \(0{,}5\) và \(0\) với xác suất \(0{,}5\)).&lt;/p&gt;

&lt;p&gt;Tính kỳ vọng hàm mất mát bình phương \(\mathbb{E}\!\left[(y - w\tilde{x})^2\right]\):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Khi \(m = 1\) (xác suất 0,5)&lt;/strong&gt;: \(\tilde{x} = 6 \implies (6 - 6w)^2 = 36 - 72w + 36w^2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khi \(m = 0\) (xác suất 0,5)&lt;/strong&gt;: \(\tilde{x} = 0 \implies (6 - 0)^2 = 36\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lấy kỳ vọng trung bình&lt;/strong&gt;:
\(\mathbb{E}[\mathcal{L}] = 0{,}5(36 - 72w + 36w^2) + 0{,}5(36) = 36 - 36w + 18w^2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tách phần mất mát gốc \((6 - 3w)^2 = 36 - 36w + 9w^2\)&lt;/strong&gt;:
\(\mathbb{E}[\mathcal{L}] = \underbrace{(6 - 3w)^2}_{\text{Mất mát gốc}} + \underbrace{9 w^2}_{\frac{1-q}{q} x^2 w^2}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nhìn vào số hạng dư \(+ 9w^2\): Dropout tự động sinh ra một &lt;strong&gt;số hạng phạt \(L_2\)&lt;/strong&gt; có trọng số tỷ lệ thuận với \(\frac{p}{1-p} x^2\) mà không cần viết tường minh trong hàm loss!&lt;/p&gt;

&lt;h1 id=&quot;dropout-hạn-chế-quá-khớp-bằng-vô-hiệu-hóa-ngẫu-nhiên&quot;&gt;Dropout: Hạn chế quá khớp bằng vô hiệu hóa ngẫu nhiên&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/0/04/Dropout_Neural_Net_Model.svg/800px-Dropout_Neural_Net_Model.svg.png&quot; alt=&quot;Dropout Visualization&quot; /&gt;
&lt;em&gt;Hình ảnh: Minh họa kỹ thuật Dropout trong mạng neuron. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Dropout&lt;/strong&gt; là kỹ thuật chính quy hóa hoạt động bằng cách tạm thời vô hiệu hóa ngẫu nhiên (đặt giá trị đầu ra về 0) một tỷ lệ neuron trong quá trình huấn luyện. Cách làm đơn giản này giúp giảm quá khớp và là một trong những kỹ thuật chính quy hóa phổ biến nhất trong học sâu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Các lợi ích chính của Dropout:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hạn chế đồng thích nghi (&lt;em&gt;co-adaptation&lt;/em&gt;)&lt;/strong&gt;: buộc các neuron học những đặc trưng độc lập hơn thay vì phụ thuộc cố định vào nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tạo hiệu ứng tổ hợp (&lt;em&gt;ensemble&lt;/em&gt;)&lt;/strong&gt;: mỗi bước huấn luyện cập nhật một mạng con khác nhau, tương tự huấn luyện nhiều mạng con chia sẻ trọng số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dễ cài đặt&lt;/strong&gt;: chỉ cần vài dòng mã và có sẵn trong mọi thư viện học sâu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cải thiện tổng quát hóa&lt;/strong&gt;: giúp giảm sai số trên tập kiểm định khi mô hình có dung lượng lớn.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ý tưởng cốt lõi:&lt;/strong&gt; Khi các neuron bị loại bỏ ngẫu nhiên trong quá trình huấn luyện, mạng không thể dựa quá nhiều vào một vài đơn vị cụ thể, mà phải học các biểu diễn phân tán và bền vững hơn. Có thể liên hệ với một đội bóng trong đó các cầu thủ luân phiên vắng mặt trong buổi tập: mỗi thành viên buộc phải rèn kỹ năng độc lập thay vì chỉ phối hợp cố định với một đồng đội duy nhất.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;
&lt;h3 id=&quot;dropout-trong-quá-trình-huấn-luyện&quot;&gt;Dropout trong quá trình huấn luyện&lt;/h3&gt;

&lt;p&gt;Xét một tầng có vectơ kích hoạt \(\mathbf{a}\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 1: Sinh mặt nạ nhị phân&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{m}_i \sim \text{Bernoulli}(1-p)\]

&lt;p&gt;trong đó \(p\) là tỷ lệ dropout (xác suất vô hiệu hóa mỗi neuron).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 2: Áp mặt nạ và chia tỉ lệ&lt;/strong&gt; (&lt;em&gt;inverted dropout&lt;/em&gt;):&lt;/p&gt;

\[\mathbf{a}_{\text{dropout}} = \frac{\mathbf{m} \odot \mathbf{a}}{1-p}\]

&lt;p&gt;trong đó \(\odot\) là phép nhân theo từng phần tử.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lý do chia cho \((1-p)\):&lt;/strong&gt; Để bảo toàn giá trị kỳ vọng của kích hoạt giữa huấn luyện và suy luận:&lt;/p&gt;

\[\mathbb{E}[\mathbf{a}_{\text{dropout}}] = \mathbb{E}\left[\frac{\mathbf{m} \odot \mathbf{a}}{1-p}\right] = \mathbf{a}\]

&lt;h3 id=&quot;dropout-khi-suy-luận-kiểm-tra&quot;&gt;Dropout khi suy luận (kiểm tra)&lt;/h3&gt;

&lt;p&gt;Khi đánh giá hoặc suy luận, toàn bộ các neuron đều được giữ lại và không cần nhân thêm hệ số nào vì bước chia tỉ lệ đã được thực hiện sẵn trong lúc huấn luyện:&lt;/p&gt;

\[\mathbf{a}_{\text{test}} = \mathbf{a}\]

&lt;h3 id=&quot;diễn-giải-toán-học&quot;&gt;Diễn giải toán học&lt;/h3&gt;

&lt;p&gt;Với tầng có \(n\) neuron, dropout xấp xỉ quá trình huấn luyện tổ hợp gồm \(2^n\) mạng con chia sẻ trọng số: mỗi bước cập nhật tác động lên một mạng con ngẫu nhiên, còn khi suy luận toàn mạng đóng vai trò xấp xỉ trung bình của tất cả các mạng con đó mà không phải huấn luyện riêng lẻ từng mô hình.&lt;/p&gt;

&lt;h3 id=&quot;tóm-tắt-hành-vi-theo-tỷ-lệ-p&quot;&gt;Tóm tắt hành vi theo tỷ lệ \(p\)&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Tỷ lệ phần tử bị đặt về 0 khi huấn luyện: \(p\).&lt;/li&gt;
  &lt;li&gt;Hệ số nhân cho các phần tử giữ lại: \(\frac{1}{1-p}\).&lt;/li&gt;
  &lt;li&gt;Giá trị kỳ vọng đầu ra: bằng đầu ra khi không áp dụng dropout.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;h3 id=&quot;ví-dụ-minh-họa&quot;&gt;Ví dụ minh họa&lt;/h3&gt;

&lt;p&gt;Giả sử một tầng ẩn có 4 neuron với tỷ lệ dropout \(p = 0.5\) (50%):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước huấn luyện 1:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Kích hoạt ban đầu: \([2.0, 3.5, 1.2, 4.1]\)&lt;/li&gt;
  &lt;li&gt;Mặt nạ ngẫu nhiên: \([0, 1, 1, 0]\)&lt;/li&gt;
  &lt;li&gt;Sau inverted dropout (nhân 2): \([0, 7.0, 2.4, 0]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Bước huấn luyện 2:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Kích hoạt ban đầu: \([2.0, 3.5, 1.2, 4.1]\)&lt;/li&gt;
  &lt;li&gt;Mặt nạ ngẫu nhiên: \([1, 0, 1, 1]\)&lt;/li&gt;
  &lt;li&gt;Sau inverted dropout (nhân 2): \([4.0, 0, 2.4, 8.2]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Khi kiểm tra:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Kích hoạt giữ nguyên: \([2.0, 3.5, 1.2, 4.1]\) (toàn bộ 4 neuron đều hoạt động).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;minh-họa-trực-quan&quot;&gt;Minh họa trực quan&lt;/h3&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Huấn luyện (dropout=0.5):
    Input → [X  ✓  ✓  X] → Output
            ↓  ↓  ↓  ↓
         (loại bỏ) (đã scale)

Kiểm tra (không dropout):
    Input → [✓  ✓  ✓  ✓] → Output
            ↓  ↓  ↓  ↓
           (tất cả hoạt động)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;cơ-chế-ngăn-đồng-thích-nghi&quot;&gt;Cơ chế ngăn đồng thích nghi&lt;/h3&gt;

&lt;p&gt;Khi &lt;strong&gt;không có dropout&lt;/strong&gt;, giả sử Neuron A chuyên phát hiện “mắt” và Neuron B luôn dựa vào đầu ra của Neuron A; nếu Neuron A dự đoán sai, Neuron B cũng sai theo. Khi &lt;strong&gt;có dropout&lt;/strong&gt;, Neuron A đôi khi bị vô hiệu hóa, buộc Neuron B phải tự học các tín hiệu bổ trợ để vẫn hoạt động ổn định, nhờ đó cả hai hình thành các đặc trưng độc lập và bền vững hơn.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=D8PJAL-MZv8&quot;&gt;Dropout Regularization (C2W1L06)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Giải thích chi tiết cơ chế mặt nạ khi huấn luyện và hệ số chia tỉ lệ inverted dropout.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Làm rõ vì sao giảm phương sai giúp cải thiện tổng quát hóa.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=6g0t3Phly2M&quot;&gt;Regularization (C2W1L04)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Đặt dropout trong bức tranh chung cùng các kỹ thuật chính quy hóa khác.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09 Kỹ thuật Chính quy hóa</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter09/09_00_Introduction</id>
   <content type="html">&lt;p&gt;Một mạng neuron sâu có hàng triệu tham số mạnh đến mức Chiyuan Zhang và cộng sự (2017) đã chứng minh một sự thật gây sốc: nó có thể &lt;strong&gt;học thuộc lòng 100% nhãn ngẫu nhiên&lt;/strong&gt; (ảnh con chó bị gán bừa thành máy bay) mà mất mát huấn luyện vẫn về 0! Chính vì mạng quá dễ “học vẹt” như vậy, nghệ thuật huấn luyện Deep Learning thực thụ không chỉ là làm giảm sai số huấn luyện, mà là áp đặt &lt;strong&gt;chính quy hóa (Regularization)&lt;/strong&gt; và &lt;strong&gt;chuẩn hóa (Normalization)&lt;/strong&gt; để ép mô hình nắm bắt quy luật tổng quát thay vì nhiễu.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-chính-quy-hóa-và-chuẩn-hóa&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Chính quy hóa và Chuẩn hóa&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đánh đổi Thiên lệch – Phương sai (Bias–Variance Trade-off)&lt;/strong&gt;:
Chính quy hóa chủ động đặt thêm ràng buộc hoặc nhiễu có kiểm soát trong lúc huấn luyện để chấp nhận tăng nhẹ sai số trên tập train, đổi lấy mức giảm lớn trên tập kiểm định (validation/test).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dropout — Phá vỡ sự đồng thích nghi (Co-adaptation)&lt;/strong&gt;:
Tắt ngẫu nhiên một tỷ lệ \(p\) neuron ở mỗi bước huấn luyện, buộc mạng không được dựa dẫm vào vài đường đi “tủ” mà phải phân tán tri thức ra nhiều đặc trưng dự phòng độc lập.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Batch Normalization và họ Chuẩn hóa (LayerNorm, GroupNorm, InstanceNorm)&lt;/strong&gt;:
Ổn định phân phối giá trị kích hoạt giữa các tầng, làm mịn bề mặt hàm mất mát để cho phép dùng tốc độ học lớn hơn và hội tụ nhanh hơn hẳn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hệ sinh thái Chính quy hóa Toàn diện&lt;/strong&gt;:
Kết hợp đồng bộ Weight Decay (L2), Data Augmentation (Mixup/CutMix), Label Smoothing, Early Stopping và DropPath tùy theo kiến trúc (CNN hay Transformer).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-hiệu-ứng-co-trọng-số-của-chính-quy-hóa-l_2-weight-decay-sau-1-bước-cập-nhật&quot;&gt;Giải thích: Tính tay hiệu ứng co trọng số của Chính quy hóa \(L_2\) (Weight Decay) sau 1 bước cập nhật&lt;/h3&gt;

&lt;p&gt;Xét hàm mất mát có thêm số hạng phạt \(L_2\): \(\mathcal{L}_{\text{reg}}(w) = \mathcal{L}(w) + \frac{\lambda}{2} w^2\). Giả sử tại bước hiện tại, trọng số \(w = 2{,}0\), gradient dữ liệu \(\nabla \mathcal{L}(w) = 0{,}5\), tốc độ học \(\eta = 0{,}1\) và hệ số phạt \(\lambda = 0{,}2\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Gradient tổng hợp&lt;/strong&gt;:
\(\nabla \mathcal{L}_{\text{reg}}(w) = \nabla \mathcal{L}(w) + \lambda w = 0{,}5 + (0{,}2)(2{,}0) = \mathbf{0{,}90}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Cập nhật trọng số&lt;/strong&gt;:
\(w_{\text{new}} = w - \eta \nabla \mathcal{L}_{\text{reg}}(w) = 2{,}0 - 0{,}1(0{,}90) = \mathbf{1{,}91}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Viết lại dưới dạng phân rã trọng số (Weight Decay)&lt;/strong&gt;:
\(w_{\text{new}} = (1 - \eta \lambda) w - \eta \nabla \mathcal{L}(w) = (1 - 0{,}02)(2{,}0) - 0{,}05 = 1{,}96 - 0{,}05 = \mathbf{1{,}91}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mỗi bước lặp, \(L_2\) âm thầm nhân trọng số với hệ số \(0{,}98 &amp;lt; 1\) để kéo các trọng số lớn không cần thiết về gần \(0\), ngăn mô hình “gồng” trọng số quá lớn để khớp nhiễu!&lt;/p&gt;

&lt;p&gt;Chính quy hóa (&lt;em&gt;regularization&lt;/em&gt;) giúp hạn chế hiện tượng quá khớp (&lt;em&gt;overfitting&lt;/em&gt;) bằng cách kiểm soát độ phức tạp hiệu dụng của mô hình. Chương này trình bày các kỹ thuật nền tảng gồm chính quy hóa L1/L2, dropout, chuẩn hóa theo lô (&lt;em&gt;batch normalization&lt;/em&gt;), tăng cường dữ liệu (&lt;em&gt;data augmentation&lt;/em&gt;) và dừng sớm (&lt;em&gt;early stopping&lt;/em&gt;) nhằm cải thiện khả năng tổng quát hóa trên dữ liệu mới.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau phần dropout và BatchNorm, bạn có thể đọc thêm bài &lt;strong&gt;09-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về SAM, DropPath và cách các mô hình nền tảng hiện nay thực hiện chính quy hóa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (luyện phỏng vấn):&lt;/strong&gt; Bài &lt;strong&gt;09-98 Luyện phỏng vấn&lt;/strong&gt; cung cấp các câu hỏi tự luyện về overfitting, dropout và BatchNorm; bạn có thể kết hợp với tài liệu &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) để tham khảo thêm bộ câu hỏi có lời giải.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=DEMmkFC6IGM&quot;&gt;Overfitting in a Neural Network explained&lt;/a&gt; — deeplizard (tiếng Anh). Giải thích hiện tượng quá khớp — vấn đề trọng tâm mà chương này giải quyết.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Trình bày khái niệm độ chệch (bias) và phương sai (variance) làm khung phân tích xuyên suốt chương.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=6g0t3Phly2M&quot;&gt;Regularization (C2W1L04)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Tổng quan các kỹ thuật chính quy hóa (như weight decay và các phương pháp liên quan) trước khi đi vào từng bài chi tiết.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Nếu đem sơ đồ khối Transformer gốc năm 2017 đặt cạnh một mô hình ngôn ngữ lớn hiện đại giai đoạn 2024–2026 như &lt;strong&gt;Llama 3&lt;/strong&gt;, &lt;strong&gt;Qwen 2.5&lt;/strong&gt;, &lt;strong&gt;DeepSeek&lt;/strong&gt; hay &lt;strong&gt;Gemma 2&lt;/strong&gt;, bạn sẽ thấy bộ khung tổng thể vẫn gần như nguyên vẹn — nhưng gần như &lt;strong&gt;mọi linh kiện bên trong&lt;/strong&gt; đều đã được tinh chỉnh sắc bén hơn để huấn luyện ổn định hơn ở quy mô nghìn tỷ token và suy luận nhanh hơn trên phần cứng thực tế.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nâng-cấp-tiêu-chuẩn-của-khối-transformer-hiện-đại-20222026&quot;&gt;Kiến thức cần nhớ: Bốn nâng cấp tiêu chuẩn của Khối Transformer Hiện đại (2022–2026)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;RMSNorm + Pre-LN thay cho Post-LN LayerNorm&lt;/strong&gt;:
RMSNorm bỏ bước trừ giá trị trung bình (chỉ chia cho căn trung bình bình phương \(\text{RMS}(x)\)), giảm ~10–15% chi phí tính toán chuẩn hóa mà chất lượng và độ ổn định tương đương LayerNorm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;RoPE (Rotary Position Embedding) thay cho Sinusoidal/Learned PE&lt;/strong&gt;:
Thay vì cộng vector vị trí ở tầng đầu, RoPE &lt;strong&gt;xoay&lt;/strong&gt; trực tiếp các cặp tọa độ của vector \(Q\) và \(K\) theo góc tỷ lệ với vị trí \(m, n\) — khiến tích vô hướng \(q_m^T k_n\) chỉ phụ thuộc vào &lt;strong&gt;khoảng cách tương đối&lt;/strong&gt; \((m - n)\) và dễ ngoại suy sang ngữ cảnh dài hơn!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SwiGLU thay cho FFN + ReLU cổ điển&lt;/strong&gt;:
Thêm nhánh cổng nhân (gating): \(\text{SwiGLU}(x) = (\text{SiLU}(x W_1) \odot (x W_3)) W_2\). Vì có 3 ma trận thay vì 2, chiều ẩn trung gian thường lấy \(\frac{8}{3} d_{\text{model}}\) thay vì \(4 d_{\text{model}}\) để giữ nguyên tổng số tham số mà độ chính xác tăng rõ rệt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mixture of Experts (MoE) và Transformer Đa phương thức (Multimodal)&lt;/strong&gt;:
Thay 1 khối FFN đặc bằng nhiều chuyên gia (ví dụ 8–64 experts) nhưng chỉ kích hoạt Top-2 chuyên gia cho mỗi token (như Mixtral, DeepSeek-V3), cho phép mở rộng dung lượng tri thức lên hàng trăm tỷ tham số trong khi chi phí suy luận chỉ bằng mô hình cỡ nhỏ.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-phép-xoay-vị-trí-rope-2-chiều-để-thấy-tính-bất-biến-khoảng-cách-tương-đối&quot;&gt;Giải thích: Tính tay phép xoay vị trí RoPE 2 chiều để thấy tính bất biến khoảng cách tương đối&lt;/h3&gt;

&lt;p&gt;Xét vector 2D \(\mathbf{q} = [1, 0]^T\) đặt ở vị trí \(m\) và \(\mathbf{k} = [1, 0]^T\) đặt ở vị trí \(n\), với góc xoay cơ sở \(\theta = 30^\circ\). Ma trận xoay RoPE ở vị trí \(t\) là \(R(t\theta) = \begin{bmatrix} \cos t\theta &amp;amp; -\sin t\theta \\ \sin t\theta &amp;amp; \cos t\theta \end{bmatrix}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Trường hợp 1 (\(m = 1, \; n = 2\), khoảng cách \(n - m = 1\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;
\[\tilde{\mathbf{q}}_1 = R(30^\circ)\mathbf{q} = [\cos 30^\circ, \; \sin 30^\circ]^T = [0{,}866, \; 0{,}500]^T\]
      &lt;/li&gt;
      &lt;li&gt;
\[\tilde{\mathbf{k}}_2 = R(60^\circ)\mathbf{k} = [\cos 60^\circ, \; \sin 60^\circ]^T = [0{,}500, \; 0{,}866]^T\]
      &lt;/li&gt;
      &lt;li&gt;Tích vô hướng: \(\tilde{\mathbf{q}}_1^T \tilde{\mathbf{k}}_2 = (0{,}866)(0{,}500) + (0{,}500)(0{,}866) = \mathbf{0{,}866} = \cos(30^\circ)\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trường hợp 2 (dịch cả hai từ xuống cuối đoạn văn: \(m = 10, \; n = 11\), vẫn cách nhau \(1\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(\tilde{\mathbf{q}}_{10}^T \tilde{\mathbf{k}}_{11} = \mathbf{q}^T R(10\theta)^T R(11\theta) \mathbf{k} = \mathbf{q}^T R((11 - 10)\theta) \mathbf{k} = \cos(30^\circ) = \mathbf{0{,}866}\)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Dù hai từ đứng ở đầu hay ở tận cuối một tài liệu dài 100.000 từ, điểm chú ý RoPE giữa chúng vẫn &lt;strong&gt;chỉ phụ thuộc vào khoảng cách tương đối \(n - m\)&lt;/strong&gt; — một tính chất hình học tuyệt đẹp!&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-từ-khối-transformer-gốc-đến-hệ-thống-llm-hiện-đại&quot;&gt;Tùy chọn: Từ khối Transformer gốc đến hệ thống LLM hiện đại&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết encoder/decoder hay mã hóa vị trí. Nội dung đối chiếu khối Transformer năm 2017 với cấu trúc LLM giai đoạn 2022–2026 gồm RoPE, KV-cache, mô hình trọng số mở và hạ tầng phục vụ.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Mỗi tầng Transformer vẫn giữ cấu trúc cốt lõi: trao đổi thông tin qua attention rồi biến đổi cục bộ qua MLP. Từ cuối năm 2022 sau sự xuất hiện của ChatGPT, khối kiến trúc này trở thành nền tảng phổ biến cho xử lý ngôn ngữ, sinh mã nguồn và nhiều hệ thống đa phương thức.&lt;/p&gt;

&lt;h2 id=&quot;1-những-thay-đổi-chính-trong-khối-kiến-trúc&quot;&gt;1. Những thay đổi chính trong khối kiến trúc&lt;/h2&gt;

&lt;p&gt;Phần lớn mô hình ngôn ngữ chỉ-decoder hiện nay (từ GPT-2 đến Llama, Mistral, Qwen, Gemma) cập nhật một số chi tiết quan trọng:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;RoPE&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2104.09864&quot;&gt;Su et al., 2021/2023&lt;/a&gt;) thay thế mã hóa vị trí sin–cos tuyệt đối cộng ở đầu vào.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pre-norm kết hợp RMSNorm và SwiGLU&lt;/strong&gt; (xem bài tùy chọn Chương 02).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GQA và FlashAttention&lt;/strong&gt; (xem bài tùy chọn Chương 07).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;KV-cache khi giải mã&lt;/strong&gt;: lưu lại key/value của các token \(1..t-1\) để mỗi token mới chỉ tốn \(O(t)\) thay vì tính lại \(O(t^2)\) từ đầu.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;RoPE xoay từng cặp chiều của query và key một góc \(\theta_i t\) theo vị trí \(t\):&lt;/p&gt;

\[\begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}
\leftarrow
\begin{pmatrix} \cos(t\theta_i) &amp;amp; -\sin(t\theta_i) \\ \sin(t\theta_i) &amp;amp; \cos(t\theta_i) \end{pmatrix}
\begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}.\]

&lt;p&gt;Mã hóa vị trí sin–cos trong bài lý thuyết vẫn là nền tảng đúng về mặt nguyên lý; RoPE là biến thể chuẩn trong các mô hình LLM giai đoạn 2024–2026.&lt;/p&gt;

&lt;h2 id=&quot;2-các-ứng-dụng-và-hệ-sinh-thái-tiêu-biểu&quot;&gt;2. Các ứng dụng và hệ sinh thái tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;mô-hình-ngôn-ngữ-nền-tảng-trọng-số-mở&quot;&gt;Mô hình ngôn ngữ nền tảng trọng số mở&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2302.13971&quot;&gt;LLaMA&lt;/a&gt;, &lt;a href=&quot;https://arxiv.org/abs/2307.09288&quot;&gt;Llama 2&lt;/a&gt;, Llama 3, &lt;a href=&quot;https://arxiv.org/abs/2310.06825&quot;&gt;Mistral 7B&lt;/a&gt;, Qwen2 và Gemma 2 là các kiến trúc chỉ-decoder tham chiếu phổ biến; các phiên bản tinh chỉnh theo chỉ dẫn (&lt;em&gt;instruction-tuned&lt;/em&gt;) thường được dùng trực tiếp trong ứng dụng thực tế.&lt;/p&gt;

&lt;h3 id=&quot;hệ-thống-phục-vụ-và-suy-luận-cục-bộ&quot;&gt;Hệ thống phục vụ và suy luận cục bộ&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt; — ghép batch liên tục (&lt;em&gt;continuous batching&lt;/em&gt;) kết hợp PagedAttention.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;llama.cpp&lt;/a&gt; — suy luận mô hình lượng tử hóa định dạng GGUF trên CPU và Apple Silicon.&lt;/li&gt;
  &lt;li&gt;Giải mã suy đoán (&lt;em&gt;Speculative decoding&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Leviathan et al., 2023&lt;/a&gt;) — mô hình nhỏ dự đoán trước nhiều token để mô hình lớn kiểm chứng song song.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;transformer-đa-phương-thức&quot;&gt;Transformer đa phương thức&lt;/h3&gt;

&lt;p&gt;Các hệ thống kết hợp Vision Transformer (ViT) với decoder ngôn ngữ (như LLaVA năm 2023 và các mô hình dòng GPT-4V) áp dụng cùng cấu trúc khối Transformer lên chuỗi mảng ảnh (&lt;em&gt;image patches&lt;/em&gt;).&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-phần-mềm-phổ-biến&quot;&gt;3. Thư viện và phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/transformers&quot;&gt;Hugging Face transformers&lt;/a&gt; — định nghĩa kiến trúc mô hình và giao diện &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;generate()&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt; và &lt;a href=&quot;https://github.com/sgl-project/sglang&quot;&gt;SGLang&lt;/a&gt; — hệ thống phục vụ suy luận thông lượng cao.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;llama.cpp&lt;/a&gt; — chạy mô hình GGUF cục bộ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2302.13971&quot;&gt;LLaMA (Touvron et al., 2023)&lt;/a&gt; và &lt;a href=&quot;https://arxiv.org/abs/2307.09288&quot;&gt;Llama 2 (2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2310.06825&quot;&gt;Mistral 7B (Jiang et al., 2023)&lt;/a&gt; — kết hợp sliding-window attention và GQA.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2104.09864&quot;&gt;RoFormer / RoPE (Su et al.)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Speculative Decoding (Leviathan et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-vai-trò-bổ-trợ-cho-nội-dung-cốt-lõi&quot;&gt;5. Vai trò bổ trợ cho nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên hoàn thành phần suy diễn encoder–decoder và cài đặt Transformer nhỏ bằng PyTorch trước. Bài đọc thêm này kết nối các khái niệm đó với &lt;strong&gt;hệ thống LLM thực tế&lt;/strong&gt;. Chi tiết công thức, sơ đồ khối RMSNorm → attention + RoPE → SwiGLU cùng ước lượng tham số và FLOP được trình bày trong bài &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown (tiếng Anh). Ôn lại khung khối Transformer chuẩn mà các mô hình hiện đại vẫn kế thừa.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How might LLMs store facts&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 7](https://www.youtube.com/watch?v=9-Jl0dxWQs8) — 3Blue1Brown (tiếng Anh). Góc nhìn về vai trò lưu trữ tri thức của khối MLP trong các mô hình decoder hiện đại.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=gBMO1JZav44&quot;&gt;How FlashAttention Accelerates Generative AI Revolution&lt;/a&gt; — Jia-Bin Huang (tiếng Anh). Giải thích FlashAttention dưới góc độ tối ưu hóa hệ thống mà không thay đổi công thức attention.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-02 Transformer Explainer</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_02_Transformer_Explainer/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_02_Transformer_Explainer</id>
   <content type="html">&lt;p&gt;Đọc công thức GPT-2 trên giấy giống như đọc bản vẽ kiến trúc của một tòa nhà, còn tương tác trực tiếp với &lt;strong&gt;Transformer Explainer&lt;/strong&gt; (công cụ trực quan hóa chạy ngay GPT-2 trong trình duyệt của nhóm nghiên cứu Georgia Tech) giống như bước thẳng vào bên trong tòa nhà đó và nhìn dòng điện chạy qua từng dây dẫn: từ lúc một câu tiếng Anh bị cắt thành token, đi qua 12 tầng Multi-Head Attention và MLP, cho tới khi biến thành xác suất chọn từ tiếp theo!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-chặng-quan-sát-cốt-lõi-trên-transformer-explainer&quot;&gt;Kiến thức cần nhớ: Bốn chặng quan sát cốt lõi trên Transformer Explainer&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Từ văn bản thô sang Token ID và Vector Embedding + Vị trí&lt;/strong&gt;:
Thấy trực tiếp cách bộ tách từ BPE (Byte-Pair Encoding) chia từ hiếm thành nhiều mảnh (&lt;em&gt;subwords&lt;/em&gt;) và cộng vector ngữ nghĩa với vector vị trí thành đầu vào &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;768&lt;/code&gt; chiều của GPT-2 Small.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dòng chảy Q, K, V và bản đồ chú ý nhân quả trên 12 Head&lt;/strong&gt;:
Nhìn thấy rõ ràng đường chéo tam giác dưới của Causal Self-Attention: mỗi token chỉ nối dây về các token đứng trước nó, và các head khác nhau tạo ra các đường nối sáng đậm ở những từ hoàn toàn khác nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vai trò mở rộng \(4\times\) của khối MLP (768 \(\to\) 3072 \(\to\) 768)&lt;/strong&gt;:
Quan sát quá trình biến đổi phi tuyến qua GELU tinh chỉnh biểu diễn của từng token sau khi đã thu thập ngữ cảnh từ Attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Logits \(\to\) Temperature \(\to\) Top-k / Top-p (Nucleus) Sampling&lt;/strong&gt;:
Thấy ngay trong thời gian thực: chỉ cần kéo thanh trượt Temperature hoặc Top-p, danh sách các từ ứng viên tiếp theo lập tức co gọn (chính xác, ít bất ngờ) hoặc giãn rộng (sáng tạo, đa dạng).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-bước-lọc-top-p-nucleus-sampling-với-p--080&quot;&gt;Giải thích: Tính tay bước lọc Top-p (Nucleus Sampling) với \(p = 0{,}80\)&lt;/h3&gt;

&lt;p&gt;Giả sử sau khi qua &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softmax&lt;/code&gt; (tại nhiệt độ \(\tau = 1{,}0\)), GPT-2 gán xác suất cho 5 từ ứng viên đứng đầu (đã sắp xếp giảm dần) như sau:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Thứ hạng&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Từ ứng viên&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Xác suất gốc \(P(w)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Xác suất tích lũy&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Giữ lại với Top-p (\(p=0{,}80\))?&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Xác suất sau chuẩn hóa lại&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;data&quot;&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}45\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}45\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Giữ&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}45 / 0{,}85 = \mathbf{52{,}9\%}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;models&quot;&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}25\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}70\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Giữ&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}25 / 0{,}85 = \mathbf{29{,}4\%}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;learning&quot;&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}15\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}85 \ge 0{,}80\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Giữ&lt;/strong&gt; (đạt ngưỡng!)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}15 / 0{,}85 = \mathbf{17{,}6\%}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;4&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;pizza&quot;&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}10\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}95\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Loại bỏ&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0\%\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;5&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;cloud&quot;&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}05\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1{,}00\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;Loại bỏ&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0\%\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Top-p tự động co nhóm ứng viên lại khi mô hình đã rất chắc chắn (đôi khi chỉ giữ 1–2 từ) và mở rộng nhóm khi có nhiều câu trả lời hợp lý — khắc phục nhược điểm cứng nhắc của Top-k cố định!&lt;/p&gt;

&lt;h1 id=&quot;transformer-explainer&quot;&gt;Transformer Explainer&lt;/h1&gt;

&lt;p&gt;Các phương trình trong chương này mô tả &lt;em&gt;những gì Transformer tính toán&lt;/em&gt;, còn &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; cho phép bạn &lt;em&gt;quan sát trực tiếp&lt;/em&gt; các phép tính đó trên một mô hình ngôn ngữ thực tế mà không cần cài đặt hay dùng GPU. Công cụ chạy trực tiếp trên trình duyệt mô hình &lt;strong&gt;GPT-2 (small)&lt;/strong&gt; (124 triệu tham số, 12 khối Transformer xếp chồng), nên mọi con số hiển thị đều là kết quả truyền xuôi thật từ prompt bạn nhập.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_summary.png&quot; alt=&quot;Tổng quan Transformer Explainer&quot; /&gt;
&lt;em&gt;Giao diện tương tác: prompt được tách token, sau đó đi qua embedding, multi-head self-attention và MLP. Nguồn: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (giấy phép MIT).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Bạn nên mở công cụ trước rồi dùng bài này như tài liệu hướng dẫn đối chiếu:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Demo trực tiếp:&lt;/strong&gt; &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;poloclub.github.io/transformer-explainer&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mã nguồn:&lt;/strong&gt; &lt;a href=&quot;https://github.com/poloclub/transformer-explainer&quot;&gt;github.com/poloclub/transformer-explainer&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài báo (CHI 2026):&lt;/strong&gt; &lt;a href=&quot;https://doi.org/10.1145/3772318.3791725&quot;&gt;Cho et al., “Transformer Explainer…”&lt;/a&gt; (&lt;a href=&quot;https://poloclub.github.io/papers/26-chi-transformer-explainer.pdf&quot;&gt;PDF&lt;/a&gt;, &lt;a href=&quot;https://arxiv.org/abs/2408.04619&quot;&gt;arXiv:2408.04619&lt;/a&gt;)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Video demo:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=TFUc41G2ikY&quot;&gt;YouTube&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Do giao diện được thiết kế để tương tác toàn màn hình (di chuột xem trọng số attention, mở rộng từng tầng, kéo thanh trượt), khóa học dẫn liên kết trực tiếp tới trang demo thay vì nhúng vào khung nhỏ.&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;GPT-2 là Transformer &lt;strong&gt;chỉ có decoder&lt;/strong&gt;: mô hình dự đoán token tiếp theo dựa trên toàn bộ các token đứng bên trái. Kiến trúc này gọn hơn sơ đồ encoder–decoder trong &lt;em&gt;“Attention Is All You Need”&lt;/em&gt; (vốn có thêm self-attention phía encoder và cross-attention giữa hai phía), nhưng vẫn giữ nguyên các khối cơ bản:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Embedding&lt;/strong&gt; — ánh xạ token thành vectơ và cộng thêm tín hiệu vị trí.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các khối Transformer&lt;/strong&gt; — mỗi khối gồm &lt;strong&gt;self-attention&lt;/strong&gt; đa đầu (trao đổi thông tin giữa các vị trí) tiếp nối bởi &lt;strong&gt;MLP&lt;/strong&gt; (biến đổi cục bộ từng vị trí), đi kèm kết nối phần dư (&lt;em&gt;residual&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất đầu ra&lt;/strong&gt; — lớp tuyến tính kết hợp softmax chuyển trạng thái ẩn cuối thành phân phối xác suất trên toàn bộ từ vựng để lấy mẫu token kế tiếp.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;GPT-2 (small) sử dụng bộ từ vựng 50.257 token và chiều embedding 768. Cả 12 khối đều có cùng cấu trúc; giao diện thường mở chi tiết &lt;strong&gt;Block 1&lt;/strong&gt; và chú thích 11 khối còn lại phía sau. Mô hình trong trình duyệt được chuyển đổi từ nanoGPT của Andrej Karpathy và chạy qua ONNX Runtime, giúp các giá trị cập nhật tức thì khi bạn đổi prompt hoặc điều chỉnh tham số lấy mẫu.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_teaser.jpg&quot; alt=&quot;Hình teaser có chú thích của toàn bộ giao diện&quot; /&gt;
&lt;em&gt;Hình tổng quan giao diện chính thức (đã điều chỉnh kích thước cho trang khóa học): (A) nhập prompt và sinh token kế tiếp; (B) điều chỉnh nhiệt độ và chế độ lấy mẫu; (C) mở rộng chi tiết phép tính attention (tích vô hướng, chia tỉ lệ kèm mask nhân quả, softmax). Nguồn: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (giấy phép MIT).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-ý-nghĩa-từng-phần-trên-giao-diện&quot;&gt;2. Ý nghĩa từng phần trên giao diện&lt;/h2&gt;

&lt;h3 id=&quot;embedding-tách-token-và-mã-hóa-vị-trí&quot;&gt;Embedding, tách token và mã hóa vị trí&lt;/h3&gt;

&lt;p&gt;Khi mở cột &lt;strong&gt;Embedding&lt;/strong&gt;, prompt trước tiên được tách thành các token con (&lt;em&gt;subword&lt;/em&gt;): những từ phổ biến như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Data&lt;/code&gt; hay &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;visualization&lt;/code&gt; giữ nguyên một token, trong khi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;empowers&lt;/code&gt; được tách thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;em&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;powers&lt;/code&gt;. Mỗi token ứng với một chỉ số nguyên và một vectơ &lt;strong&gt;token embedding&lt;/strong&gt; 768 chiều đã học.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_embedding.png&quot; alt=&quot;Embedding: token, token embedding và mã hóa vị trí&quot; /&gt;
&lt;em&gt;Bốn bước embedding cho prompt “Data visualization empowers users to”: (1) tách token, (2) tra cứu token embedding theo id, (3) mã hóa vị trí, (4) cộng hai vectơ. Nguồn: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (giấy phép MIT).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mã hóa vị trí được cộng trực tiếp thay vì ghép nối.&lt;/strong&gt; Khác với bảng sin–cos cố định của Transformer gốc, GPT-2 học một ma trận embedding vị trí trong lúc huấn luyện rồi cộng vào token embedding. Nguyên tắc cốt lõi vẫn không đổi: vì self-attention thuần không tự nhận biết thứ tự, mỗi vectơ đầu vào sau phép cộng cần mang đồng thời thông tin nội dung và vị trí của token.&lt;/p&gt;

&lt;h3 id=&quot;query-key-value-và-multi-head-self-attention&quot;&gt;Query, Key, Value và multi-head self-attention&lt;/h3&gt;

&lt;p&gt;Từ các vectơ embedding đó, mô hình tính &lt;strong&gt;query (Q)&lt;/strong&gt;, &lt;strong&gt;key (K)&lt;/strong&gt; và &lt;strong&gt;value (V)&lt;/strong&gt;. Ở GPT-2 (small), thao tác này gom thành một phép nhân ma trận duy nhất: đầu vào kích thước \((6, 768)\) nhân với ma trận trọng số \((768, 2304)\) cộng độ lệch, cho ra tensor \((6, 2304)\). Con số 2304 bằng \(3 \times 768\) (tương ứng Q, K, V ghép lại), sau đó được tách thành &lt;strong&gt;12 đầu attention&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_qkv.png&quot; alt=&quot;Tính Q, K và V từ embedding&quot; /&gt;
&lt;em&gt;Nhân embedding với ma trận trọng số QKV gộp (cộng độ lệch) để thu đồng thời Q, K và V. Nguồn: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (giấy phép MIT).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Có thể hình dung theo ẩn dụ tìm kiếm mà chính công cụ sử dụng: &lt;strong&gt;query&lt;/strong&gt; là từ khóa bạn nhập, &lt;strong&gt;key&lt;/strong&gt; là tiêu đề các trang để đối chiếu, còn &lt;strong&gt;value&lt;/strong&gt; là nội dung trang bạn đọc sau khi khớp. Attention thực hiện phép tra cứu mềm: mỗi token xác định các token đứng trước có liên quan nhất rồi lấy tổ hợp có trọng số của các value tương ứng.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_attention.png&quot; alt=&quot;Scaled dot-product attention với mask nhân quả&quot; /&gt;
&lt;em&gt;Một đầu attention: tích vô hướng Q–K, chia tỉ lệ kèm mask nhân quả, rồi softmax (kèm dropout khi huấn luyện). Dạng tam giác dưới thể hiện ràng buộc của decoder: không được nhìn thấy token tương lai. Nguồn: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (giấy phép MIT).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Đi từ trái sang phải qua ba ma trận:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tích vô hướng&lt;/strong&gt; \(QK^{\top}\) đo độ tương đồng thô giữa mọi cặp query và key.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chia tỉ lệ và áp mask&lt;/strong&gt; chia cho \(\sqrt{d_k}\) (hệ số \(1/\sqrt{d_k}\) ở Chương 07) và áp &lt;strong&gt;mặt nạ nhân quả&lt;/strong&gt; gán \(-\infty\) cho các vị trí tương lai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Softmax&lt;/strong&gt; chuẩn hóa từng hàng thành phân phối xác suất trên các vị trí hợp lệ, sau đó nhân với \(V\) để ra đầu ra của đầu attention.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bạn có thể chuyển đổi giữa 12 đầu và di chuột lên từng token để quan sát mức chú ý của nó. Các đầu thường chuyên biệt hóa theo vai trò khác nhau (như cú pháp cục bộ hoặc liên kết ngữ nghĩa xa). Cuối cùng, đầu ra của 12 đầu được nối lại và chiếu qua lớp tuyến tính trước khi cộng vào luồng phần dư.&lt;/p&gt;

&lt;h3 id=&quot;khối-mlp&quot;&gt;Khối MLP&lt;/h3&gt;

&lt;p&gt;Sau khi attention định tuyến thông tin giữa các vị trí, &lt;strong&gt;MLP&lt;/strong&gt; (mạng feed-forward hai tầng) xử lý độc lập từng token. Trong GPT-2 (small), lớp ẩn mở rộng từ 768 lên \(4 \times 768 = 3072\) với hàm kích hoạt GELU, rồi chiếu trở lại 768 chiều, bao bọc bởi kết nối phần dư.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_mlp.png&quot; alt=&quot;MLP nở lên 3072 chiều với đường residual&quot; /&gt;
&lt;em&gt;MLP theo từng vị trí mở rộng mỗi token lên 3072 chiều rồi chiếu lại 768 chiều và cộng vào đường phần dư. Nguồn: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (giấy phép MIT).&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;xác-suất-đầu-ra-nhiệt-độ-temperature-và-lấy-mẫu&quot;&gt;Xác suất đầu ra, nhiệt độ (temperature) và lấy mẫu&lt;/h3&gt;

&lt;p&gt;Sau 12 khối Transformer, lớp tuyến tính cuối ánh xạ trạng thái ở vị trí cuối thành &lt;strong&gt;logit&lt;/strong&gt; — một điểm số cho mỗi từ trong từ vựng — rồi softmax chuyển thành phân phối xác suất cho token tiếp theo.&lt;/p&gt;

&lt;p&gt;Tham số &lt;strong&gt;temperature&lt;/strong&gt; (\(T\)) chia toàn bộ logit cho \(T\) &lt;em&gt;trước&lt;/em&gt; bước softmax:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(T = 1\): giữ nguyên phân phối gốc.&lt;/li&gt;
  &lt;li&gt;\(T &amp;lt; 1\): phân phối sắc nét hơn, ưu tiên các ứng viên xác suất cao (ổn định và ít ngẫu nhiên hơn).&lt;/li&gt;
  &lt;li&gt;\(T &amp;gt; 1\): phân phối phẳng hơn, tăng cơ hội cho các ứng viên xếp hạng thấp (đa dạng hơn nhưng cũng dễ lệch ngữ cảnh hơn).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hai bộ lọc phổ biến giúp giới hạn tập ứng viên trước khi lấy mẫu:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Top-k:&lt;/strong&gt; chỉ giữ \(k\) token có điểm cao nhất; phần còn lại bị gán \(-\infty\) để nhận xác suất 0.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Top-p&lt;/strong&gt; (&lt;em&gt;nucleus sampling&lt;/em&gt;): giữ tập token nhỏ nhất có tổng xác suất tích lũy đạt ngưỡng \(p\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_softmax.png&quot; alt=&quot;Temperature, lấy mẫu top-k và xác suất token kế tiếp&quot; /&gt;
&lt;em&gt;Với temperature 0.8 và top-k = 5, logit được chia tỉ lệ, các token ngoài top 5 bị loại rồi áp softmax cho phân phối token kế tiếp. Với prompt “…users to”, từ “visualize” dẫn đầu với 54,67%. Nguồn: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (giấy phép MIT).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Trong hình minh họa, temperature 0.8 chuyển logit \(-135.91\) thành \(-169.89\) (\(-135.91 / 0.8\)). Sau lọc top-k, các từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;quickly&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;explore&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;find&lt;/code&gt; bị loại khỏi danh sách ứng viên. Vì bước cuối là lấy mẫu xác suất chứ không luôn lấy \(\arg\max\), từ &lt;em&gt;“create”&lt;/em&gt; vẫn có khoảng 21% cơ hội được chọn.&lt;/p&gt;

&lt;h2 id=&quot;3-bài-tập-thực-hành-có-hướng-dẫn&quot;&gt;3. Bài tập thực hành có hướng dẫn&lt;/h2&gt;

&lt;p&gt;Hãy mở &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;demo trực tiếp&lt;/a&gt; và thực hiện lần lượt các bước sau với prompt mặc định &lt;em&gt;“Data visualization empowers users to”&lt;/em&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Quan sát tách token:&lt;/strong&gt; Mở cột Embedding. Từ nào giữ nguyên một token, từ nào bị tách nhỏ? Lý do bộ từ vựng &lt;em&gt;subword&lt;/em&gt; hoạt động như vậy là gì?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra phép cộng vị trí:&lt;/strong&gt; Xác nhận mỗi vectơ đầu vào là tổng của token embedding và vectơ vị trí (0, 1, 2, …). Điều gì sẽ sai nếu bỏ bước này? (Đối chiếu với phần &lt;em&gt;ablation&lt;/em&gt; trong bài &lt;strong&gt;08-01-02-02&lt;/strong&gt;.)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh các đầu attention:&lt;/strong&gt; Mở một đầu ở Block 1, di chuột lên token cuối và ghi lại các token trước có trọng số cao nhất, rồi đổi sang một đầu khác để so sánh mức độ tương đồng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra mặt nạ nhân quả:&lt;/strong&gt; Trong ma trận &lt;em&gt;“Scaling · Mask”&lt;/em&gt;, xác định vùng bị che. Giải thích vì sao mô hình chỉ-decoder vẫn phải che các vị trí tương lai ngay cả khi toàn bộ prompt đã được nhập sẵn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thử nghiệm temperature:&lt;/strong&gt; Giữ nguyên prompt, lần lượt đặt temperature gần 0.1 rồi gần 1.5 và nhận xét sự thay đổi của biểu đồ xác suất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh top-k và top-p:&lt;/strong&gt; Giữ temperature ở 0.8, thử &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;top-k = 1&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;top-k = 5&lt;/code&gt;, rồi chuyển sang &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;top-p&lt;/code&gt;. Quan sát cách các token ngoài ngưỡng biến mất ở cột Softmax.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thử với prompt riêng:&lt;/strong&gt; Nhập một câu tiếng Anh ngắn (hoặc trộn tiếng Anh và tiếng Việt) rồi nhấn Generate. Lưu ý rằng đây là GPT-2 small chứ không phải LLM hiện đại đã tinh chỉnh theo chỉ dẫn, nên năng lực dự đoán có giới hạn dù dùng chung nền tảng kiến trúc.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-khái-niệm-liên-quan&quot;&gt;4. Khái niệm liên quan&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Chương 07&lt;/strong&gt;: scaled dot-product attention, multi-head attention và mặt nạ nhân quả chính là các ma trận hiển thị trong công cụ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;08-01-01 Lý thuyết Transformer&lt;/strong&gt;: mã hóa vị trí và cấu trúc khối hoàn chỉnh (lưu ý GPT-2 dùng PE tuyệt đối học được thay vì sin–cos cố định).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;08-01-02-02 Demo, bài báo và bẫy thường gặp&lt;/strong&gt;: tự huấn luyện mô hình nhỏ; kết hợp với Explainer để quan sát một mô hình đã tiền huấn luyện thực tế.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chương 26&lt;/strong&gt;: tokenization, giải mã và chiến lược lấy mẫu ở quy mô LLM.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-các-bài-báo-nền-tảng&quot;&gt;5. Các bài báo nền tảng&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://doi.org/10.1145/3772318.3791725&quot;&gt;Transformer Explainer (Cho et al., CHI 2026)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Công trình giới thiệu công cụ trực quan hóa tương tác GPT-2 chạy trên trình duyệt này (bản thảo trên &lt;a href=&quot;https://arxiv.org/abs/2408.04619&quot;&gt;arXiv:2408.04619&lt;/a&gt;).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf&quot;&gt;Language Models are Unsupervised Multitask Learners (GPT-2, Radford et al., 2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Dòng mô hình chỉ-decoder đang vận hành bên trong công cụ.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need (Vaswani et al., 2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Kiến trúc Transformer encoder–decoder gốc dùng để đối chiếu với kiến trúc chỉ-decoder trong Explainer.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;6-điểm-chính&quot;&gt;6. Điểm chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Transformer sinh văn bản hoạt động theo quy trình dự đoán token kế tiếp: embedding → các khối attention + MLP xếp chồng → softmax trên từ vựng.&lt;/li&gt;
  &lt;li&gt;Trọng số attention là độ tương đồng đã chuẩn hóa và áp mặt nạ, quyết định trực tiếp cách mỗi token tổng hợp ngữ cảnh.&lt;/li&gt;
  &lt;li&gt;Temperature, top-k và top-p không thay đổi trọng số mô hình mà chỉ biến đổi phân phối xác suất lấy mẫu từ cùng một vectơ logit.&lt;/li&gt;
  &lt;li&gt;GPT-2 small đủ gọn để chạy trực tiếp trong trình duyệt và đủ rõ để minh họa cụ thể từng phép toán của Chương 08.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;ghi-nguồn-và-giấy-phép&quot;&gt;Ghi nguồn và giấy phép&lt;/h2&gt;

&lt;p&gt;Transformer Explainer do Aeree Cho, Grace C. Kim, Alexander Karpekov, Alec Helbling, Jay Wang, Seongmin Lee, Benjamin Hoover và Polo Chau phát triển tại Georgia Institute of Technology (Polo Club of Data Science), phát hành theo &lt;a href=&quot;https://github.com/poloclub/transformer-explainer/blob/main/LICENSE&quot;&gt;giấy phép MIT&lt;/a&gt;. Các hình trong bài được trích hoặc điều chỉnh kích thước từ thư mục chính thức &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;static/preview&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;static/article_assets&lt;/code&gt; trong &lt;a href=&quot;https://github.com/poloclub/transformer-explainer&quot;&gt;kho mã nguồn công khai&lt;/a&gt; (hình teaser được thu từ 8135×3895 xuống 2400×1149 cho trang khóa học). Khi trích dẫn công cụ, sử dụng mục BibTeX sau:&lt;/p&gt;

&lt;div class=&quot;language-bibtex highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;@inproceedings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;cho2026transformer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{Transformer Explainer: Learning LLM Transformers with Interactive Visual Explanation and Experimentation}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;author&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{Cho, Aeree and Kim, Grace C and Karpekov, Alexander and Lee, Seongmin and Helbling, Alec and Hoover, Benjamin and Wang, Zijie J and Kahng, Minsuk and Chau, Duen Horng}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;booktitle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{Proceedings of the 2026 CHI Conference on Human Factors in Computing Systems}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;pages&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{1--21}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;year&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{2026}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=TFUc41G2ikY&quot;&gt;Transformer Explainer Demo&lt;/a&gt; — Polo Club / Georgia Tech (tiếng Anh). Giới thiệu nhanh cách tương tác với công cụ trực quan hóa GPT-2 dùng trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown (tiếng Anh). Minh họa bằng hoạt hình cùng luồng embedding → attention → MLP → softmax.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Mã nguồn nanoGPT làm nền chuyển đổi cho mô hình chạy trên trình duyệt.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-01 Kiến trúc Transformer</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_01_Transformer_Architecture/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_01_Transformer_Architecture</id>
   <content type="html">&lt;p&gt;Nhiều người mới học cảm thấy sơ đồ kiến trúc Transformer trong bài báo gốc năm 2017 trông như một mê cung đầy mũi tên rẽ nhánh. Nhưng khi tách nó thành hai góc nhìn — &lt;strong&gt;lý thuyết từng khối con&lt;/strong&gt; (tại sao cần FFN mở rộng \(4\times\), tại sao Pre-LN ổn định hơn Post-LN) và &lt;strong&gt;cài đặt mã nguồn gọn sạch&lt;/strong&gt; — bạn sẽ nhận ra Transformer thực chất là một trong những kiến trúc tối giản và đối xứng nhất lịch sử học sâu.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-học-phần-kiến-trúc-transformer&quot;&gt;Kiến thức cần nhớ: Ba trụ cột học phần Kiến trúc Transformer&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giải phẫu toán học từng khối con&lt;/strong&gt;:
Token Embedding (nhân \(\sqrt{d_{\text{model}}}\)), Positional Encoding, Multi-Head Attention, Position-wise FFN (\(\text{Linear} \to \text{Activation} \to \text{Linear}\)), Residual Connection và LayerNorm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thiết kế ba họ mô hình từ cùng một bộ khối&lt;/strong&gt;:
Chỉ bằng cách bật/tắt mặt nạ nhân quả (causal mask) và giữ hay bỏ khối cross-attention, cùng một khối lõi sinh ra cả BERT, GPT lẫn T5.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng từ code tới thực nghiệm&lt;/strong&gt;:
Tự lắp ráp một Transformer mini hoàn chỉnh bằng PyTorch, kiểm tra bằng smoke tests (shape, gradient, causal leak) và hiểu rõ các cạm bẫy khi mở rộng quy mô (warmup, weight tying, KV-cache).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-tỷ-lệ-phân-bổ-tham-số-giữa-attention-và-ffn-trong-1-tầng-transformer&quot;&gt;Giải thích: Tính tay tỷ lệ phân bổ tham số giữa Attention và FFN trong 1 tầng Transformer&lt;/h3&gt;

&lt;p&gt;Với \(d_{\text{model}} = 512\) và chiều ẩn của FFN chuẩn là \(d_{\text{ff}} = 4 \, d_{\text{model}} = 2{,}048\) (bỏ qua bias và LayerNorm nhỏ):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Khối Multi-Head Self-Attention&lt;/strong&gt; (4 ma trận \(W^Q, W^K, W^V, W^O\) kích thước \(512 \times 512\)):
\(4 \times 512^2 = \mathbf{1{,}048{,}576}\) tham số (&lt;strong&gt;33,3%&lt;/strong&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khối Feed-Forward Network (FFN)&lt;/strong&gt; (hai ma trận \(W_1 \in \mathbb{R}^{512 \times 2048}\) và \(W_2 \in \mathbb{R}^{2048 \times 512}\)):
\(2 \times 512 \times 2{,}048 = 8 \times 512^2 = \mathbf{2{,}097{,}152}\) tham số (&lt;strong&gt;66,7%&lt;/strong&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng 1 tầng Transformer Encoder/Decoder-only&lt;/strong&gt;: \(12 \, d_{\text{model}}^2 = \mathbf{3{,}145{,}728}\) tham số!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Một sự thật hay gây bất ngờ: &lt;strong&gt;hai phần ba&lt;/strong&gt; số tham số của một mô hình ngôn ngữ Transformer không nằm ở Attention, mà nằm ở các tầng &lt;strong&gt;FFN&lt;/strong&gt; — nơi mô hình lưu trữ phần lớn tri thức sự kiện (&lt;em&gt;factual knowledge&lt;/em&gt;) như một bộ nhớ khóa–giá trị khổng lồ!&lt;/p&gt;

&lt;h1 id=&quot;08-01-kiến-trúc-transformer&quot;&gt;08-01 Kiến trúc Transformer&lt;/h1&gt;

&lt;p&gt;Đây là phần trọng tâm của Chương 08, trình bày cách ghép nối các thành phần attention từ Chương 07 thành kiến trúc Transformer hoàn chỉnh.&lt;/p&gt;

&lt;h2 id=&quot;nội-dung-chính&quot;&gt;Nội dung chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lý thuyết Transformer&lt;/strong&gt;&lt;br /&gt;
Động lực thay thế RNN, self-attention QKV trong mô hình hoàn chỉnh, multi-head attention, mã hóa vị trí (&lt;em&gt;positional encoding&lt;/em&gt;), cấu trúc tầng encoder và decoder (masked self-attention, cross-attention, FFN), kết nối phần dư và LayerNorm, cùng ba dòng mô hình chỉ-encoder, chỉ-decoder và encoder–decoder.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Cài đặt Transformer&lt;/strong&gt;&lt;br /&gt;
Xây dựng các module từ đầu bằng PyTorch, chạy kiểm thử nhanh (&lt;em&gt;smoke test&lt;/em&gt;), huấn luyện ví dụ nhỏ, điểm qua các bài báo nền tảng và tổng hợp bẫy vận hành (quy ước mặt nạ, lỗi PE, KV-cache, chi phí \(O(L^2)\)).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;lộ-trình-gợi-ý&quot;&gt;Lộ trình gợi ý&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Bước&lt;/th&gt;
      &lt;th&gt;Bài học&lt;/th&gt;
      &lt;th&gt;Mục tiêu đạt được&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;08-01-01 Lý thuyết&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Tự viết lại được phương trình của một tầng Transformer hoàn chỉnh&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02 Tổng quan cài đặt&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Nắm rõ sơ đồ module và danh mục kiểm tra&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02-01 Mã cốt lõi&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Cài đặt và kiểm chứng các khối PyTorch chạy được&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02-02 Demo &amp;amp; bẫy&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Huấn luyện thành công bài toán nhỏ và nắm quy trình gỡ lỗi&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Nếu phần phương trình ban đầu còn trừu tượng, bạn có thể mở lớp tương ứng trong bài &lt;strong&gt;Mã cốt lõi&lt;/strong&gt;, chạy thử trên dữ liệu ngẫu nhiên rồi quay lại đối chiếu với lý thuyết.&lt;/p&gt;

&lt;p&gt;Hãy bắt đầu với bài &lt;strong&gt;Lý thuyết Transformer&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown (tiếng Anh). Trình bày luồng dữ liệu xuyên suốt cả phần lý thuyết và phần cài đặt.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Đích thực hành của phần cài đặt: xây dựng mô hình GPT từ các khối cơ bản.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zxQyTK8quyY&quot;&gt;Transformer Neural Networks, ChatGPT’s foundation, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Giải thích chi tiết từng tensor trước khi đọc mã nguồn.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-01-02 Cài đặt Transformer</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_01_02_Transformer_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_01_02_Transformer_Implementation</id>
   <content type="html">&lt;p&gt;Tự tay lắp ráp một Transformer hoạt động trơn tru bằng PyTorch không dài như nhiều người tưởng — toàn bộ lõi từ Positional Encoding, Multi-Head Attention, FFN đến một Encoder–Decoder hoàn chỉnh chỉ gói gọn trong chưa đầy 200 dòng code rõ ràng. Bí quyết nằm ở việc chia mô-đun rành mạch và thiết lập các bài kiểm tra khói (smoke tests) ngay trước khi bước vào vòng huấn luyện.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-nguyên-tắc-vàng-khi-lập-trình-kiến-trúc-transformer&quot;&gt;Kiến thức cần nhớ: Ba nguyên tắc vàng khi lập trình kiến trúc Transformer&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phân tách mô-đun sạch theo sơ đồ dữ liệu&lt;/strong&gt;:
Xây dựng tuần tự từ dưới lên: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PositionalEncoding&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MultiHeadAttention&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PositionwiseFFN&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;EncoderLayer&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DecoderLayer&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Transformer&lt;/code&gt;. Mỗi mô-đun có hợp đồng đầu vào/đầu ra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, L, d_model)&lt;/code&gt; thống nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quản lý hai loại mặt nạ độc lập (Padding Mask và Causal Mask)&lt;/strong&gt;:
Kết hợp bằng phép giao logic (chỉ cho phép chú ý những vị trí &lt;strong&gt;vừa&lt;/strong&gt; không phải &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;PAD&amp;gt;&lt;/code&gt;, &lt;strong&gt;vừa&lt;/strong&gt; không nằm ở tương lai) với hình dạng broadcast &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, 1, L_q, L_k)&lt;/code&gt; để áp dụng cho mọi head.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Danh mục kiểm tra trước khi huấn luyện quy mô lớn&lt;/strong&gt;:
Kiểm tra tính nhân quả (&lt;em&gt;causal leak test&lt;/em&gt;: đổi token cuối xem logit các token trước có đổi 0,0 hay không), kiểm tra dòng gradient không bị &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;, và thử nghiệm overfit hoàn hảo trên 1 batch nhỏ (10 mẫu) để xác minh không có lỗi logic ngầm.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-phép-kết-hợp-padding-mask-và-causal-mask-cho-chuỗi-dài-l--4&quot;&gt;Giải thích: Tính tay phép kết hợp Padding Mask và Causal Mask cho chuỗi dài \(L = 4\)&lt;/h3&gt;

&lt;p&gt;Giả sử trong một batch, câu có độ dài tối đa \(L = 4\), nhưng câu này chỉ có 3 từ thật và vị trí cuối (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;idx=3&lt;/code&gt;) là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;PAD&amp;gt;&lt;/code&gt;. Quy ước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1 = được phép chú ý&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0 = bị che&lt;/code&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Causal Mask&lt;/strong&gt; (tam giác dưới \(4 \times 4\)):
\(\begin{bmatrix} 1 &amp;amp; 0 &amp;amp; 0 &amp;amp; 0 \\ 1 &amp;amp; 1 &amp;amp; 0 &amp;amp; 0 \\ 1 &amp;amp; 1 &amp;amp; 1 &amp;amp; 0 \\ 1 &amp;amp; 1 &amp;amp; 1 &amp;amp; 1 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Key Padding Mask&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1, 1, 1, 0]&lt;/code&gt; phát sóng theo mọi hàng):
\(\begin{bmatrix} 1 &amp;amp; 1 &amp;amp; 1 &amp;amp; 0 \\ 1 &amp;amp; 1 &amp;amp; 1 &amp;amp; 0 \\ 1 &amp;amp; 1 &amp;amp; 1 &amp;amp; 0 \\ 1 &amp;amp; 1 &amp;amp; 1 &amp;amp; 0 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mặt nạ kết hợp (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;causal &amp;amp; padding&lt;/code&gt;)&lt;/strong&gt;:
\(\begin{bmatrix} 1 &amp;amp; 0 &amp;amp; 0 &amp;amp; 0 \\ 1 &amp;amp; 1 &amp;amp; 0 &amp;amp; 0 \\ 1 &amp;amp; 1 &amp;amp; 1 &amp;amp; 0 \\ 1 &amp;amp; 1 &amp;amp; 1 &amp;amp; 0 \end{bmatrix}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tại hàng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;idx=2&lt;/code&gt; (từ thật thứ 3), mô hình nhìn thấy các vị trí &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0, 1, 2&lt;/code&gt; và không bao giờ nhìn thấy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;PAD&amp;gt;&lt;/code&gt; ở cột &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3&lt;/code&gt; — sạch sẽ tuyệt đối!&lt;/p&gt;

&lt;h1 id=&quot;08-01-02-cài-đặt-transformer&quot;&gt;08-01-02 Cài đặt Transformer&lt;/h1&gt;

&lt;p&gt;Phần lý thuyết mô tả các phép biến đổi toán học, còn phần cài đặt đảm bảo mô hình tuân thủ chặt chẽ &lt;strong&gt;kích thước tensor, quy ước mặt nạ, thứ tự kết nối phần dư và độ ổn định số học&lt;/strong&gt;. Hai bài trong mục này hướng dẫn xây dựng một mô hình Transformer nhỏ gọn nhưng đầy đủ.&lt;/p&gt;

&lt;h2 id=&quot;các-bài-học-trong-mục-này&quot;&gt;Các bài học trong mục này&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Cài đặt cốt lõi&lt;/strong&gt;&lt;br /&gt;
Cài đặt từ đầu bằng PyTorch các khối scaled dot-product attention, multi-head attention, mã hóa vị trí, FFN và khối encoder.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Demo, bài báo và bẫy thường gặp&lt;/strong&gt;&lt;br /&gt;
Chạy kiểm thử nhanh lượt truyền xuôi, quan sát trọng số attention, huấn luyện trên một tác vụ chuỗi nhỏ, điểm qua các bài báo nền tảng và danh mục gỡ lỗi thực tế.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;sơ-đồ-các-module&quot;&gt;Sơ đồ các module&lt;/h2&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Token ids
  → Embedding + PositionalEncoding
  → N × EncoderLayer
        MultiHeadSelfAttention (+ residual/norm)
        PositionwiseFFN        (+ residual/norm)
  → (tùy chọn) chồng DecoderLayer với causal + cross-attn
  → Đầu Linear lên từ vựng
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;danh-mục-kiểm-tra-trước-khi-mở-rộng-quy-mô&quot;&gt;Danh mục kiểm tra trước khi mở rộng quy mô&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Hạng mục&lt;/th&gt;
      &lt;th&gt;Tiêu chí kiểm tra&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Mặt nạ nhân quả&lt;/td&gt;
      &lt;td&gt;Trọng số ở các vị trí tương lai xấp xỉ 0&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mặt nạ đệm&lt;/td&gt;
      &lt;td&gt;Các vị trí &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PAD&lt;/code&gt; có trọng số bằng 0&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Kết nối phần dư&lt;/td&gt;
      &lt;td&gt;Thử nghiệm cắt giảm: bỏ residual sẽ làm giảm mạnh khả năng huấn luyện mạng sâu&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mã hóa vị trí (PE)&lt;/td&gt;
      &lt;td&gt;Với bản cổ điển, cộng một lần ở đầu vào (trừ khi dùng thiết kế PE tương đối/RoPE theo từng tầng)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Thống nhất &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_first&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Mọi module dùng chung quy ước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, L, d)&lt;/code&gt; hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(L, B, d)&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Đảm bảo gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; khi suy luận để tắt dropout&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Hãy bắt đầu với bài &lt;strong&gt;Cài đặt cốt lõi&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Hướng dẫn xây dựng lần lượt từng module (attention, MLP, khối Transformer, đầu mô hình ngôn ngữ) khớp với sơ đồ bài này.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown (tiếng Anh). Đối chiếu các phương trình toán học tương ứng với từng module.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zxQyTK8quyY&quot;&gt;Transformer Neural Networks, ChatGPT’s foundation, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Góc nhìn trực quan bổ sung giúp khoanh vùng nhanh khi gặp lỗi kích thước tensor.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-01-02-02 Demo, Bài báo và Bẫy Transformer</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_01_02_02_Transformer_Demos_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_01_02_02_Transformer_Demos_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Biết viết một lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransformerBlock&lt;/code&gt; chạy được trên tensor ngẫu nhiên chưa đủ để huấn luyện thành công một mô hình thực thụ. Trong thực chiến, Transformer nổi tiếng là kiến trúc “khó tính” ở giai đoạn đầu huấn luyện: quên lịch tăng dần tốc độ học (learning rate warmup), dùng sai chỉ số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ignore_index&lt;/code&gt; cho padding trong hàm mất mát, hay bật nhầm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval()&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train()&lt;/code&gt; đều có thể khiến loss đi ngang mãi mãi mà không báo một dòng lỗi nào.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-bài-học-thực-chiến-từ-demo-và-cạm-bẫy-transformer&quot;&gt;Kiến thức cần nhớ: Bốn bài học thực chiến từ Demo và Cạm bẫy Transformer&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lịch tốc độ học Warmup + Cosine/Inverse-Sqrt Decay&lt;/strong&gt;:
Ở những bước đầu tiên, phương sai gradient của LayerNorm và ước lượng moment bậc 2 của Adam chưa ổn định; tăng tuyến tính learning rate từ \(0 \to \eta_{\max}\) trong vài nghìn bước đầu (warmup) ngăn chặn hiện tượng phân kỳ sớm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dịch nhãn (Target Shifting) và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ignore_index=pad_id&lt;/code&gt; trong Loss&lt;/strong&gt;:
Với mô hình ngôn ngữ tự hồi quy, đầu vào là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tokens[:, :-1]&lt;/code&gt; và nhãn đích là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tokens[:, 1:]&lt;/code&gt;; đồng thời phải truyền &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ignore_index=pad_id&lt;/code&gt; vào &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CrossEntropyLoss&lt;/code&gt; để mô hình không lãng phí dung lượng vào việc đoán ký tự đệm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;PAD&amp;gt;&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán chất lượng học qua Bản đồ Trọng số Attention&lt;/strong&gt;:
Trực quan hóa ma trận trọng số của từng head giúp phát hiện các mẫu thú vị (head nhìn từ ngay trước, head nối chủ ngữ–động từ, head tập trung vào dấu câu) cũng như phát hiện lỗi rò rỉ mặt nạ nhân quả.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính toán ngân sách bộ nhớ khi huấn luyện (Activation vs. Weight)&lt;/strong&gt;:
Độ dài chuỗi tăng gấp đôi khiến bộ nhớ lưu ma trận attention tăng gấp &lt;strong&gt;4 lần&lt;/strong&gt; — đó là lý do thực tế luôn phải kết hợp Gradient Accumulation, Mixed Precision (BF16/FP16) và FlashAttention.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-lịch-learning-rate-warmup--inverse-square-root-noam-scheduler-của-bài-báo-gốc-2017&quot;&gt;Giải thích: Tính tay lịch Learning Rate Warmup + Inverse Square Root (Noam Scheduler của bài báo gốc 2017)&lt;/h3&gt;

&lt;p&gt;Công thức lịch tốc độ học kinh điển trong &lt;em&gt;“Attention Is All You Need”&lt;/em&gt;:
\(\eta(\text{step}) = d_{\text{model}}^{-0{,}5} \cdot \min\!\left(\text{step}^{-0{,}5}, \; \text{step} \cdot \text{warmup}^{-1{,}5}\right)\)&lt;/p&gt;

&lt;p&gt;Giả sử \(d_{\text{model}} = 512 \implies d_{\text{model}}^{-0{,}5} \approx 0{,}04419\) và \(\text{warmup} = 4{,}000\) bước:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Bước huấn luyện (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;step&lt;/code&gt;)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Nhánh hoạt động&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Phép tính \(\eta(\text{step})\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Tốc độ học \(\eta\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;step = 1,000&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Warmup tuyến tính&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0{,}04419 \times 1{,}000 \times 4{,}000^{-1{,}5}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(1{,}75 \times 10^{-4}\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;step = 4,000&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Đạt đỉnh (Peak)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0{,}04419 \times 4{,}000^{-0{,}5}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(6{,}99 \times 10^{-4}\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;step = 16,000&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Giảm theo \(1/\sqrt{\text{step}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0{,}04419 \times 16{,}000^{-0{,}5}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(3{,}49 \times 10^{-4}\)&lt;/strong&gt; (giảm một nửa)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Lịch Noam tăng mượt mà trong 4.000 bước đầu để ổn định Adam, rồi hạ dần nhẹ nhàng khi mô hình tiến gần vùng cực tiểu.&lt;/p&gt;

&lt;h1 id=&quot;demo-bài-báo-và-bẫy-transformer&quot;&gt;Demo, Bài báo và Bẫy Transformer&lt;/h1&gt;

&lt;p&gt;Sau khi đã có các module cốt lõi ở bài trước, phần này đưa chúng vào chạy thử trên một bài toán nhỏ để kiểm chứng quá trình học, hệ thống hóa các bài báo nền tảng và tổng hợp những lỗi vận hành dễ tốn nhiều thời gian gỡ lỗi nhất.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Ba kỹ năng thực hành giúp chuyển từ việc sao chép mã nguồn sang làm chủ mô hình Transformer:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Quan sát nội bộ&lt;/strong&gt; (&lt;em&gt;instrumentation&lt;/em&gt;) — theo dõi trọng số attention và chuẩn hóa kích hoạt qua từng tầng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vòng huấn luyện tối thiểu&lt;/strong&gt; — kiểm chứng trên một bài toán nhỏ rằng mô hình thực sự hội tụ và học được mẫu dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỹ thuật vận hành&lt;/strong&gt; — nắm vững lịch warmup tốc độ học, KV-cache, tính toán hỗn hợp độ chính xác (&lt;em&gt;mixed precision&lt;/em&gt;) và giới hạn \(O(L^2)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mô hình trong bài được giữ ở kích thước nhỏ để chạy nhanh ngay trên CPU cá nhân.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-ghi-chú-toán-học-và-hệ-thống&quot;&gt;2. Ghi chú toán học và hệ thống&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Hàm mất mát &lt;em&gt;teacher forcing&lt;/em&gt;&lt;/strong&gt; cho bài toán dự đoán token kế tiếp trên chuỗi \(y_{1:L}\):&lt;/p&gt;

\[\mathcal{L} = -\sum_{t=1}^{L-1} \log p_\theta(y_{t+1} \mid y_{\le t})\]

&lt;p&gt;Trong ví dụ minh họa chỉ-encoder bên dưới, ta dùng đầu &lt;strong&gt;dự đoán dịch chuyển&lt;/strong&gt; (&lt;em&gt;shift prediction&lt;/em&gt;) trực tiếp trên trạng thái encoder — đủ gọn để kiểm chứng đồng thời PE, attention và kết nối phần dư.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;KV-cache khi suy luận:&lt;/strong&gt; Khi sinh token thứ \(t\), mô hình lưu lại và tái sử dụng các ma trận \(K_{1:t-1}, V_{1:t-1}\) đã tính từ các bước trước, chỉ chiếu thêm token mới. Nhờ đó chi phí tại bước \(t\) giảm xuống \(O(t\,d)\) thay vì tính lại toàn bộ \(O(t^2 d)\) từ đầu ở mỗi bước (tổng chi phí cho chuỗi dài \(T\) vẫn là \(O(T^2)\), nhưng loại bỏ phần tính toán lặp lại rất lớn).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;p&gt;Bài toán thử nghiệm: cho một chuỗi số nguyên tăng dần theo modulo, dự đoán số nguyên kế tiếp (dịch chuyển 1 bước). Khi có PE và self-attention, mô hình học được quy luật chuỗi mà không cần tầng hồi quy. Nếu loại bỏ PE trong thử nghiệm cắt giảm (&lt;em&gt;ablation&lt;/em&gt;), hiệu năng trên các mẫu phụ thuộc thứ tự sẽ giảm rõ rệt — đây là phép kiểm tra trực tiếp xem PE có đang hoạt động đúng hay không.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;
&lt;h3 id=&quot;41-chạy-xuôi-và-kiểm-tra-trọng-số-attention&quot;&gt;4.1 Chạy xuôi và kiểm tra trọng số attention&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Reuse modules from the core lesson (paste classes from 08-01-02-01 into the same script,
# or import them from your package).
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# --- assume MultiHeadAttention, PositionalEncoding, TransformerEncoder,
# --- subsequent_mask are defined as in 08-01-02-01 ---
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;manual_seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;enc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TransformerEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ids&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Inspect first layer self-attention with causal mask via standalone MHA
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subsequent_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, H, L, L)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;future mass&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diagonal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;42-huấn-luyện-thử-dự-đoán-bước-kế-tiếp-trên-trạng-thái-encoder&quot;&gt;4.2 Huấn luyện thử: Dự đoán bước kế tiếp trên trạng thái encoder&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyNextStepModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TransformerEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;head&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, L) token ids
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# (B, L, d)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;head&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# (B, L, V)
&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;make_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# sequences 0..seq_len-1 mod vocab, plus noise offset per row
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;base&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;repeat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;offset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;base&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;offset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# predict next id (shift); last position predicts (last+1)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyNextStepModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;opt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3e-4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;201&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;make_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# predict y_t from representation at position t
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;opt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip_grad_norm_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;opt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;step &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  loss &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;make_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;input    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tolist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;target   &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tolist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;pred     &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tolist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Khi chạy đoạn mã trên, giá trị mất mát cần giảm đều qua các bước với gradient hữu hạn — đó là dấu hiệu xác nhận kiến trúc hoạt động đúng.&lt;/p&gt;

&lt;h3 id=&quot;43-thử-nghiệm-cắt-giảm-ablation-bỏ-mã-hóa-vị-trí&quot;&gt;4.3 Thử nghiệm cắt giảm (Ablation): Bỏ mã hóa vị trí&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NoPEEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TransformerEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;token_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;embed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;token_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# intentionally skip self.pos
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln_f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train briefly with NoPEEncoder inside a similar wrapper and compare final loss.
# Order-sensitive tasks should degrade without PE.
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;44-lịch-warmup-tốc-độ-học-theo-transformer-gốc&quot;&gt;4.4 Lịch warmup tốc độ học theo Transformer gốc&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;transformer_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;warmup&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;warmup&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;transformer_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Seq2seq dùng RNN&lt;/strong&gt;: cùng mô hình mã hóa–giải mã nhưng khó song song hóa hơn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình chuỗi CNN&lt;/strong&gt;: vùng tiếp nhận mang tính cục bộ, cần nhiều tầng sâu để bao phủ tầm xa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sparse Transformers / Longformer / Linformer&lt;/strong&gt;: các biến thể attention giảm độ phức tạp dưới mức bậc hai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Encoder–decoder so với chỉ-decoder&lt;/strong&gt;: khác nhau ở giao diện ứng dụng nhưng chia sẻ chung lõi khối Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Instruction tuning và RLHF&lt;/strong&gt;: các giai đoạn tinh chỉnh nằm phía trên mô hình ngôn ngữ Transformer đã tiền huấn luyện.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need (Vaswani et al., 2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Công trình gốc đề xuất multi-head attention, mã hóa vị trí, cấu trúc encoder–decoder và lịch huấn luyện chuẩn.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;BERT (Devlin et al., 2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Tiền huấn luyện encoder hai chiều (MLM và NSP), định hình quy trình &lt;em&gt;pretrain → fine-tune&lt;/em&gt; cho hiểu ngôn ngữ tự nhiên.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf&quot;&gt;GPT-2 (Radford et al., 2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Mô hình ngôn ngữ nhân quả quy mô lớn, mở ra hướng giải quyết tác vụ không cần tinh chỉnh (&lt;em&gt;zero-shot&lt;/em&gt;) qua prompt.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;ViT (Dosovitskiy et al., 2021)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Biểu diễn ảnh thành chuỗi các mảng (patch), mở rộng phạm vi ứng dụng của Transformer sang thị giác máy tính.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2207.09238&quot;&gt;Formal Algorithms for Transformers (Phuong &amp;amp; Hutter, 2022)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Trình bày mã giả chặt chẽ cho các biến thể Transformer, rất thuận tiện khi đối chiếu cài đặt.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-cạm-bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;7. Cạm bẫy thường gặp và mẹo thực hành&lt;/h2&gt;
&lt;h3 id=&quot;các-lỗi-nghiêm-trọng&quot;&gt;Các lỗi nghiêm trọng&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Thiếu tín hiệu vị trí&lt;/strong&gt; — mô hình trở thành tập hợp vectơ không phân biệt thứ tự.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đảo ngược quy ước mặt nạ&lt;/strong&gt; — gây rò rỉ tương lai hoặc tạo hàng toàn \(-\infty\) dẫn tới &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; sau softmax.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không che token đệm (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PAD&lt;/code&gt;)&lt;/strong&gt; — làm nhiễu quá trình huấn luyện và giảm chất lượng đánh giá.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quên hệ số \(1/\sqrt{d_k}\)&lt;/strong&gt; — gây bão hòa softmax và làm huấn luyện khó hội tụ khi chiều lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trộn lẫn công thức Post-LN và Pre-LN&lt;/strong&gt; — áp dụng tốc độ học và lịch warmup của bố cục này sang bố cục kia.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quên chuyển sang &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; khi suy luận&lt;/strong&gt; — dropout vẫn hoạt động làm đầu ra bị nhiễu ngẫu nhiên.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính lại toàn bộ quá khứ ở mỗi bước giải mã&lt;/strong&gt; — gây độ trễ rất lớn; cần bật KV-cache khi suy luận thực tế.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;mẹo-huấn-luyện&quot;&gt;Mẹo huấn luyện&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Áp dụng &lt;strong&gt;cắt ngưỡng gradient&lt;/strong&gt; (ví dụ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max_norm=1.0&lt;/code&gt;) để ổn định giai đoạn đầu.&lt;/li&gt;
  &lt;li&gt;Dùng &lt;strong&gt;warmup&lt;/strong&gt; tăng dần tốc độ học rồi giảm dần thay vì dùng tốc độ học lớn ngay từ bước 0.&lt;/li&gt;
  &lt;li&gt;Sử dụng &lt;strong&gt;mixed precision&lt;/strong&gt; (kèm &lt;em&gt;loss scaling&lt;/em&gt; khi cần) để tăng tốc và tiết kiệm bộ nhớ GPU.&lt;/li&gt;
  &lt;li&gt;Theo dõi &lt;strong&gt;entropy của trọng số attention&lt;/strong&gt; theo từng tầng để phát hiện sớm hiện tượng tập trung cực đoan hoặc phân bố đều bất thường.&lt;/li&gt;
  &lt;li&gt;Luôn kiểm chứng trên cấu hình &lt;strong&gt;nhỏ&lt;/strong&gt; (2 tầng, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;d = 64–128&lt;/code&gt;) trước khi mở rộng quy mô.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;danh-mục-kiểm-tra-gỡ-lỗi&quot;&gt;Danh mục kiểm tra gỡ lỗi&lt;/h3&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[ ] out.shape == (B, L, d) or (B, L, V)
[ ] causal: triu(attn,1) ≈ 0
[ ] pad keys: weights ≈ 0
[ ] loss finite; grad norms finite
[ ] PE length covers max L
[ ] model.train() vs model.eval() correct
[ ] Ablation: shuffle positions → performance drop (if PE works)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-tóm-tắt-các-điểm-chính&quot;&gt;8. Tóm tắt các điểm chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Một cài đặt Transformer đúng đòi hỏi kết hợp chặt chẽ giữa &lt;strong&gt;module chuẩn, quy ước mặt nạ rõ ràng và cấu trúc kết nối phần dư&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Kiểm chứng qua một bài toán nhỏ giúp đảm bảo kiến trúc vận hành đúng trước khi làm việc với các mô hình lớn.&lt;/li&gt;
  &lt;li&gt;Các dòng mô hình tiêu biểu như BERT, GPT và ViT đều kế thừa cùng một lõi kiến trúc.&lt;/li&gt;
  &lt;li&gt;Phần lớn sự cố trong thực tế xuất phát từ &lt;strong&gt;mặt nạ, mã hóa vị trí, độ chính xác số học và chi phí \(O(L^2)\)&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bạn đã hoàn thành mạch kiến thức cốt lõi của Chương 08 từ giới thiệu, lý thuyết, cài đặt đến thử nghiệm và gỡ lỗi. Để quan sát trực tiếp một mô hình GPT-2 đã tiền huấn luyện mà không cần tự huấn luyện, hãy tiếp tục với bài &lt;strong&gt;08-02 Transformer Explainer&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Minh họa quá trình huấn luyện, lấy mẫu và các lỗi thường gặp khi thiếu mặt nạ nhân quả hoặc cấu hình sai.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zxQyTK8quyY&quot;&gt;Transformer Neural Networks, ChatGPT’s foundation, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Trình bày rõ vai trò của từng kết nối (như đường phần dư) và hậu quả khi thiếu chúng.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How might LLMs store facts&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 7](https://www.youtube.com/watch?v=9-Jl0dxWQs8) — 3Blue1Brown (tiếng Anh). Phân tích cách khối MLP bên trong Transformer lưu trữ tri thức, mở rộng góc nhìn sau khi chạy demo.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-01-02-01 Cài đặt Cốt lõi Transformer</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_01_02_01_Transformer_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_01_02_01_Transformer_Core_Code</id>
   <content type="html">&lt;p&gt;Andrej Karpathy từng nói rằng cách duy nhất để thực sự hiểu một mô hình ngôn ngữ lớn là &lt;strong&gt;tự viết lại lõi Transformer từ đầu trong một tệp Python duy nhất&lt;/strong&gt;. Khi bạn tự tay viết &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MultiHeadAttention&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FeedForward&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransformerBlock&lt;/code&gt; và kiểm chứng bằng bài test rò rỉ tương lai (&lt;em&gt;causal leak test&lt;/em&gt;), mọi bí ẩn đằng sau các mô hình hàng trăm tỷ tham số sẽ tan biến — bởi GPT-4 hay Llama về bản chất chỉ là sự nhân bản của chính khối mã nguồn này ở quy mô lớn hơn!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-chi-tiết-kỹ-thuật-cốt-tử-trong-mã-nguồn-transformer&quot;&gt;Kiến thức cần nhớ: Bốn chi tiết kỹ thuật cốt tử trong mã nguồn Transformer&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đăng ký buffer không huấn luyện (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;register_buffer&lt;/code&gt;)&lt;/strong&gt;:
Ma trận Positional Encoding cố định và mặt nạ tam giác nhân quả phải được lưu bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self.register_buffer(...)&lt;/code&gt; thay vì thuộc tính thường — nhờ đó chúng tự động di chuyển cùng mô hình khi gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.to(&apos;cuda&apos;)&lt;/code&gt; mà không bị optimizer cập nhật trọng số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cấu trúc Pre-LN trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransformerBlock&lt;/code&gt;&lt;/strong&gt;:
Viết &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x = x + self.drop(self.attn(self.ln1(x)))&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x = x + self.drop(self.ffn(self.ln2(x)))&lt;/code&gt; giúp mạng sâu ổn định ngay cả khi không chỉnh lịch warmup quá tỉ mỉ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng rò rỉ thông tin tương lai (Causal Leak Test)&lt;/strong&gt;:
Chạy lượt xuôi với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x1&lt;/code&gt;, sau đó sửa ngẫu nhiên token cuối cùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x2[:, -1] = ...&lt;/code&gt; rồi chạy lại: hiệu tuyệt đối &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max(|out1[:, :-1] - out2[:, :-1]|)&lt;/code&gt; bắt buộc phải bằng đúng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; (hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt; 1e-6&lt;/code&gt; do làm tròn dấu phẩy động).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân biệt mặt nạ tự chú ý (Self-Attention) và chú ý chéo (Cross-Attention)&lt;/strong&gt;:
Trong Decoder, tầng thứ nhất dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;causal_mask&lt;/code&gt; trên chuỗi đích (\(Q, K, V\) đều từ đích); tầng thứ hai dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;src_padding_mask&lt;/code&gt; với \(Q\) từ đích còn \(K, V\) từ đầu ra Encoder.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-lần-theo-luồng-kích-thước-tensor-qua-trọn-vẹn-1-khối-decoder-only-transformer&quot;&gt;Giải thích: Lần theo luồng kích thước Tensor qua trọn vẹn 1 khối Decoder-only Transformer&lt;/h3&gt;

&lt;p&gt;Cho batch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;B = 4&lt;/code&gt;, độ dài chuỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L = 16&lt;/code&gt;, kích thước ẩn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;d_model = 128&lt;/code&gt;, số head &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;H = 4&lt;/code&gt; (\(d_k = 32\)), chiều ẩn FFN &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;d_ff = 512&lt;/code&gt;, từ vựng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;V = 1000&lt;/code&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Bước xử lý&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Phép toán chính&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Kích thước Tensor đầu ra&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;1. Token IDs đầu vào&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Mảng số nguyên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0..999]&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 16)&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;2. Embedding + PosEnc&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;emb(ids) * sqrt(128) + pe[:, :16]&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 16, 128)&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;3. Tách Head Q, K, V&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(128,128) -&amp;gt; view -&amp;gt; transpose&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 4, 16, 32)&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;4. Ma trận điểm Attention&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(Q @ K^T) / sqrt(32)&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 4, 16, 16)&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;5. Ghép Head + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;W_O&lt;/code&gt; + Residual&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transpose -&amp;gt; reshape -&amp;gt; Linear + x&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 16, 128)&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;6. Khối FFN + Residual&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(128,512) -&amp;gt; GELU -&amp;gt; Linear(512,128) + x&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 16, 128)&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;7. LM Head dự đoán từ tiếp theo&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(128, 1000)&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 16, 1000)&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Khi tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CrossEntropyLoss&lt;/code&gt;, ta duỗi 2 chiều đầu của logits thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4*16, 1000) = (64, 1000)&lt;/code&gt; và nhãn đích thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64,)&lt;/code&gt; — khớp chính xác từng chiều một!&lt;/p&gt;

&lt;h1 id=&quot;cài-đặt-cốt-lõi-transformer&quot;&gt;Cài đặt Cốt lõi Transformer&lt;/h1&gt;

&lt;p&gt;Bài này cài đặt các &lt;strong&gt;khối nền tảng&lt;/strong&gt; của một encoder Transformer (cùng lõi attention dùng chung với decoder) bằng PyTorch. Mã nguồn ưu tiên tính minh bạch và kiểm soát đúng kích thước tensor; trong hệ thống sản xuất, các khối này thường được thay bằng hàm tối ưu hóa tích hợp (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scaled_dot_product_attention&lt;/code&gt;) với quy mô lớn hơn.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Ta sẽ xây dựng lần lượt từ dưới lên theo năm thành phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Scaled dot-product attention&lt;/li&gt;
  &lt;li&gt;Multi-head attention&lt;/li&gt;
  &lt;li&gt;Mã hóa vị trí dạng sin–cos&lt;/li&gt;
  &lt;li&gt;Mạng FFN theo từng vị trí&lt;/li&gt;
  &lt;li&gt;Tầng encoder và khối encoder hoàn chỉnh&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mỗi thành phần là một &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Module&lt;/code&gt; độc lập với giao diện &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;forward&lt;/code&gt; rõ ràng để dễ dàng kiểm thử riêng lẻ.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-nhắc-lại-công-thức&quot;&gt;2. Nhắc lại công thức&lt;/h2&gt;

\[\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V\]

\[\mathrm{PE}_{(pos,2i)}=\sin(pos/10000^{2i/d}),\quad
\mathrm{PE}_{(pos,2i+1)}=\cos(pos/10000^{2i/d})\]

&lt;p&gt;Một tầng encoder theo bố cục Pre-LN (được dùng trong mã nguồn bên dưới để tăng ổn định huấn luyện):&lt;/p&gt;

\[\begin{aligned}
X &amp;amp;\leftarrow X + \mathrm{MHA}(\mathrm{LN}(X)) \\
X &amp;amp;\leftarrow X + \mathrm{FFN}(\mathrm{LN}(X))
\end{aligned}\]

&lt;hr /&gt;

&lt;h2 id=&quot;3-kiểm-chứng-luồng-dữ-liệu&quot;&gt;3. Kiểm chứng luồng dữ liệu&lt;/h2&gt;

&lt;p&gt;Ta chạy các chuỗi chỉ số token ngẫu nhiên qua encoder để kiểm tra ba tiêu chí cơ bản:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Đầu ra giữ đúng kích thước \((B, L, d_{\mathrm{model}})\).&lt;/li&gt;
  &lt;li&gt;Mặt nạ nhân quả / đệm triệt tiêu hoàn toàn trọng số tại các vị trí bị cấm.&lt;/li&gt;
  &lt;li&gt;Lượt lan truyền ngược (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss.backward()&lt;/code&gt;) thực thi suôn sẻ, chứng tỏ đồ thị tính toán khả vi hoàn chỉnh.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mục tiêu của bước này là đảm bảo tính chính xác của &lt;strong&gt;kiến trúc và luồng tensor&lt;/strong&gt; trước khi bước sang huấn luyện thực tế.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ScaledDotProductAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    q,k,v: (B, H, L, d_k)  [v last dim may be d_v == d_k here]
    mask:  broadcastable to (B, H, Lq, Lk); True = keep, False = mask out
           (we use bool keep-mask; convert to -inf fill)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;masked_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-inf&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ScaledDotProductAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# (B, L, d) -&amp;gt; (B, H, L, dk)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# (B, H, L, dk) -&amp;gt; (B, L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;contiguous&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# q,k,v: (B, L, d_model)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PositionalEncoding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    PE sin-cos cố định (Vaswani et al.).
    - pos: 0..L-1
    - i: 0..d_model/2-1  →  chiều chẵn 2i = sin, chiều lẻ 2i+1 = cos
    - forward: token_emb + PE  (cùng shape)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;div&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;10000.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;div&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2i
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;div&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2i+1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;register_buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, max_len, d)
&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, L, d)  — thường đã là token embedding
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PositionwiseFFN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;EncoderLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pre-LN encoder layer.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LayerNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self_attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LayerNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ff&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PositionwiseFFN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;self_attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TransformerEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embed&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PositionalEncoding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ModuleList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;EncoderLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln_f&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LayerNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;token_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# token_ids: (B, L)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;embed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;token_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln_f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;subsequent_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bool keep-mask for causal attention: (1, 1, L, L).&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tril&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# -------------------- smoke tests --------------------
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__name__&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;__main__&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;manual_seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TransformerEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ids&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;encoder out&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# causal mask path through MHA directly
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subsequent_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# forbidden future: upper triangle of weights ~ 0
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;future&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diagonal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;future&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;future&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;atol&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;causal multi-head OK&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;backward OK&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;lưu-ý-về-quy-ước-mặt-nạ-mask&quot;&gt;Lưu ý về quy ước mặt nạ (mask)&lt;/h3&gt;

&lt;p&gt;Đoạn mã trên dùng &lt;strong&gt;boolean keep-mask&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;True&lt;/code&gt; nghĩa là vị trí được phép chú ý). Nhiều thư viện lại dùng quy ước ngược lại (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;True&lt;/code&gt; là bị che) hoặc dùng mask số thực cộng (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;). Luôn đọc kỹ tài liệu của hàm đang gọi vì nhầm quy ước mặt nạ là lỗi phổ biến hàng đầu khi cài đặt Transformer.&lt;/p&gt;

&lt;h3 id=&quot;mở-rộng-cho-padding-mask&quot;&gt;Mở rộng cho padding mask&lt;/h3&gt;

&lt;p&gt;Với các chuỗi có độ dài khác nhau trong một batch, hãy tạo mặt nạ kích thước \((B, 1, 1, L)\) (tự broadcast qua các head và vị trí query) gán &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;False&lt;/code&gt; ở các vị trí &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PAD&lt;/code&gt;, sau đó kết hợp bằng phép &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AND&lt;/code&gt; logic với mặt nạ nhân quả khi dùng ở decoder.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.TransformerEncoder&lt;/code&gt;&lt;/strong&gt;: phiên bản tích hợp sẵn trong PyTorch tương ứng với khối vừa viết.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng decoder&lt;/strong&gt;: bổ sung thêm một khối MHA cho cross-attention và mặt nạ nhân quả cho self-attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chia sẻ trọng số (Weight tying)&lt;/strong&gt;: dùng chung ma trận nhúng đầu vào và ma trận chiếu đầu ra trong mô hình ngôn ngữ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SDPA / FlashAttention&lt;/strong&gt;: giữ nguyên kết quả toán học nhưng tối ưu hóa tốc độ và bộ nhớ ở tầng kernel.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-tài-liệu-tham-khảo-liên-quan-đến-cài-đặt&quot;&gt;6. Tài liệu tham khảo liên quan đến cài đặt&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Vaswani et al., 2017&lt;/a&gt; — danh sách module và bộ siêu tham số chuẩn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2207.09238&quot;&gt;Phuong &amp;amp; Hutter, 2022&lt;/a&gt; — mô tả thuật toán chính thức, rất hữu ích khi cài đặt lại từ đầu.&lt;/li&gt;
  &lt;li&gt;Tài liệu PyTorch: &lt;a href=&quot;https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.Transformer&lt;/code&gt;&lt;/a&gt; — giao diện chuẩn dùng cho sản xuất.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-cạm-bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;7. Cạm bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Lỗi thường gặp&lt;/th&gt;
      &lt;th&gt;Cách khắc phục&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Chiều dài bảng PE nhỏ hơn độ dài chuỗi&lt;/td&gt;
      &lt;td&gt;Tăng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max_len&lt;/code&gt; hoặc chuyển sang mã hóa vị trí tương đối / RoPE&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Quên tắt dropout khi đánh giá&lt;/td&gt;
      &lt;td&gt;Luôn gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; kết hợp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.no_grad()&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Không nhất quán hệ số nhân \(\sqrt{d}\) cho embedding&lt;/td&gt;
      &lt;td&gt;Giữ nhất quán theo chuẩn bài báo gốc (nhân \(\sqrt{d_{\mathrm{model}}}\) trước khi cộng PE)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Cộng sai nhánh phần dư&lt;/td&gt;
      &lt;td&gt;Cộng trực tiếp vào &lt;em&gt;đầu vào gốc&lt;/em&gt; của tầng con, không bỏ qua đường tắt&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Phép toán in-place làm hỏng đồ thị gradient&lt;/td&gt;
      &lt;td&gt;Tránh dùng thao tác in-place lên tensor đang cần cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;backward()&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Mẹo:&lt;/strong&gt; khi tự viết lớp attention tùy chỉnh, có thể kiểm tra gradient bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.autograd.gradcheck&lt;/code&gt; trên tensor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; kích thước nhỏ.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-tóm-tắt-các-điểm-chính&quot;&gt;8. Tóm tắt các điểm chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Thứ tự xây dựng tự nhiên là &lt;strong&gt;attention → multi-head → PE → FFN → xếp chồng các tầng&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Bố cục phần dư Pre-LN là lựa chọn mặc định ổn định cho các mô hình nhiều tầng.&lt;/li&gt;
  &lt;li&gt;Quy ước mặt nạ là một phần của giao diện API nên cần ghi chú rõ ràng.&lt;/li&gt;
  &lt;li&gt;Kiểm thử nhanh (smoke test) cho kích thước tensor, ràng buộc nhân quả và lan truyền ngược là bước bắt buộc trước khi huấn luyện.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bài tiếp theo sẽ chạy thử huấn luyện trên bài toán nhỏ, tổng hợp tài liệu nền tảng và danh mục gỡ lỗi vận hành.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến); các đường dẫn dưới đây được lưu lại để tra cứu và ghi nhận nguồn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1306224801415127&quot;&gt;Position Encoding trong Transformer (từng bước)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Hướng dẫn cài đặt chi tiết từ đầu các module cốt lõi của Transformer (video dài, rất sát với bài này).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown (tiếng Anh). Sơ đồ luồng dữ liệu trực quan để đối chiếu song song khi viết mã.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Positional embeddings in transformers EXPLAINED&lt;/td&gt;
          &lt;td&gt;Demystifying positional encodings.](https://www.youtube.com/watch?v=1biZfFLPRSY) — AI Coffee Break with Letitia (tiếng Anh). Giải thích chi tiết vai trò của mã hóa vị trí khi mô hình cần nhận diện thứ tự chuỗi.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-01-01 Lý thuyết Transformer</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_01_01_Transformer_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_01_01_Transformer_Theory</id>
   <content type="html">&lt;p&gt;Nếu Self-Attention là “phòng họp” nơi các từ trao đổi thông tin với nhau, thì câu hỏi đặt ra là: &lt;em&gt;tại sao sau mỗi phòng họp, Transformer lại phải cho từng từ đi vào một “phòng làm việc riêng” gọi là FFN, rồi lại phải chuẩn hóa bằng LayerNorm và cộng đường tắt Residual?&lt;/em&gt; Bài học lý thuyết này giải mã chính xác từng mắt xích toán học giữ cho cả cỗ máy Transformer 100 tầng vẫn huấn luyện mượt mà.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-lý-thuyết-của-transformer&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột lý thuyết của Transformer&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mã hóa vị trí lượng giác (Sinusoidal Positional Encoding)&lt;/strong&gt;:
Dùng cặp \(\sin(\text{pos}/10000^{2i/d})\) và \(\cos(\text{pos}/10000^{2i/d})\) ở nhiều tần số khác nhau — nhờ công thức cộng góc lượng giác, vị trí \(\text{pos} + k\) luôn là một phép &lt;strong&gt;biến đổi tuyến tính&lt;/strong&gt; (ma trận xoay 2D) của vị trí \(\text{pos}\), giúp mô hình dễ dàng học khoảng cách tương đối!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pre-LN vs. Post-LN (Vị trí đặt LayerNorm)&lt;/strong&gt;:
Bài báo gốc đặt LayerNorm &lt;em&gt;sau&lt;/em&gt; phép cộng residual (Post-LN: \(\text{LN}(x + F(x))\)) nên rất nhạy với learning rate và bắt buộc phải có warmup kỹ. Hầu hết LLM hiện đại chuyển sang &lt;strong&gt;Pre-LN&lt;/strong&gt; (\(x + F(\text{LN}(x))\)) để giữ đường cao tốc gradient thông suốt tuyệt đối từ tầng cuối về tầng đầu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Position-wise Feed-Forward Network (FFN)&lt;/strong&gt;:
Nếu chỉ xếp chồng các tầng Attention thuần túy, sự kết hợp giữa các giá trị chủ yếu vẫn mang tính tuyến tính theo trọng số; FFN chiếu lên chiều \(4 d_{\text{model}}\) qua ReLU/GELU/SwiGLU để tạo sức biểu đạt phi tuyến giàu có cho từng token.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Liên kết trọng số (Weight Tying) và hệ số \(\sqrt{d_{\text{model}}}\)&lt;/strong&gt;:
Chia sẻ chung ma trận giữa bảng Token Embedding đầu vào và tầng Linear dự đoán từ vựng đầu ra (LM Head) giúp tiết kiệm hàng chục triệu tham số, đồng thời nhân embedding với \(\sqrt{d_{\text{model}}}\) để tín hiệu ngữ nghĩa không bị lấn át bởi Positional Encoding có biên độ \(\in [-1, 1]\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-vector-positional-encoding-lượng-giác-tại-3-vị-trí-đầu-tiên-d_textmodel--4&quot;&gt;Giải thích: Tính tay vector Positional Encoding lượng giác tại 3 vị trí đầu tiên (\(d_{\text{model}} = 4\))&lt;/h3&gt;

&lt;p&gt;Với \(d_{\text{model}} = 4\), ta có 2 cặp chỉ số tần số:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Cặp \(i = 0\) (tần số cao): \(\omega_0 = 1 / 10000^{0/4} = 1\) \(\to\) \((\sin(\text{pos}), \; \cos(\text{pos}))\)&lt;/li&gt;
  &lt;li&gt;Cặp \(i = 1\) (tần số thấp): \(\omega_1 = 1 / 10000^{2/4} = 1/100 = 0{,}01\) \(\to\) \((\sin(0{,}01\,\text{pos}), \; \cos(0{,}01\,\text{pos}))\)&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Vị trí &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pos&lt;/code&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Chiều 0: \(\sin(\text{pos})\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Chiều 1: \(\cos(\text{pos})\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Chiều 2: \(\sin(0{,}01\,\text{pos})\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Chiều 3: \(\cos(0{,}01\,\text{pos})\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pos = 0&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}0000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1{,}0000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}0000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1{,}0000\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pos = 1&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}8415\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}5403\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}0100\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}9999\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pos = 2&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}9093\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(-0{,}4161\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}0200\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}9998\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Hãy tưởng tượng một chiếc đồng hồ nhị phân liên tục: cặp chiều &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(0, 1)&lt;/code&gt; đóng vai trò “kim giây” quay rất nhanh để phân biệt các từ kề nhau, còn cặp chiều &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(2, 3)&lt;/code&gt; đóng vai trò “kim giờ” quay chậm rãi để phân biệt các đoạn văn cách nhau hàng trăm từ!&lt;/p&gt;

&lt;h1 id=&quot;lý-thuyết-transformer&quot;&gt;Lý thuyết Transformer&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_architecture.png&quot; alt=&quot;Transformer Architecture&quot; /&gt;
&lt;em&gt;Kiến trúc Transformer encoder–decoder (Vaswani et al., 2017). Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Transformer là kiến trúc xử lý dữ liệu chuỗi (và các dạng dữ liệu biểu diễn được thành chuỗi) dựa chủ yếu trên &lt;strong&gt;attention đa đầu&lt;/strong&gt; (&lt;em&gt;multi-head attention&lt;/em&gt;) và &lt;strong&gt;mạng feed-forward theo từng vị trí&lt;/strong&gt; (&lt;em&gt;position-wise feed-forward network&lt;/em&gt;), kết hợp với kết nối phần dư (&lt;em&gt;residual connection&lt;/em&gt;) và chuẩn hóa lớp (&lt;em&gt;layer normalization&lt;/em&gt;). Được Vaswani và cộng sự (2017) đề xuất cho dịch máy, Transformer loại bỏ hoàn toàn các tầng hồi quy và tích chập khỏi luồng xử lý chuỗi chính.&lt;/p&gt;

&lt;h3 id=&quot;vì-sao-cải-tiến-rnn-là-chưa-đủ&quot;&gt;Vì sao cải tiến RNN là chưa đủ&lt;/h3&gt;

&lt;p&gt;Ngay cả các kiến trúc hồi quy tiên tiến như LSTM hay GRU vẫn chịu ba giới hạn cấu trúc:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Giới hạn&lt;/th&gt;
      &lt;th&gt;Hệ quả&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Cập nhật trạng thái tuần tự từ trái sang phải&lt;/td&gt;
      &lt;td&gt;Khó song song hóa theo độ dài chuỗi khi huấn luyện&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Đường truyền phụ thuộc dài&lt;/td&gt;
      &lt;td&gt;Tín hiệu từ token đầu chuỗi phải đi qua nhiều bước mới ảnh hưởng đến vị trí cuối&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Trạng thái ẩn kích thước cố định&lt;/td&gt;
      &lt;td&gt;Tạo nút thắt mềm khi cần lưu giữ ngữ cảnh rất phong phú&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Cơ chế attention cho thấy mô hình có thể trực tiếp truy xuất các trạng thái liên quan. Transformer đi thêm một bước quyết định: loại bỏ hẳn phần hồi quy, để mọi tầng cho phép các vị trí chú ý trực tiếp tới nhau (kèm mặt nạ khi cần) rồi biến đổi phi tuyến độc lập trên từng vị trí bằng mạng MLP.&lt;/p&gt;

&lt;h3 id=&quot;ba-dòng-kiến-trúc-chính&quot;&gt;Ba dòng kiến trúc chính&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Dòng kiến trúc&lt;/th&gt;
      &lt;th&gt;Cấu trúc attention&lt;/th&gt;
      &lt;th&gt;Mô hình tiêu biểu&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Chỉ-encoder (&lt;em&gt;Encoder-only&lt;/em&gt;)&lt;/td&gt;
      &lt;td&gt;Self-attention hai chiều&lt;/td&gt;
      &lt;td&gt;BERT, RoBERTa&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Chỉ-decoder (&lt;em&gt;Decoder-only&lt;/em&gt;)&lt;/td&gt;
      &lt;td&gt;Self-attention nhân quả (&lt;em&gt;causal&lt;/em&gt;)&lt;/td&gt;
      &lt;td&gt;GPT-2/3/4, LLaMA&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Encoder–decoder&lt;/td&gt;
      &lt;td&gt;Encoder kết hợp decoder có cross-attention&lt;/td&gt;
      &lt;td&gt;Transformer gốc, T5, BART&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Cả ba dòng đều dùng chung các khối nền tảng, chỉ khác nhau ở mẫu mặt nạ attention và mục tiêu huấn luyện.&lt;/p&gt;

&lt;h3 id=&quot;cấu-trúc-tổng-thể&quot;&gt;Cấu trúc tổng thể&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Nhúng token kết hợp mã hóa vị trí.&lt;/li&gt;
  &lt;li&gt;Các tầng encoder xếp chồng: self-attention → FFN (mỗi tầng con kèm kết nối phần dư và chuẩn hóa lớp).&lt;/li&gt;
  &lt;li&gt;Các tầng decoder xếp chồng: masked self-attention → cross-attention → FFN.&lt;/li&gt;
  &lt;li&gt;Lớp chiếu tuyến tính đầu ra sang không gian từ vựng (cho tác vụ sinh) hoặc đầu phân loại (cho tác vụ hiểu).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/tf_full_arch_multihead_zoom.jpg&quot; alt=&quot;Toàn cảnh kiến trúc + Multi-Head / Scaled Dot-Product&quot; /&gt;
&lt;em&gt;Hình: Kiến trúc encoder–decoder cùng chi tiết multi-head attention và scaled dot-product. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Chương 07 đã trình bày chi tiết toán học của attention; bài này ghép các phép toán đó thành &lt;strong&gt;hệ thống hoàn chỉnh&lt;/strong&gt;, tập trung vào &lt;strong&gt;mã hóa vị trí&lt;/strong&gt; và &lt;strong&gt;cấu trúc từng tầng&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;
&lt;h3 id=&quot;21-biểu-diễn-đầu-vào&quot;&gt;2.1 Biểu diễn đầu vào&lt;/h3&gt;

&lt;p&gt;Với chuỗi chỉ số token \(t_1,\ldots,t_L\), ma trận nhúng \(E\) ánh xạ từng token thành vectơ, sau đó cộng với vectơ mã hóa vị trí \(\mathbf{p}_i\):&lt;/p&gt;

\[\mathbf{x}_i^{(0)} = E_{t_i} + \mathbf{p}_i \in \mathbb{R}^{d_{\mathrm{model}}}\]

&lt;p&gt;Xếp các hàng theo thứ tự ta thu được ma trận đầu vào:&lt;/p&gt;

\[\mathbf{X}^{(0)} \in \mathbb{R}^{L \times d_{\mathrm{model}}}.\]

&lt;p&gt;(Trong mã nguồn thực tế có thêm chiều batch \(B\), tức kích thước \((B, L, d)\).)&lt;/p&gt;

&lt;h3 id=&quot;22-scaled-multi-head-self-attention&quot;&gt;2.2 Scaled multi-head self-attention&lt;/h3&gt;

&lt;p&gt;Với các ma trận chiếu học được (chi tiết xem Chương 07):&lt;/p&gt;

\[\mathrm{MultiHead}(\mathbf{X})
= \mathrm{Concat}_h\!\left(
  \mathrm{Attention}(\mathbf{X}W_h^Q,\mathbf{X}W_h^K,\mathbf{X}W_h^V)
\right) W^O\]

\[\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V\]

&lt;p&gt;trong đó \(M\) là ma trận mặt nạ cộng (padding và/hoặc causal). Trong tầng Transformer, đây là bước &lt;strong&gt;trao đổi thông tin&lt;/strong&gt; giữa các vị trí.&lt;/p&gt;

&lt;h3 id=&quot;23-mạng-feed-forward-theo-vị-trí-ffn&quot;&gt;2.3 Mạng feed-forward theo vị trí (FFN)&lt;/h3&gt;

&lt;p&gt;Mạng FFN áp dụng &lt;strong&gt;độc lập&lt;/strong&gt; lên từng vị trí với cùng một bộ trọng số:&lt;/p&gt;

\[\mathrm{FFN}(\mathbf{z}) = W_2\,\sigma(W_1\mathbf{z}+\mathbf{b}_1)+\mathbf{b}_2\]

&lt;p&gt;Kích thước trung gian thường mở rộng theo tỷ lệ \(d_{\mathrm{model}} \to d_{\mathrm{ff}} \to d_{\mathrm{model}}\) với \(d_{\mathrm{ff}} \approx 4\,d_{\mathrm{model}}\). Hàm kích hoạt \(\sigma\) là ReLU trong bài báo gốc, còn các mô hình mới hơn thường dùng GELU hoặc SwiGLU.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vai trò của FFN:&lt;/strong&gt; Multi-head attention chủ yếu thực hiện phép trộn tuyến tính có trọng số động giữa các vectơ value. Nếu thiếu lớp MLP phi tuyến trên từng vị trí, năng lực biến đổi đặc trưng trên từng token sẽ bị hạn chế. Có thể tóm tắt ngắn gọn: attention đảm nhiệm &lt;em&gt;trộn thông tin&lt;/em&gt;, còn FFN đảm nhiệm &lt;em&gt;tính toán phi tuyến&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;24-kết-nối-phần-dư-và-chuẩn-hóa-lớp-layernorm&quot;&gt;2.4 Kết nối phần dư và chuẩn hóa lớp (&lt;em&gt;LayerNorm&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Bài báo gốc bố trí chuẩn hóa sau phép cộng phần dư (&lt;strong&gt;Post-LN&lt;/strong&gt;):&lt;/p&gt;

\[\mathbf{Y} = \mathrm{LayerNorm}\big(\mathbf{X} + \mathrm{Sublayer}(\mathbf{X})\big)\]

&lt;p&gt;trong đó Sublayer là MultiHead hoặc FFN. Nhiều kiến trúc hiện đại chuyển sang bố cục &lt;strong&gt;Pre-LN&lt;/strong&gt;:&lt;/p&gt;

\[\mathbf{Y} = \mathbf{X} + \mathrm{Sublayer}\big(\mathrm{LayerNorm}(\mathbf{X})\big)\]

&lt;p&gt;vì giúp quá trình huấn luyện ổn định hơn khi mạng có nhiều tầng sâu. Kết nối phần dư tạo đường truyền trực tiếp cho gradient, còn LayerNorm giữ thang giá trị kích hoạt ổn định qua các tầng.&lt;/p&gt;

&lt;h3 id=&quot;25-tầng-encoder-đầy-đủ&quot;&gt;2.5 Tầng encoder đầy đủ&lt;/h3&gt;

&lt;p&gt;Ở dạng Post-LN (như bài báo gốc):&lt;/p&gt;

\[\begin{aligned}
\mathbf{U} &amp;amp;= \mathrm{LayerNorm}\big(\mathbf{X} + \mathrm{MultiHeadSelfAttn}(\mathbf{X})\big) \\
\mathbf{Z} &amp;amp;= \mathrm{LayerNorm}\big(\mathbf{U} + \mathrm{FFN}(\mathbf{U})\big)
\end{aligned}\]

&lt;p&gt;Toàn bộ encoder gồm \(N\) tầng như vậy xếp nối tiếp (mô hình gốc dùng \(N=6\), các LLM hiện đại có thể dùng hàng chục đến hơn một trăm tầng).&lt;/p&gt;

&lt;h3 id=&quot;26-tầng-decoder-đầy-đủ&quot;&gt;2.6 Tầng decoder đầy đủ&lt;/h3&gt;

&lt;p&gt;Mỗi tầng decoder gồm ba tầng con:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Masked self-attention&lt;/strong&gt; trên các token đích đã sinh (áp dụng mặt nạ nhân quả).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-attention&lt;/strong&gt; với query lấy từ decoder, còn key và value lấy từ đầu ra của encoder.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FFN&lt;/strong&gt; tương tự phía encoder.&lt;/li&gt;
&lt;/ol&gt;

\[\begin{aligned}
\mathbf{U} &amp;amp;= \mathrm{LN}\big(\mathbf{Y} + \mathrm{MaskedSelfAttn}(\mathbf{Y})\big) \\
\mathbf{V} &amp;amp;= \mathrm{LN}\big(\mathbf{U} + \mathrm{CrossAttn}(\mathbf{U}, \mathbf{H}_{\mathrm{enc}}, \mathbf{H}_{\mathrm{enc}})\big) \\
\mathbf{Z} &amp;amp;= \mathrm{LN}\big(\mathbf{V} + \mathrm{FFN}(\mathbf{V})\big)
\end{aligned}\]

&lt;p&gt;&lt;strong&gt;Mặt nạ nhân quả (causal mask):&lt;/strong&gt; Với query ở vị trí \(i\), các key ở vị trí \(j &amp;gt; i\) bị chặn để mô hình không nhìn trước đáp án khi huấn luyện bằng &lt;em&gt;teacher forcing&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;27-mã-hóa-vị-trí-dạng-sincos&quot;&gt;2.7 Mã hóa vị trí dạng sin–cos&lt;/h3&gt;

&lt;p&gt;Vì attention thuần có tính đồng biến theo hoán vị (&lt;em&gt;permutation equivariant&lt;/em&gt;), thứ tự token sẽ vô nghĩa nếu không có tín hiệu vị trí. Công thức mã hóa vị trí gốc:&lt;/p&gt;

\[\begin{aligned}
PE_{(pos,2i)} &amp;amp;= \sin\!\big(pos / 10000^{2i/d_{\mathrm{model}}}\big) \\
PE_{(pos,2i+1)} &amp;amp;= \cos\!\big(pos / 10000^{2i/d_{\mathrm{model}}}\big)
\end{aligned}\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_formula_and_token_matrix.jpg&quot; alt=&quot;Công thức PE + ma trận token&quot; /&gt;
&lt;em&gt;Hình: Mỗi token tương ứng một vectơ kích thước \(d_{\mathrm{model}}\); PE dùng hàm sin/cos theo vị trí \(pos\) và chỉ số tần số \(i\). (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_pos_index_sentence.jpg&quot; alt=&quot;pos = chỉ số từ trong câu&quot; /&gt;
&lt;em&gt;Hình: Chỉ số vị trí \(pos = 0,1,2,\ldots\) đánh số theo thứ tự token trong câu. (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cách ánh xạ chỉ số chiều:&lt;/strong&gt; Với \(d_{\mathrm{model}}=512\), chỉ số \(i\) chạy từ \(0\) đến \(255\); mỗi giá trị \(i\) tạo &lt;strong&gt;hai&lt;/strong&gt; chiều — chiều chẵn \(2i\) dùng &lt;strong&gt;sin&lt;/strong&gt; và chiều lẻ \(2i+1\) dùng &lt;strong&gt;cos&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_i_range_sin_cos_dims.jpg&quot; alt=&quot;Bảng i → chiều sin/cos&quot; /&gt;
&lt;em&gt;Hình: \(i=0\) tương ứng chiều 0 (sin) và 1 (cos); …; \(i=255\) tương ứng chiều 510 và 511. (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_even_odd_dims.jpg&quot; alt=&quot;Chiều chẵn sin / lẻ cos&quot; /&gt;
&lt;em&gt;Hình: Gán hàm sin vào các chiều chẵn và hàm cos vào các chiều lẻ của vectơ PE. (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_sin_cos_formula_plot.jpg&quot; alt=&quot;Sin và cos&quot; /&gt;
&lt;em&gt;Hình: Cặp sóng sin/cos cùng tần số làm cơ sở cho mã hóa vị trí. (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_multiple_frequencies_i.jpg&quot; alt=&quot;Nhiều tần số theo i&quot; /&gt;
&lt;em&gt;Hình: Mỗi chỉ số \(i\) ứng với một tần số khác nhau: \(i\) nhỏ ứng với sóng dao động nhanh (tần số cao), \(i\) lớn ứng với sóng dao động chậm (tần số thấp). (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tạo vectơ PE tại một vị trí:&lt;/strong&gt; Cố định \(pos\), với mỗi chỉ số \(i\) ta lấy giá trị sin và cos tương ứng rồi ghép thành vectơ dài \(d_{\mathrm{model}}\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_sample_values_pos0.jpg&quot; alt=&quot;Lấy PE tại pos=0&quot; /&gt;
&lt;em&gt;Hình: Cột giá trị tại \(pos=0\) tạo thành vectơ PE cho token đầu tiên. (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_sample_values_pos3.jpg&quot; alt=&quot;Lấy PE tại pos=3&quot; /&gt;
&lt;em&gt;Hình: Tại \(pos=3\), các sóng đã lệch pha nên tạo ra vectơ PE khác biệt. (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cộng vào token embedding:&lt;/strong&gt; Vì có cùng số chiều, vectơ PE được cộng trực tiếp theo từng phần tử vào token embedding:&lt;/p&gt;

\[\mathbf{x}_{pos} = \mathrm{TokenEmb}(w_{pos}) + \mathrm{PE}_{pos}\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_input_emb_vs_positional.jpg&quot; alt=&quot;Token emb vs PE (cùng 512-d)&quot; /&gt;
&lt;em&gt;Hình: Token embedding và PE có cùng chiều \(d_{\mathrm{model}}\) và được cộng theo từng phần tử để gắn thông tin thứ tự vào biểu diễn nội dung. (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_token_emb_plus_pe_columns.jpg&quot; alt=&quot;Cột token emb (tím) + cột PE (xanh)&quot; /&gt;
&lt;em&gt;Hình: Mỗi vị trí gồm một cột token embedding cộng với cột PE tương ứng. (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Các đặc điểm chính của PE dạng sin–cos:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Xác định sẵn, không cần tham số học.&lt;/li&gt;
  &lt;li&gt;Tạo biểu diễn riêng biệt cho từng vị trí nhờ tổ hợp nhiều tần số.&lt;/li&gt;
  &lt;li&gt;Độ dịch vị trí tương đối \(PE_{pos+k}\) có thể biểu diễn dưới dạng phép biến đổi tuyến tính của \(PE_{pos}\), thuận lợi cho việc học quan hệ khoảng cách.&lt;/li&gt;
  &lt;li&gt;Về lý thuyết có khả năng ngoại suy sang độ dài lớn hơn lúc huấn luyện tốt hơn so với embedding vị trí tuyệt đối học trực tiếp (dù trong thực tế vẫn có giới hạn).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Các phương án thay thế:&lt;/strong&gt; embedding vị trí tuyệt đối học được (BERT, GPT-2), độ lệch vị trí tương đối (T5, Shaw et al.) và RoPE (phổ biến trong các LLM hiện đại). Tất cả đều giải quyết cùng một nhu cầu là đưa thông tin thứ tự vào cơ chế trộn theo nội dung.&lt;/p&gt;

&lt;h3 id=&quot;28-độ-phức-tạp-tính-toán&quot;&gt;2.8 Độ phức tạp tính toán&lt;/h3&gt;

&lt;p&gt;Self-attention đầy đủ tốn \(O(L^2 d)\) phép tính và \(O(L^2)\) bộ nhớ cho ma trận điểm số — đây là chi phí đổi lấy khả năng tương tác trực tiếp toàn cục. Với độ dài câu hoặc đoạn thông thường, chi phí này hoàn toàn khả thi; với văn bản rất dài, các biến thể attention thưa hoặc tuyến tính được sử dụng để giảm tải.&lt;/p&gt;

&lt;h3 id=&quot;29-mục-tiêu-huấn-luyện&quot;&gt;2.9 Mục tiêu huấn luyện&lt;/h3&gt;

&lt;p&gt;Trong bài toán dịch máy gốc, encoder đọc chuỗi nguồn còn decoder dự đoán từng token đích bằng hàm mất mát cross-entropy theo cơ chế &lt;em&gt;teacher forcing&lt;/em&gt;. Các mô hình chỉ-encoder hiện đại dùng mục tiêu mô hình ngôn ngữ có che (Masked LM), còn mô hình chỉ-decoder dùng dự đoán token kế tiếp (Causal LM). Kiến trúc cốt lõi giữ nguyên; sự thay đổi nằm ở mẫu mặt nạ và mục tiêu huấn luyện.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;h3 id=&quot;31-đường-đi-của-một-token-trong-encoder&quot;&gt;3.1 Đường đi của một token trong encoder&lt;/h3&gt;

&lt;p&gt;Xét câu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;I love deep learning&lt;/code&gt; tại vị trí từ &lt;strong&gt;learning&lt;/strong&gt;. Ở tầng self-attention đầu tiên, query của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;learning&lt;/code&gt; có thể gán trọng số lớn cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;deep&lt;/code&gt; và chính nó, tạo ra biểu diễn mang nghĩa cụm &lt;em&gt;“deep learning”&lt;/em&gt; thay vì nghĩa rời rạc của từ &lt;em&gt;“learning”&lt;/em&gt;. Sau đó FFN biến đổi phi tuyến biểu diễn này. Quá trình trên diễn ra &lt;strong&gt;song song&lt;/strong&gt; cho cả bốn từ chỉ trong một lượt nhân ma trận, thay vì bốn bước tuần tự như RNN.&lt;/p&gt;

&lt;h3 id=&quot;32-một-bước-giải-mã-trong-decoder&quot;&gt;3.2 Một bước giải mã trong decoder&lt;/h3&gt;

&lt;p&gt;Khi sinh từ tiếng Pháp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;profond&lt;/code&gt; sau chuỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;J&apos; aime l&apos;apprentissage&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Masked self-attention&lt;/strong&gt; chỉ chú ý tới các từ tiếng Pháp đã sinh trước đó để giữ mạch câu nhất quán.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-attention&lt;/strong&gt; tra cứu các trạng thái encoder tiếng Anh và tập trung trọng số vào từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;deep&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FFN cùng lớp softmax trên từ vựng&lt;/strong&gt; dự đoán từ tiếp theo là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;profond&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nếu mặt nạ nhân quả cài đặt sai, mô hình sẽ đọc được đáp án tương lai lúc huấn luyện nhưng hoạt động kém hẳn khi suy luận tự hồi quy thực tế.&lt;/p&gt;

&lt;h3 id=&quot;33-so-sánh-chỉ-encoder-và-chỉ-decoder&quot;&gt;3.3 So sánh chỉ-encoder và chỉ-decoder&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;BERT (chỉ-encoder):&lt;/strong&gt; dùng self-attention hai chiều cùng Masked LM, phù hợp các bài toán hiểu và trích xuất biểu diễn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GPT (chỉ-decoder):&lt;/strong&gt; dùng self-attention nhân quả cùng mục tiêu dự đoán token kế tiếp, phù hợp các bài toán sinh văn bản.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cả hai đều sử dụng cùng khối MultiHead Attention và FFN, chỉ khác mặt nạ và luồng dữ liệu.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-mã-minh-họa-bám-theo-phương-trình&quot;&gt;4. Mã minh họa bám theo phương trình&lt;/h2&gt;

&lt;p&gt;Cài đặt tối giản cho một tầng encoder theo bố cục Pre-LN:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyEncoderLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LayerNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MultiheadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LayerNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ff&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key_padding_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key_padding_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key_padding_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyEncoderLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 10, 64)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Các module cài đặt đầy đủ từ đầu sẽ được trình bày ở các bài thực hành tiếp theo.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Seq2seq dùng RNN&lt;/strong&gt;: cùng mô hình mã hóa–giải mã nhưng Transformer thay tầng hồi quy bằng attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập (CNN)&lt;/strong&gt;: bộ lọc cục bộ có trọng số cố định, đối lập với phép trộn toàn cục có trọng số động của attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mạng phần dư (ResNet)&lt;/strong&gt;: giúp xếp chồng nhiều tầng sâu mà không làm suy giảm gradient.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các mục tiêu tiền huấn luyện&lt;/strong&gt;: Masked LM (BERT), Causal LM (GPT) và khôi phục đoạn bị che (T5).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vision Transformer (ViT)&lt;/strong&gt;: chia ảnh thành các mảng (patch) rồi xử lý như chuỗi token bằng chính kiến trúc encoder Transformer.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Vaswani et al., 2017 — Attention Is All You Need&lt;/a&gt; — đề xuất kiến trúc Transformer gốc.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;Devlin et al., 2019 — BERT&lt;/a&gt; — tiền huấn luyện encoder hai chiều.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf&quot;&gt;Radford et al., 2019 — GPT-2&lt;/a&gt; — mô hình ngôn ngữ nhân quả quy mô lớn và khả năng zero-shot.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;Dosovitskiy et al., 2021 — ViT&lt;/a&gt; — ứng dụng Transformer cho thị giác máy tính.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2207.09238&quot;&gt;Phuong &amp;amp; Hutter, 2022 — Formal Algorithms for Transformers&lt;/a&gt; — đặc tả thuật toán chính thức, rõ ràng cho các biến thể Transformer.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-cạm-bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;7. Cạm bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thiếu mã hóa vị trí&lt;/strong&gt; khiến mô hình không phân biệt được thứ tự từ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dùng giá trị &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; thay vì \(-\infty\)&lt;/strong&gt; cho causal mask trước softmax gây rò rỉ thông tin tương lai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quên padding mask&lt;/strong&gt; khi huấn luyện theo batch gồm các chuỗi có độ dài khác nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thiếu hệ số chia \(1/\sqrt{d_k}\)&lt;/strong&gt; khi chiều head lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhầm cấu hình Post-LN với Pre-LN&lt;/strong&gt; khi sao chép lịch tốc độ học và warmup từ tài liệu khác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mẹo:&lt;/strong&gt; luôn viết unit-test kiểm tra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;triu(weights, 1) ≈ 0&lt;/code&gt; cho causal attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mẹo:&lt;/strong&gt; thử nghiệm trước với mô hình nhỏ 2 tầng rồi mới mở rộng độ sâu và bề rộng.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-tóm-tắt-các-điểm-chính&quot;&gt;8. Tóm tắt các điểm chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Mỗi tầng Transformer kết hợp &lt;strong&gt;attention (trao đổi thông tin)&lt;/strong&gt; và &lt;strong&gt;FFN (biến đổi cục bộ)&lt;/strong&gt; cùng kết nối phần dư và chuẩn hóa lớp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mẫu mặt nạ&lt;/strong&gt; quyết định dòng kiến trúc: hai chiều (encoder), nhân quả (decoder) hay chéo (cross-attention).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mã hóa vị trí&lt;/strong&gt; bù đắp việc self-attention thuần không tự nhận biết thứ tự.&lt;/li&gt;
  &lt;li&gt;Encoder và decoder ghép các tầng cùng loại để giải quyết dịch máy và nhiều bài toán chuỗi khác.&lt;/li&gt;
  &lt;li&gt;BERT, GPT và ViT đều xây dựng trên cùng một khuôn mẫu kiến trúc, chỉ khác mặt nạ, mục tiêu huấn luyện và loại dữ liệu đầu vào.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Tiếp theo, ta sẽ cài đặt chi tiết từng khối trong bài &lt;strong&gt;08-01-02&lt;/strong&gt;.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến); các đường dẫn dưới đây được lưu lại để tra cứu và ghi nhận nguồn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1007473105556936&quot;&gt;Attention trong Transformer (Self, Masked, Cross, Multi-Head)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1306224801415127&quot;&gt;Position Encoding trong Transformer (từng bước)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown (tiếng Anh). Trình bày trọn vẹn các thành phần embedding, attention, MLP, softmax và nhiệt độ tương ứng với bài lý thuyết.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown (tiếng Anh). Đi sâu vào phép tính attention bên trong khối Transformer.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Gc0HXCWT0IA&quot;&gt;Tất cả những gì bạn cần biết về Transformer trong 35 phút&lt;/a&gt; — Việt Nguyễn AI (tiếng Việt). Tổng quan đầy đủ về kiến trúc Transformer bằng tiếng Việt.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08 Kiến trúc Transformer</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter08/08_00_Introduction</id>
   <content type="html">&lt;p&gt;Tháng 6 năm 2017, tám nhà nghiên cứu tại Google công bố một bài báo mang tựa đề đầy thách thức: &lt;em&gt;“Attention Is All You Need”&lt;/em&gt;. Họ loại bỏ hoàn toàn vòng lặp hồi quy của RNN/LSTM, thay thế bằng một kiến trúc hoàn toàn song song mang tên &lt;strong&gt;Transformer&lt;/strong&gt;. Ít ai ngờ rằng chỉ vài năm sau, chính bản thiết kế 15 trang giấy ấy lại trở thành nền móng thống nhất cho cả ChatGPT, Claude, Gemini, AlphaFold 2 dự đoán cấu trúc protein, Vision Transformer lẫn các mô hình sinh video hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-kiến-trúc-transformer&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Kiến trúc Transformer&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bỏ tuần tự hóa — Mở khóa song song hóa toàn phần trên GPU&lt;/strong&gt;:
Khác với RNN phải đợi \(h_{t-1}\) mới tính được \(h_t\), Transformer xử lý đồng thời cả \(L\) token trong một lượt nhân ma trận, rút ngắn thời gian huấn luyện từ hàng tuần xuống hàng giờ trên quy mô dữ liệu khổng lồ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mã hóa vị trí (Positional Encoding) — Trả lại khái niệm thứ tự&lt;/strong&gt;:
Bản thân Self-Attention có tính bất biến hoán vị (đảo vị trí các từ cho kết quả như nhau), nên ta bắt buộc phải cộng thêm tín hiệu vị trí (sin/cos, learned, hoặc RoPE) vào embedding đầu vào.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khối chuẩn hóa lặp lại: Attention + FFN + Residual + LayerNorm&lt;/strong&gt;:
Mỗi tầng Transformer thực hiện hai nhịp đều đặn: &lt;strong&gt;trộn thông tin giữa các token&lt;/strong&gt; (Multi-Head Attention) rồi &lt;strong&gt;biến đổi phi tuyến độc lập trên từng token&lt;/strong&gt; (Position-wise FFN), luôn được bọc bởi kết nối tắt và LayerNorm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ba nhánh kiến trúc dẫn xuất (Encoder-only, Decoder-only, Encoder–Decoder)&lt;/strong&gt;:
BERT (Encoder-only, hiểu ngữ cảnh hai chiều), GPT/Llama (Decoder-only, sinh văn bản tự hồi quy), và T5/Transformer gốc (Encoder–Decoder, dịch máy và chuyển đổi chuỗi–chuỗi).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-đối-chiếu-bằng-số-3-chỉ-số-quan-trọng-giữa-rnn-cnn-và-self-attention-trên-chuỗi-dài-l&quot;&gt;Giải thích: Đối chiếu bằng số 3 chỉ số quan trọng giữa RNN, CNN và Self-Attention trên chuỗi dài \(L\)&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Tầng xử lý&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Độ phức tạp tính toán / tầng&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Số bước tuần tự (không song song được)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Độ dài đường đi dài nhất giữa 2 từ cách xa \(L\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;RNN / LSTM&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(O(L \cdot d^2)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(O(L)\)&lt;/strong&gt; (nút thắt huấn luyện)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(O(L)\)&lt;/strong&gt; (khó học phụ thuộc xa)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;CNN 1D (nhân \(k\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(O(k \cdot L \cdot d^2)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(O(1)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(O(\log_k L)\) (cần xếp nhiều tầng giãn)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Self-Attention&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(O(L^2 \cdot d)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(O(1)\)&lt;/strong&gt; (song song toàn phần)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(O(1)\)&lt;/strong&gt; (mọi cặp từ nối thẳng trực tiếp)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Khi độ dài chuỗi \(L &amp;lt; d\) (ví dụ \(L = 512, \; d = 1024\)), Self-Attention vừa nhanh hơn RNN, vừa song song hóa tuyệt đối, vừa kết nối trực tiếp mọi cặp token trong đúng 1 bước!&lt;/p&gt;

&lt;h1 id=&quot;chương-08--kiến-trúc-transformer&quot;&gt;Chương 08 — Kiến trúc Transformer&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_architecture.png&quot; alt=&quot;Transformer Architecture&quot; /&gt;
&lt;em&gt;Kiến trúc Transformer đầy đủ (encoder–decoder) từ bài báo “Attention Is All You Need”. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;vì-sao-cần-kiến-trúc-transformer&quot;&gt;Vì sao cần kiến trúc Transformer&lt;/h2&gt;

&lt;p&gt;Chương 07 đã trình bày &lt;strong&gt;cơ chế chú ý&lt;/strong&gt; (&lt;em&gt;attention&lt;/em&gt;) như một phép tra cứu mềm tổng quát dựa trên truy vấn (&lt;em&gt;query&lt;/em&gt;), khóa (&lt;em&gt;key&lt;/em&gt;) và giá trị (&lt;em&gt;value&lt;/em&gt;). Kiến trúc Transformer đưa ý tưởng này lên làm thành phần trung tâm: loại bỏ hoàn toàn tầng hồi quy, xây dựng toàn bộ mạng dựa trên &lt;strong&gt;attention&lt;/strong&gt;, kết hợp với các mạng MLP theo từng vị trí, kết nối phần dư (&lt;em&gt;residual&lt;/em&gt;) và chuẩn hóa lớp.&lt;/p&gt;

&lt;p&gt;Thiết kế này đồng thời giải quyết ba hạn chế cố hữu của các mô hình hồi quy (RNN/LSTM):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Khả năng song song hóa&lt;/strong&gt; (&lt;em&gt;parallelism&lt;/em&gt;) — toàn bộ các vị trí trong chuỗi được xử lý đồng thời bằng phép nhân ma trận khi huấn luyện, không còn phụ thuộc vòng lặp từ trái sang phải.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đường truyền thông tin tầm xa ngắn&lt;/strong&gt; — mọi cặp token có thể trao đổi thông tin trực tiếp chỉ trong một tầng (độ dài đường truyền \(O(1)\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khả năng mở rộng quy mô&lt;/strong&gt; (&lt;em&gt;scalability&lt;/em&gt;) — cùng một khối kiến trúc có thể xếp chồng thành hàng chục đến hàng trăm tầng và thích ứng tốt cho nhiều tác vụ khác nhau.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Từ nền tảng này hình thành các dòng mô hình chủ đạo của học sâu hiện đại: chỉ-encoder (BERT), chỉ-decoder (GPT), encoder–decoder (T5), Vision Transformer (ViT) và nhiều hệ thống đa phương thức.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/sa_transformer_multihead_overview.jpg&quot; alt=&quot;Toàn cảnh Transformer + Multi-Head&quot; /&gt;
&lt;em&gt;Hình: Kiến trúc encoder–decoder với multi-head attention (nhiều head scaled dot-product chạy song song). (Minh họa từ video Transformer / Self-Attention nhập môn)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Liên hệ Chương 18 (Biểu diễn từ):&lt;/strong&gt; Word2Vec hay GloVe gán &lt;strong&gt;một&lt;/strong&gt; vectơ cố định cho mỗi từ bất kể ngữ cảnh. Ngược lại, Transformer và BERT tạo &lt;strong&gt;biểu diễn phụ thuộc ngữ cảnh&lt;/strong&gt;: cùng từ “Apple” sẽ có vectơ khác nhau tùy theo câu đang nói về trái cây hay hãng công nghệ, nhờ cơ chế attention tổng hợp thông tin từ các từ xung quanh.&lt;/p&gt;

&lt;h3 id=&quot;ba-vị-trí-xuất-hiện-attention-trong-encoderdecoder&quot;&gt;Ba vị trí xuất hiện attention trong encoder–decoder&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/tf_masked_mha_highlight.jpg&quot; alt=&quot;Masked MHA trên decoder&quot; /&gt;
&lt;em&gt;Hình: &lt;strong&gt;Masked multi-head attention&lt;/strong&gt; giúp decoder không nhìn thấy các token tương lai. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/tf_cross_vs_masked_labels.jpg&quot; alt=&quot;Cross vs Masked&quot; /&gt;
&lt;em&gt;Hình: So sánh &lt;strong&gt;Cross-attention&lt;/strong&gt; (K, V từ encoder; Q từ decoder) và &lt;strong&gt;Masked self-attention&lt;/strong&gt;. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/tf_cross_attn_kv_from_encoder.jpg&quot; alt=&quot;Cross-attention: K,V từ encoder&quot; /&gt;
&lt;em&gt;Hình: Luồng K và V truyền từ encoder sang decoder qua cross-attention. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mã hóa vị trí (Positional Encoding — PE):&lt;/strong&gt; Vì self-attention thuần chỉ dựa trên nội dung nên không phân biệt được thứ tự token. PE dạng sin–cos gán cho mỗi vị trí \(pos\) một vectơ đa tần số rồi &lt;strong&gt;cộng trực tiếp&lt;/strong&gt; vào token embedding (chi tiết từng bước về \(pos\), \(i\), sin/cos và \(d=512\) được trình bày trong bài Lý thuyết Transformer).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_input_emb_vs_positional.jpg&quot; alt=&quot;Input embedding + positional encoding&quot; /&gt;
&lt;em&gt;Hình: Token embedding và mã hóa vị trí có cùng chiều \(d_{\mathrm{model}}\), được cộng theo từng phần tử trước khi đưa vào các tầng Transformer. (Minh họa từ video Position Encoding)&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau chương này, bạn sẽ có thể:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Vẽ sơ đồ các khối &lt;strong&gt;encoder&lt;/strong&gt;, &lt;strong&gt;decoder&lt;/strong&gt; và luồng dữ liệu kết nối giữa chúng.&lt;/li&gt;
  &lt;li&gt;Phân biệt rõ vai trò của &lt;strong&gt;self-attention&lt;/strong&gt;, &lt;strong&gt;masked self-attention&lt;/strong&gt; và &lt;strong&gt;cross-attention&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Suy ra và cài đặt &lt;strong&gt;mã hóa vị trí&lt;/strong&gt; (&lt;em&gt;positional encoding&lt;/em&gt;), đồng thời giải thích vì sao self-attention thuần không tự nhận biết thứ tự.&lt;/li&gt;
  &lt;li&gt;Viết đầy đủ phương trình của một &lt;strong&gt;tầng Transformer&lt;/strong&gt; (attention, FFN, kết nối phần dư và chuẩn hóa lớp).&lt;/li&gt;
  &lt;li&gt;Cài đặt một mô hình Transformer thu gọn bằng PyTorch với kích thước tensor và mặt nạ chính xác.&lt;/li&gt;
  &lt;li&gt;Nắm vững các bài báo nền tảng (Vaswani, BERT, GPT-2, ViT) cùng các vấn đề vận hành phổ biến (warmup, KV-cache, chi phí bậc hai).&lt;/li&gt;
  &lt;li&gt;Sử dụng &lt;strong&gt;Transformer Explainer&lt;/strong&gt; để quan sát trực tiếp embedding, trọng số attention, nhiệt độ (&lt;em&gt;temperature&lt;/em&gt;) và cơ chế lấy mẫu trên mô hình GPT-2 ngay trong trình duyệt.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;lộ-trình-học&quot;&gt;Lộ trình học&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Bài học&lt;/th&gt;
      &lt;th&gt;Trọng tâm&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-01 Kiến trúc (tổng quan)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Lộ trình kết nối giữa lý thuyết và cài đặt&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-01-01 Lý thuyết&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Self-attention trong mô hình hoàn chỉnh, PE và cấu trúc tầng encoder/decoder&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02 Cài đặt (tổng quan)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Sơ đồ module và danh mục kiểm tra&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02-01 Mã cốt lõi&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Cài đặt các khối nền tảng từ đầu bằng PyTorch&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02-02 Demo, bài báo, bẫy thường gặp&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Huấn luyện ví dụ nhỏ, tài liệu nền tảng và kỹ thuật gỡ lỗi&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-02 Transformer Explainer&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Trực quan hóa tương tác mô hình GPT-2 trên trình duyệt&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;kiến-thức-tiên-quyết&quot;&gt;Kiến thức tiên quyết&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Cơ chế attention ở Chương 07 (scaled dot-product, multi-head, causal/padding mask).&lt;/li&gt;
  &lt;li&gt;Hiểu khái niệm kết nối phần dư (residual) và LayerNorm.&lt;/li&gt;
  &lt;li&gt;Thành thạo softmax, lớp embedding và cấu trúc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Module&lt;/code&gt; trong PyTorch.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;mô-hình-tư-duy-cốt-lõi&quot;&gt;Mô hình tư duy cốt lõi&lt;/h2&gt;

&lt;p&gt;Mỗi tầng Transformer lặp lại hai thao tác chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Trao đổi thông tin&lt;/strong&gt; (&lt;em&gt;communicate&lt;/em&gt;) — multi-head attention trộn ngữ cảnh giữa các vị trí trong chuỗi.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biến đổi cục bộ&lt;/strong&gt; (&lt;em&gt;compute&lt;/em&gt;) — mạng feed-forward theo từng vị trí xử lý độc lập từng token.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Thông tin vị trí được bổ sung ở đầu vào (hoặc tích hợp trực tiếp vào điểm số attention ở các biến thể vị trí tương đối) để sự tương tác phụ thuộc vào cả nội dung lẫn cấu trúc thứ tự của chuỗi. Khi bạn có thể tự vẽ luồng tính toán của một tầng encoder và một bước decoder kèm mặt nạ trên giấy, bạn đã sẵn sàng cho phần lý thuyết và cài đặt tiếp theo.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến); các đường dẫn dưới đây được lưu lại để tra cứu và ghi nhận nguồn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/930207546288223&quot;&gt;Transformer là gì? Self-Attention siêu dễ hiểu (Phần 1)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1007473105556936&quot;&gt;Attention trong Transformer (Self, Masked, Cross, Multi-Head)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1306224801415127&quot;&gt;Position Encoding trong Transformer (từng bước)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1501843101324752&quot;&gt;Word Embedding và Transformer hiểu ngôn ngữ&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trực quan hóa tương tác:&lt;/strong&gt; Sau phần lý thuyết và ví dụ cài đặt, bạn có thể dùng bài &lt;strong&gt;08-02 Transformer Explainer&lt;/strong&gt; để quan sát trực tiếp mô hình GPT-2 (small) trên trình duyệt: tách token, các đầu attention, nhiệt độ và lấy mẫu top-k / top-p.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Bài &lt;strong&gt;08-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; tổng hợp các cải tiến trong LLM hiện đại như RoPE, KV-cache, các mô hình mã nguồn mở và công cụ phục vụ (vLLM, llama.cpp).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lộ trình LLM chuyên sâu:&lt;/strong&gt; Sau khi nắm vững tầng decoder và quy trình giải mã ở Chương 08, bạn có thể tiếp tục sang &lt;strong&gt;Chương 26&lt;/strong&gt; (Mô hình ngôn ngữ lớn) về tiền huấn luyện, prompting, căn chỉnh, phục vụ, chưng cất và phân tích khối kiến trúc / chi phí tính toán ở bài &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown (tiếng Anh). Trình bày trực quan cấu trúc khối Transformer (attention kết hợp MLP) xuyên suốt chương này.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zxQyTK8quyY&quot;&gt;Transformer Neural Networks, ChatGPT’s foundation, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Lượt giải thích rõ ràng, có gắn nhãn đầy đủ từng thành phần trong khối Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dqoEU9Ac3ek&quot;&gt;MIT 6.S191 (2024): Recurrent Neural Networks, Transformers, and Attention&lt;/a&gt; — Alexander Amini (tiếng Anh). Bài giảng MIT trình bày bước chuyển từ RNN sang Transformer.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Công thức Attention chuẩn có một điểm yếu chí mạng ở cấp độ phần cứng: để tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softmax(QK^T / sqrt(d))&lt;/code&gt;, GPU phải ghi cả ma trận điểm số \(L \times L\) ra bộ nhớ chính HBM chậm chạp rồi lại đọc ngược vào — khiến Attention bị nghẽn băng thông bộ nhớ (&lt;em&gt;memory-bound&lt;/em&gt;) ngay cả khi nhân tính toán Tensor Core đang rảnh rỗi! Giai đoạn 2022–2026 chứng kiến cuộc cách mạng kỹ thuật hệ thống với &lt;strong&gt;FlashAttention&lt;/strong&gt;, &lt;strong&gt;GQA/MQA&lt;/strong&gt; và &lt;strong&gt;PagedAttention&lt;/strong&gt;, giúp kéo dài ngữ cảnh LLM từ 4K lên hàng triệu token.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-đột-phá-hệ-thống-về-attention-20222026&quot;&gt;Kiến thức cần nhớ: Bốn đột phá hệ thống về Attention (2022–2026)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;FlashAttention (Tri Dao et al., 2022–2024) — Chính xác 100%, bộ nhớ \(O(L)\)&lt;/strong&gt;:
Không hề xấp xỉ toán học! FlashAttention chia nhỏ \(Q, K, V\) thành các khối (tiles) vừa khít bộ nhớ siêu nhanh SRAM trên chip GPU, dùng thuật toán &lt;em&gt;online softmax&lt;/em&gt; để tính trọn vẹn Attention mà &lt;strong&gt;không bao giờ&lt;/strong&gt; phải ghi ma trận \(L \times L\) xuống HBM.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multi-Query (MQA) và Grouped-Query Attention (GQA)&lt;/strong&gt;:
Trong suy luận LLM, nút thắt lớn nhất là kích thước &lt;strong&gt;KV-Cache&lt;/strong&gt;. MQA cho tất cả các Query head dùng chung 1 cặp K/V; GQA (dùng trong Llama 3, Mistral, Qwen) chia \(H_q\) đầu query thành \(G\) nhóm dùng chung K/V — giảm bộ nhớ KV-cache tới 4–8 lần mà chất lượng gần như không đổi.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;PagedAttention (vLLM) — Quản lý bộ nhớ ảo cho KV-Cache&lt;/strong&gt;:
Mượn ý tưởng phân trang (virtual memory paging) của hệ điều hành, PagedAttention chia KV-cache thành các khối nhỏ không cần liên tục trong VRAM, loại bỏ tình trạng phân mảnh bộ nhớ và tăng thông lượng phục vụ LLM gấp nhiều lần.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sliding-Window và Sparse/Linear Attention&lt;/strong&gt;:
Giới hạn mỗi token chỉ chú ý vào cửa sổ cục bộ \(W\) token gần nhất (Mistral) hoặc kết hợp các token neo (&lt;em&gt;attention sinks&lt;/em&gt;), giảm độ phức tạp từ \(O(L^2)\) xuống \(O(L \cdot W)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-mức-tiết-kiệm-vram-của-gqa-và-flashattention-ở-ngữ-cảnh-l--8192&quot;&gt;Giải thích: Tính tay mức tiết kiệm VRAM của GQA và FlashAttention ở ngữ cảnh \(L = 8{,}192\)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — FlashAttention vs. Standard Attention (1 layer, 1 batch, \(H=32\) head, FP16 = 2 byte)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Ma trận điểm số \(S = Q K^T\) nếu lưu ra HBM chiếm:
\(32 \times 8{,}192 \times 8{,}192 \times 2\text{ bytes} \approx \mathbf{4{,}29\text{ GB}}\) (chỉ riêng 1 tầng cho 1 câu!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FlashAttention&lt;/strong&gt;: không lưu ma trận \(L \times L\), chỉ lưu đầu ra và thống kê softmax \(O(L) \Rightarrow\) giảm bộ nhớ trung gian từ &lt;strong&gt;4,29 GB xuống vài MB&lt;/strong&gt;!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Tiết kiệm KV-Cache nhờ GQA (kiểu Llama-3 8B: \(H_q = 32, \; H_{kv} = 8, \; d_k = 128\), 32 tầng, \(L = 8{,}192\), FP16)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;MHA chuẩn&lt;/strong&gt; (\(H_{kv} = 32\)): \(32\text{ tầng} \times 2\text{ (K,V)} \times 32 \times 128 \times 8{,}192 \times 2\text{ B} = \mathbf{4{,}29\text{ GB}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GQA&lt;/strong&gt; (\(H_{kv} = 8\), tỷ lệ 4:1): giảm đúng &lt;strong&gt;4 lần&lt;/strong&gt;, chỉ còn &lt;strong&gt;1,07 GB&lt;/strong&gt; — giúp phục vụ đồng thời gấp 4 lần số người dùng trên cùng một GPU!&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;tùy-chọn-kernel-attention-hệ-thống-phục-vụ-và-biến-thể-multi-query&quot;&gt;Tùy chọn: Kernel attention, hệ thống phục vụ và biến thể multi-query&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần toán học scaled dot-product hay multi-head attention. Nội dung tập trung vào các kỹ thuật hệ thống và biến thể kiến trúc giúp attention vận hành hiệu quả ở quy mô LLM.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Công thức cốt lõi vẫn giữ nguyên:&lt;/p&gt;

\[\mathrm{Attn}(Q,K,V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d}}\right)V.\]

&lt;p&gt;Trong giai đoạn 2022–2026, trọng tâm tối ưu hóa chuyển sang &lt;strong&gt;băng thông bộ nhớ (IO)&lt;/strong&gt;, &lt;strong&gt;cách quản lý KV-cache&lt;/strong&gt; và &lt;strong&gt;giảm số lượng head key/value&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;1-flashattention-tính-attention-chính-xác-với-lưu-lượng-bộ-nhớ-thấp&quot;&gt;1. FlashAttention: Tính attention chính xác với lưu lượng bộ nhớ thấp&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;Dao et al., 2022&lt;/a&gt; chia khối (&lt;em&gt;tiling&lt;/em&gt;) các ma trận \(Q, K, V\) trong bộ nhớ đệm nhanh (SRAM) để không phải ghi toàn bộ ma trận điểm số \(T\times T\) ra bộ nhớ chính GPU (HBM). &lt;a href=&quot;https://arxiv.org/abs/2307.08691&quot;&gt;FlashAttention-2&lt;/a&gt; (2023) tối ưu thêm mức độ song song hóa, còn &lt;a href=&quot;https://arxiv.org/abs/2407.08608&quot;&gt;FlashAttention-3&lt;/a&gt; (2024) khai thác phần cứng Hopper với thực thi bất đồng bộ và định dạng FP8. Hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scaled_dot_product_attention&lt;/code&gt; của PyTorch tự động điều hướng sang các kernel này khi kích thước tensor tương thích.&lt;/p&gt;

&lt;p&gt;Kết quả toán học vẫn là phép softmax chính xác như phần lý thuyết; cải tiến nằm ở &lt;strong&gt;cách tổ chức thuật toán theo phân cấp bộ nhớ&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-và-biến-thể-tiêu-biểu&quot;&gt;2. Ứng dụng và biến thể tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;pagedattention-và-phục-vụ-llm&quot;&gt;PagedAttention và phục vụ LLM&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2309.06180&quot;&gt;Kwon et al., 2023&lt;/a&gt; (vLLM) quản lý KV-cache theo từng khối phân trang tương tự bộ nhớ ảo trong hệ điều hành, giúp nhiều chuỗi giải mã chia sẻ bộ nhớ GPU mà không bị phân mảnh hay lãng phí vùng cấp phát trước. Đây là kỹ thuật tối ưu tầng &lt;em&gt;phục vụ (serving)&lt;/em&gt; chứ không thay đổi hàm chấm điểm.&lt;/p&gt;

&lt;h3 id=&quot;gqa-và-mqa&quot;&gt;GQA và MQA&lt;/h3&gt;

&lt;p&gt;Multi-query attention (&lt;a href=&quot;https://arxiv.org/abs/1911.02150&quot;&gt;Shazeer, 2019&lt;/a&gt;) và grouped-query attention (&lt;a href=&quot;https://arxiv.org/abs/2305.13245&quot;&gt;Ainslie et al., 2023&lt;/a&gt;, GQA) cho phép nhiều query head dùng chung một hoặc một nhóm nhỏ KV head. Các mô hình như Llama 2/3 và Mistral áp dụng GQA để giảm mạnh kích thước KV-cache:&lt;/p&gt;

\[\text{KV bytes} \propto T \cdot n_{\text{kv}} \cdot d, \quad n_{\text{kv}} \ll n_{\text{heads}}.\]

&lt;h3 id=&quot;sliding-window-và-linear-attention&quot;&gt;Sliding-window và linear attention&lt;/h3&gt;

&lt;p&gt;Attention &lt;strong&gt;cửa sổ trượt&lt;/strong&gt; (&lt;em&gt;sliding-window&lt;/em&gt;, như trong Mistral) và các biến thể linear attention thay thế ma trận tương tác đầy đủ \(T\times T\) bằng độ phức tạp \(O(T)\), hữu ích khi chi phí bậc hai của attention chuẩn trở thành rào cản triển khai thực tế.&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-phần-mềm-phổ-biến&quot;&gt;3. Thư viện và phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;F.scaled_dot_product_attention&lt;/code&gt; (SDPA) / &lt;a href=&quot;https://github.com/Dao-AILab/flash-attention&quot;&gt;FlashAttention&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt; — hệ thống phục vụ LLM sử dụng PagedAttention.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/xformers&quot;&gt;xFormers&lt;/a&gt; — thư viện toán tử attention tiết kiệm bộ nhớ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;FlashAttention (Dao et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2307.08691&quot;&gt;FlashAttention-2 (Dao, 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2407.08608&quot;&gt;FlashAttention-3 (Shah et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2309.06180&quot;&gt;PagedAttention (Kwon et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.13245&quot;&gt;GQA (Ainslie et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-vai-trò-bổ-trợ-cho-nội-dung-cốt-lõi&quot;&gt;5. Vai trò bổ trợ cho nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên hoàn thành phần cài đặt attention bằng NumPy và bài về các bẫy multi-head trước. Bài đọc thêm này bổ sung góc nhìn về &lt;strong&gt;kernel tối ưu, KV-cache và GQA&lt;/strong&gt; thường gặp trong mã nguồn LLM hiện đại. Bạn có thể xem thêm Chương &lt;strong&gt;26-07&lt;/strong&gt; về cơ chế chia khối kết hợp softmax trực tuyến của FlashAttention cùng GQA trong khối decoder, và Chương &lt;strong&gt;26-04&lt;/strong&gt; về quản lý KV-cache khi phục vụ mô hình.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=gBMO1JZav44&quot;&gt;How FlashAttention Accelerates Generative AI Revolution&lt;/a&gt; — Jia-Bin Huang (tiếng Anh). Giải thích trực quan cách FlashAttention giữ nguyên kết quả attention trong khi giảm mạnh lưu lượng truy cập bộ nhớ.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[FlashAttention - Tri Dao&lt;/td&gt;
          &lt;td&gt;Stanford MLSys #67](https://www.youtube.com/watch?v=gMOAud7hZg4) — Stanford MLSys Seminars (tiếng Anh). Buổi trình bày gốc của tác giả Tri Dao về thuật toán FlashAttention (nên xem sau video ngắn).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown (tiếng Anh). Ôn lại công thức attention chính xác mà FlashAttention tính toán không cần xấp xỉ.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-02-02 Cài đặt Attention</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_02_02_Attention_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_02_02_Attention_Implementation</id>
   <content type="html">&lt;p&gt;Trong thực tế lập trình Deep Learning, 90% lỗi liên quan đến Attention không nằm ở chỗ viết sai công thức toán, mà nằm ở ba chỗ âm thầm: &lt;strong&gt;nhầm chiều &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transpose&lt;/code&gt; khi tách head&lt;/strong&gt;, &lt;strong&gt;áp sai chiều broadcast của mask&lt;/strong&gt;, hoặc &lt;strong&gt;quên chia cho \(\sqrt{d_k}\)&lt;/strong&gt;. Danh mục kiểm tra và lộ trình cài đặt ở mục này giúp bạn viết code Attention sạch, dễ kiểm thử và không dính bẫy ngầm.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-khi-triển-khai-mã-nguồn-attention&quot;&gt;Kiến thức cần nhớ: Ba trụ cột khi triển khai mã nguồn Attention&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Từ vòng lặp tường minh (Bahdanau) đến vector hóa theo batch (Scaled Dot-Product)&lt;/strong&gt;:
Viết bản Bahdanau tường minh giúp nhìn thấy rõ bảng gióng hàng giữa từng từ nguồn–đích, sau đó chuyển sang phép nhân tensor 4D &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, H, L, d_k)&lt;/code&gt; của Multi-Head Attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chiến lược biến đổi hình dạng tensor (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transpose&lt;/code&gt;)&lt;/strong&gt;:
Tách head đúng chuẩn là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x.view(B, L, H, d_k).transpose(1, 2)&lt;/code&gt; để đưa trục &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;H&lt;/code&gt; lên trước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L&lt;/code&gt; (thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, H, L, d_k)&lt;/code&gt;), &lt;strong&gt;tuyệt đối không&lt;/strong&gt; dùng trực tiếp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x.view(B, H, L, d_k)&lt;/code&gt; vì sẽ xáo trộn dữ liệu giữa các token!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bộ kiểm thử nhanh (Smoke Tests) bắt buộc&lt;/strong&gt;:
Luôn kiểm tra 3 bất biến: tổng trọng số softmax trên trục cuối bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.0&lt;/code&gt;, các vị trí bị che (causal/padding) có trọng số bằng đúng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt;, và thay đổi token tương lai không làm thay đổi đầu ra của token quá khứ.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-minh-họa-bằng-số-vì-sao-viewb-h-l-d_k-sai-hoàn-toàn-so-với-viewb-l-h-d_ktranspose1-2&quot;&gt;Giải thích: Minh họa bằng số vì sao &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view(B, H, L, d_k)&lt;/code&gt; sai hoàn toàn so với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view(B, L, H, d_k).transpose(1, 2)&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;Giả sử \(B=1, \; L=2\) token, \(d_{\text{model}}=4\), tách thành \(H=2\) head (mỗi head \(d_k=2\)). Tensor gốc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt; gồm 2 token:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Token 0: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[a1, a2, a3, a4]&lt;/code&gt; (trong đó &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[a1, a2]&lt;/code&gt; thuộc Head 0; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[a3, a4]&lt;/code&gt; thuộc Head 1)&lt;/li&gt;
  &lt;li&gt;Token 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[b1, b2, b3, b4]&lt;/code&gt; (trong đó &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[b1, b2]&lt;/code&gt; thuộc Head 0; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[b3, b4]&lt;/code&gt; thuộc Head 1)&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Cách biến đổi shape&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Dữ liệu mà &lt;strong&gt;Head 0&lt;/strong&gt; nhận được&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Dữ liệu mà &lt;strong&gt;Head 1&lt;/strong&gt; nhận được&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Kết luận&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;ĐÚNG&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view(1, 2, 2, 2).transpose(1, 2)&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[[a1, a2], [b1, b2]]&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[[a3, a4], [b3, b4]]&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Head 0 thấy đủ cả 2 token trên 2 chiều đầu — &lt;strong&gt;Chính xác!&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;SAI&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view(1, 2, 2, 2)&lt;/code&gt; trực tiếp&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[[a1, a2], [a3, a4]]&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[[b1, b2], [b3, b4]]&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Head 0 chỉ thấy Token 0 bị cắt đôi, Head 1 chỉ thấy Token 1 — &lt;strong&gt;Hỏng hoàn toàn!&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Lỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view&lt;/code&gt; trực tiếp không hề báo exception khi chạy PyTorch, nên tự kiểm tra bằng tay trên mảng 8 phần tử như trên sẽ cứu bạn khỏi hàng giờ debug vô ích!&lt;/p&gt;

&lt;h1 id=&quot;07-02-02-cài-đặt-attention&quot;&gt;07-02-02 Cài đặt Attention&lt;/h1&gt;

&lt;p&gt;Phần toán học xác định rõ attention tính những đại lượng nào, còn phần cài đặt đảm bảo phép toán đó được hiện thực hóa chính xác — từ kích thước tensor, mặt nạ, độ ổn định số học cho tới cách dùng API.&lt;/p&gt;

&lt;h2 id=&quot;các-bài-trong-mục-này&quot;&gt;Các bài trong mục này&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Cài đặt cốt lõi&lt;/strong&gt;&lt;br /&gt;
Cài đặt attention Bahdanau và scaled self-attention từ đầu, chạy ví dụ minh họa kiểu dịch máy và đối chiếu phiên bản NumPy với PyTorch.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Multi-Head, Papers và Cạm bẫy&lt;/strong&gt;&lt;br /&gt;
Xây dựng module multi-head attention, cài đặt causal mask, phác thảo mô hình seq2seq có attention, điểm qua các bài báo nền tảng và danh mục kiểm tra gỡ lỗi thực tế.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;danh-mục-kiểm-tra-khi-cài-đặt&quot;&gt;Danh mục kiểm tra khi cài đặt&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Hạng mục kiểm tra&lt;/th&gt;
      &lt;th&gt;Lý do quan trọng&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Softmax trên trục &lt;strong&gt;key&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Trọng số phải tạo thành phân phối xác suất trên các vị trí bộ nhớ&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Chia tỉ lệ cho \(\sqrt{d_k}\)&lt;/td&gt;
      &lt;td&gt;Tránh bão hòa softmax khi số chiều lớn&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Áp mask &lt;strong&gt;trước&lt;/strong&gt; softmax bằng số âm lớn / \(-\infty\)&lt;/td&gt;
      &lt;td&gt;Đảm bảo trọng số bằng 0 và gradient chính xác&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Causal mask cho decoder tự hồi quy&lt;/td&gt;
      &lt;td&gt;Ngăn rò rỉ thông tin từ các token tương lai&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Padding mask khi huấn luyện theo batch&lt;/td&gt;
      &lt;td&gt;Tránh phân bổ trọng số vào các token &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PAD&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Reshape multi-head: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B,L,H,d)&lt;/code&gt; ↔ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B,H,L,d)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Hoán vị sai chiều làm trộn lẫn đặc trưng dù chương trình vẫn chạy không báo lỗi&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Hãy bắt đầu từ bài &lt;strong&gt;Cài đặt cốt lõi&lt;/strong&gt;, sau đó tiếp tục sang phần multi-head và các cạm bẫy thường gặp.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown (tiếng Anh). Ôn nhanh công thức toán học trước khi chuyển sang phần cài đặt.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mmzRYGCfTzc&quot;&gt;A Dive Into Multihead Attention, Self-Attention and Cross-Attention&lt;/a&gt; — Machine Learning Studio (tiếng Anh). Sơ đồ phân biệt các module self-attention, cross-attention và multi-head.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Cài đặt trực tiếp cơ chế attention bằng Python, sát với mục tiêu thực hành của mục này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-02-02-02 Multi-Head Attention, Papers và Cạm bẫy</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_02_02_02_MultiHead_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_02_02_02_MultiHead_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Trong câu &lt;em&gt;“Con mèo không băng qua đường vì &lt;strong&gt;nó&lt;/strong&gt; quá mệt”&lt;/em&gt;, để hiểu đại từ &lt;strong&gt;“nó”&lt;/strong&gt; chỉ con mèo (không phải con đường), mô hình vừa cần theo dõi quan hệ ngữ pháp chủ–vị, vừa cần theo dõi quan hệ ngữ nghĩa giữa &lt;em&gt;“mệt”&lt;/em&gt; và sinh vật sống. Nếu chỉ dùng &lt;strong&gt;một&lt;/strong&gt; đầu chú ý duy nhất, việc lấy trung bình tất cả các quan hệ khác nhau vào cùng một phân phối softmax sẽ làm mờ nhạt thông tin. &lt;strong&gt;Multi-Head Attention&lt;/strong&gt; giải quyết bài toán này bằng cách cho phép nhiều đầu chú ý cùng hoạt động song song trên các không gian con khác nhau.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-multi-head-attention-và-cạm-bẫy-thực-tế&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Multi-Head Attention và Cạm bẫy Thực tế&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phép chiếu đa không gian con (\(W_i^Q, W_i^K, W_i^V\)) và ghép nối \(W^O\)&lt;/strong&gt;:
Mỗi đầu \(i \in \{1 \dots H\}\) chiếu vector \(d_{\text{model}}\) xuống chiều nhỏ hơn \(d_k = d_{\text{model}} / H\), tính attention độc lập, rồi ghép (concat) cả \(H\) đầu về lại \(d_{\text{model}}\) và trộn qua ma trận chiếu đầu ra \(W^O\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bảo toàn ngân sách tính toán nhờ chia chiều \(d_k = d_{\text{model}} / H\)&lt;/strong&gt;:
Dùng 8 đầu với \(d_k = 64\) tốn tổng số tham số và FLOPs xấp xỉ đúng bằng dùng 1 đầu đơn với \(d_k = 512\), nhưng sức biểu đạt đa quan hệ tăng vượt trội.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đối chiếu bản tự viết với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.MultiheadAttention&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;F.scaled_dot_product_attention&lt;/code&gt;&lt;/strong&gt;:
Từ PyTorch 2.0+, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;F.scaled_dot_product_attention&lt;/code&gt; tự động chọn kernel FlashAttention trên GPU, chạy nhanh hơn nhiều lần và tốn bộ nhớ \(O(L)\) thay vì \(O(L^2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cạm bẫy kinh điển của Multi-Head Attention&lt;/strong&gt;:
Quên đặt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Dropout&lt;/code&gt; lên trọng số chú ý (attention dropout), nhầm thứ tự quy ước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;attn_mask&lt;/code&gt; (boolean &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;True&lt;/code&gt; nghĩa là &lt;strong&gt;bị che&lt;/strong&gt; trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.MultiheadAttention&lt;/code&gt; nhưng lại khác ở một số hàm tự viết!), và hiện tượng một số head trở nên dư thừa (head redundancy).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-tổng-số-tham-số-của-một-khối-multi-head-attention-chuẩn-transformer-base&quot;&gt;Giải thích: Tính tay tổng số tham số của một khối Multi-Head Attention chuẩn Transformer Base&lt;/h3&gt;

&lt;p&gt;Xét cấu hình Transformer Base kinh điển: \(d_{\text{model}} = 512\), số đầu \(H = 8 \implies d_k = d_v = 512 / 8 = 64\) (bỏ qua bias để gọn):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Ma trận chiếu&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Kích thước mỗi head&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Số head \(H\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Ma trận gộp tương đương&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Số tham số&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(W^Q\) (Query)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(512 \times 64\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;8&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(512 \times 512\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;262,144&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(W^K\) (Key)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(512 \times 64\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;8&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(512 \times 512\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;262,144&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(W^V\) (Value)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(512 \times 64\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;8&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(512 \times 512\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;262,144&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(W^O\) (Output)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;—&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;—&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(512 \times 512\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;262,144&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Tổng cộng MHA&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(4 \, d_{\text{model}}^2\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;&lt;strong&gt;1,048,576&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Một con số cực dễ nhớ cho cả khi thiết kế kiến trúc lẫn phỏng vấn: mỗi khối Multi-Head Attention luôn có đúng &lt;strong&gt;\(4 \, d_{\text{model}}^2\)&lt;/strong&gt; tham số trọng số, hoàn toàn &lt;strong&gt;độc lập&lt;/strong&gt; với số lượng head \(H\)!&lt;/p&gt;

&lt;h1 id=&quot;multi-head-attention-papers-và-cạm-bẫy&quot;&gt;Multi-Head Attention, Papers và Cạm bẫy&lt;/h1&gt;

&lt;p&gt;Cài đặt được single-head attention mới chỉ là bước đầu; trong các hệ thống Transformer thực tế, hiệu năng phụ thuộc chặt chẽ vào &lt;strong&gt;nhiều head chú ý song song&lt;/strong&gt;, thao tác tách/ghép chiều tensor chính xác, mặt nạ nhân quả và khả năng phát hiện các lỗi ẩn khi mở rộng quy mô. Bài này hoàn thiện phần cài đặt cho Chương 7.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Multi-head attention không đơn thuần là lặp lại attention cho chậm hơn mà là cơ chế mở rộng năng lực biểu diễn. Mỗi head sử dụng bộ ma trận chiếu riêng \((W_h^Q, W_h^K, W_h^V)\), cho phép nó học một tiêu chí tương đồng và một mẫu định tuyến thông tin khác nhau. Các đầu ra sau đó được nối lại theo chiều đặc trưng và trộn qua ma trận \(W^O\) để trở về chiều của mô hình.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/tf_full_arch_multihead_zoom.jpg&quot; alt=&quot;Kiến trúc Transformer + zoom Multi-Head / Scaled Dot-Product&quot; /&gt;
&lt;em&gt;Hình: Multi-head gồm nhiều nhánh Linear(Q, K, V) → scaled attention → nối (concat) → lớp tuyến tính đầu ra. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_multihead_dk_split.jpg&quot; alt=&quot;$$d_k = d_{\mathrm{model}}/H$$&quot; /&gt;
&lt;em&gt;Hình: Ví dụ \(512/8=64\) chiều cho mỗi head. (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_multihead_output_stack.jpg&quot; alt=&quot;Đầu ra multi-head&quot; /&gt;
&lt;em&gt;Hình: Ghép đầu ra của các head trước khi nhân ma trận \(W^O\). (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Quy trình thực hiện multi-head attention gồm 5 bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Chiếu \(\mathbf{X}\) sang Q, K, V với đầy đủ chiều \(d_{\mathrm{model}}\).&lt;/li&gt;
  &lt;li&gt;Tách và hoán vị chiều thành \((B, H, L, d_k)\) với \(d_k=d_{\mathrm{model}}/H\).&lt;/li&gt;
  &lt;li&gt;Chạy scaled dot-product attention song song trên tất cả các head.&lt;/li&gt;
  &lt;li&gt;Ghép lại các head thành \((B, L, d_{\mathrm{model}})\).&lt;/li&gt;
  &lt;li&gt;Áp dụng phép chiếu tuyến tính cuối \(W^O\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nếu thao tác reshape hoặc transpose bị sai thứ tự, tensor đầu ra vẫn có thể giữ nguyên kích thước mong đợi nhưng dữ liệu bên trong bị trộn lẫn. Do đó, kiểm thử đơn vị cho bước tách/ghép head là rất cần thiết.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

\[\mathrm{head}_h = \mathrm{Attention}(X W_h^Q,\ X W_h^K,\ X W_h^V)\]

\[\mathrm{MultiHead}(X)=\mathrm{Concat}_h(\mathrm{head}_h)\,W^O\]

&lt;p&gt;Trong cài đặt thực tế, thay vì thực hiện \(H\) phép nhân nhỏ tách rời, ta nhân một lần với ma trận lớn kích thước \(d_{\mathrm{model}}\) rồi tách chiều cuối thành \(H \times d_k\):&lt;/p&gt;

\[Q = X W^Q \in \mathbb{R}^{B\times L\times (H d_k)}
\ \xrightarrow{\text{reshape/transpose}}\ 
\mathbb{R}^{B\times H\times L\times d_k}.\]

&lt;p&gt;Trong giải mã tự hồi quy (causal), mặt nạ:&lt;/p&gt;

\[M_{ij}=\begin{cases}0 &amp;amp; j\le i\\ -\infty &amp;amp; j&amp;gt;i\end{cases}\]

&lt;p&gt;được cộng vào ma trận điểm số và broadcast đồng loạt trên mọi batch và mọi head.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;p&gt;Trên một câu ngắn như &lt;em&gt;“The cat sat”&lt;/em&gt;, sau quá trình huấn luyện các head thường tự chuyên biệt hóa theo những vai trò khác nhau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Head A theo dõi quan hệ lân cận cục bộ (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cat&lt;/code&gt; ↔ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;The&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sat&lt;/code&gt; ↔ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cat&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;Head B nắm bắt liên kết cú pháp (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sat&lt;/code&gt; chú ý vào chủ ngữ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cat&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;Head C tập trung gần đường chéo chính (chủ yếu theo vị trí).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Các vai trò này không được lập trình cứng mà hình thành tự nhiên từ tham số khởi tạo riêng biệt và áp lực tối ưu hóa hàm mất mát. Trực quan hóa bản đồ trọng số của từng head giúp quan sát rõ sự phân hóa này.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;
&lt;h3 id=&quot;41-multi-head-self-attention-pytorch-phiên-bản-giảng-dạy&quot;&gt;4.1 Multi-head self-attention (PyTorch, phiên bản giảng dạy)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadSelfAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wqkv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;drop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# (B, L, d) -&amp;gt; (B, H, L, dk)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# (B, H, L, dk) -&amp;gt; (B, L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;contiguous&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (B, L, d_model)
        attn_mask: mask cộng broadcast được tới (B, 1, L, L) hoặc (B, H, L, L)
                   0 = giữ, -inf = cấm
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;qkv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wqkv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, L, 3d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;qkv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;chunk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;drop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, H, L, L)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;build_causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# (1, 1, L, L) để broadcast trên batch và heads
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;full&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-inf&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;diagonal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Smoke test
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadSelfAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;build_causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diagonal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;atol&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;multi-head causal OK&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;42-dùng-module-có-sẵn&quot;&gt;4.2 Dùng module có sẵn&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;official&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MultiheadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embed_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# key_padding_mask: (B, L) True = bỏ qua (padding)
# attn_mask: (L, L) mask True/float tùy phiên bản — đọc docs cẩn thận
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;official&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;average_attn_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Cần kiểm tra kỹ tài liệu theo đúng phiên bản PyTorch đang sử dụng vì quy ước kiểu dữ liệu của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;attn_mask&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bool&lt;/code&gt; so với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float&lt;/code&gt; cộng) có thể khác nhau.&lt;/p&gt;

&lt;h3 id=&quot;43-phác-thảo-seq2seq-with-attention-tối-giản&quot;&gt;4.3 Phác thảo seq2seq-with-attention tối giản&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Seq2SeqWithAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Encoder-decoder giáo dục nhỏ:
    - encoder GRU trên source embeddings
    - bước decoder GRU
    - attention dot kiểu Luong trên encoder outputs
    Không phải NMT production; shape là bài học.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;src_vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt_vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;src_emb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;src_vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tgt_emb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tgt_vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;GRU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;GRU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt_vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;attend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dec_h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# dec_h: (B, 1, d), enc_out: (B, Ls, d)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# scores: (B, 1, Ls)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dec_h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, 1, d)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;src&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# src: (B, Ls), tgt: (B, Lt)  — đầu vào teacher forcing
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;src_emb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;src&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dec_in&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tgt_emb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dec_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dec_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# mỗi vị trí decoder chú ý tới encoder (theo batch)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dec_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# (B, Lt, Ls)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;# (B, Lt, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dec_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Seq2SeqWithAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;120&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;src&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;120&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;src&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2,3,120), (2,3,4)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;44-trực-quan-hóa-một-head-tùy-chọn&quot;&gt;4.4 Trực quan hóa một head (tùy chọn)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;plot_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Attention&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;weights_2d: mảng numpy (Lq, Lk)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;imshow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;aspect&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;auto&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;interpolation&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;nearest&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;colorbar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xticks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rotation&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;45&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;right&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;yticks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Key positions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Query positions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ với trọng số multi-head causal ở trên
# plot_attention(w[0, 0].detach().numpy())  # batch 0, head 0
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Residual và LayerNorm&lt;/strong&gt;: cách bố trí Pre-LN hay Post-LN quanh khối multi-head ảnh hưởng trực tiếp tới độ ổn định khi huấn luyện mạng sâu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ lệch vị trí tương đối (Relative position bias)&lt;/strong&gt;: các mô hình như T5 hay Shaw et al. cộng thêm hạng tử phụ thuộc khoảng cách tương đối vào điểm số attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-attention&lt;/strong&gt;: trong Transformer encoder–decoder, cross-attention dùng lại đúng cấu trúc multi-head nhưng lấy Q từ decoder và K, V từ encoder.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FlashAttention / SDPA&lt;/strong&gt;: tối ưu hóa truy cập bộ nhớ bằng cách hợp nhất chuỗi phép tính matmul–softmax–matmul trong khi giữ nguyên kết quả toán học.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Attention thưa (Sparse attention)&lt;/strong&gt;: các kiến trúc như Longformer hay BigBird giới hạn tập vị trí có trọng số \(\alpha\) khác 0 để xử lý chuỗi rất dài.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Bahdanau et al., 2015&lt;/a&gt;&lt;/strong&gt; — &lt;em&gt;Neural Machine Translation by Jointly Learning to Align and Translate.&lt;/em&gt;&lt;br /&gt;
Giới thiệu attention cộng tính giúp decoder tự học căn chỉnh mềm với các trạng thái nguồn mà không cần nhãn căn chỉnh tường minh.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Luong et al., 2015&lt;/a&gt;&lt;/strong&gt; — &lt;em&gt;Effective Approaches to Attention-based NMT.&lt;/em&gt;&lt;br /&gt;
Trình bày các hàm chấm điểm nhân tính, phân biệt attention toàn cục và cục bộ cùng kỹ thuật &lt;em&gt;input feeding&lt;/em&gt; cho decoder.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1502.03044&quot;&gt;Xu et al., 2015&lt;/a&gt;&lt;/strong&gt; — &lt;em&gt;Show, Attend and Tell.&lt;/em&gt;&lt;br /&gt;
Áp dụng attention thị giác (cả dạng mềm và dạng cứng) cho bài toán sinh chú thích ảnh, mở rộng phạm vi ứng dụng đa phương thức.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Vaswani et al., 2017&lt;/a&gt;&lt;/strong&gt; — &lt;em&gt;Attention Is All You Need.&lt;/em&gt;&lt;br /&gt;
Đề xuất multi-head scaled self-attention làm phép toán xử lý chuỗi trung tâm cho kiến trúc Transformer.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1803.02155&quot;&gt;Shaw et al., 2018&lt;/a&gt;&lt;/strong&gt; — &lt;em&gt;Self-Attention with Relative Position Representations.&lt;/em&gt;&lt;br /&gt;
Đưa biểu diễn khoảng cách tương đối vào điểm số attention, giúp cải thiện khả năng tổng quát hóa theo độ dài chuỗi.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-cạm-bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;7. Cạm bẫy thường gặp và mẹo thực hành&lt;/h2&gt;
&lt;h3 id=&quot;các-lỗi-nghiêm-trọng-cần-tránh&quot;&gt;Các lỗi nghiêm trọng cần tránh&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Softmax sai trục&lt;/strong&gt; — phải luôn chuẩn hóa dọc theo trục key/bộ nhớ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp mask sau softmax&lt;/strong&gt; — cần cộng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt; trực tiếp vào điểm số trước softmax.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quên hệ số \(1/\sqrt{d_k}\)&lt;/strong&gt; — gây bão hòa softmax và suy giảm gradient khi chiều head lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Reshape head sai thứ tự&lt;/strong&gt; — luôn kiểm thử chuỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view → transpose → attention → transpose → view&lt;/code&gt; trên tensor đã biết giá trị.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Rò rỉ padding&lt;/strong&gt; — luôn truyền &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;key_padding_mask&lt;/code&gt; tường minh khi huấn luyện theo batch có độ dài khác nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Rò rỉ thông tin tương lai (causal)&lt;/strong&gt; — kiểm tra bằng unit-test để đảm bảo phần tam giác trên của trọng số bằng 0.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhầm vị trí đặt dropout&lt;/strong&gt; — cần nhất quán xem dropout áp lên trọng số sau softmax hay ở đầu ra, đồng thời đảm bảo chuyển đúng chế độ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;danh-mục-kiểm-tra-gỡ-lỗi&quot;&gt;Danh mục kiểm tra gỡ lỗi&lt;/h3&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[ ] In shapes: Q,K,V,scores,weights,output
[ ] weights.sum(dim=keys) == 1
[ ] causal: triu(weights,1) == 0
[ ] pad positions: weights[..., pad] == 0
[ ] Không NaN sau chạy dài (kiểm scale + trừ max trong softmax tự viết)
[ ] Gradient chảy tới Wq/Wk/Wv (hook hoặc .grad sau backward)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;mẹo-thực-hành&quot;&gt;Mẹo thực hành&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Bắt đầu kiểm chứng với &lt;strong&gt;một head&lt;/strong&gt; và attention đầy đủ; chỉ mở rộng sang nhiều head sau khi phiên bản đơn giản đã hoạt động ổn định.&lt;/li&gt;
  &lt;li&gt;Theo dõi &lt;strong&gt;entropy của phân phối attention&lt;/strong&gt; theo từng lớp: entropy quá gần 0 cho thấy phân phối bị tập trung cực đoan, còn quá cao có thể báo hiệu trọng số gần như đều nhau (chưa học được mẫu).&lt;/li&gt;
  &lt;li&gt;Với bài toán dịch máy hoặc seq2seq, trực quan hóa bản đồ attention trên vài cặp câu mẫu sau mỗi epoch để phát hiện sớm lỗi mask.&lt;/li&gt;
  &lt;li&gt;Dùng các kernel SDPA tối ưu khi chạy thực tế, nhưng giữ bản cài đặt chuẩn đơn giản để làm mốc đối chiếu khi kiểm thử.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-tóm-tắt-các-điểm-chính&quot;&gt;8. Tóm tắt các điểm chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Multi-head attention&lt;/strong&gt; kết hợp nhiều cơ chế định tuyến mềm chạy song song rồi trộn đầu ra qua lớp tuyến tính \(W^O\).&lt;/li&gt;
  &lt;li&gt;Thao tác tách và ghép head là bài toán sắp xếp chiều tensor nên cần kiểm thử cẩn thận.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Causal mask và padding mask&lt;/strong&gt; là bộ phận cấu thành của thuật toán trong mọi hệ thống thực tế.&lt;/li&gt;
  &lt;li&gt;Chuỗi bài báo từ Bahdanau, Luong đến Vaswani đánh dấu bước chuyển từ thành phần bổ trợ cho RNN sang kiến trúc độc lập.&lt;/li&gt;
  &lt;li&gt;Phần lớn lỗi khi attention không hội tụ xuất phát từ &lt;strong&gt;sai trục softmax, sai mask hoặc thiếu chia tỉ lệ&lt;/strong&gt;, hơn là do bộ tối ưu.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Đến đây, bạn đã đi trọn mạch từ trực giác, toán học, mã nguồn cốt lõi đến multi-head attention. Chương 08 sẽ kết hợp các khối này cùng mạng feed-forward, kết nối phần dư và mã hóa vị trí để xây dựng kiến trúc Transformer hoàn chỉnh.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến); các đường dẫn dưới đây được lưu lại để tra cứu và ghi nhận nguồn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1806844676942638&quot;&gt;Công thức Attention: tự tay tính Q, K, V&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1007473105556936&quot;&gt;Attention trong Transformer (Self, Masked, Cross, Multi-Head)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=mmzRYGCfTzc&quot;&gt;A Dive Into Multihead Attention, Self-Attention and Cross-Attention&lt;/a&gt; — Machine Learning Studio (tiếng Anh). Làm rõ bản chất của multi-head là nhiều bản đồ attention song song thay vì một lớp softmax lớn hơn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown (tiếng Anh). Trình bày trực quan kỹ thuật che (masking) cho ràng buộc nhân quả trong phần bẫy thường gặp.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Cài đặt mặt nạ nhân quả trực tiếp trong mã nguồn, giúp thấy rõ hậu quả nếu thiếu bước này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-02-02-01 Cài đặt Attention Cốt lõi</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_02_02_01_Attention_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_02_02_01_Attention_Core_Code</id>
   <content type="html">&lt;p&gt;Cách tốt nhất để biến công thức Attention từ một dòng ký hiệu trừu tượng thành công cụ bạn thực sự làm chủ là tự tay viết hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bahdanau_attention&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scaled_dot_product_attention&lt;/code&gt;, chạy trên một ví dụ nhỏ và &lt;strong&gt;in thẳng ma trận trọng số chú ý \(\alpha\) ra màn hình&lt;/strong&gt;. Khi thấy từng con số xác suất tự động sáng lên ở đúng các cặp từ tương ứng, trực giác về soft alignment sẽ khắc sâu ngay lập tức.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-kỹ-thuật-lập-trình-cốt-lõi-cho-attention&quot;&gt;Kiến thức cần nhớ: Bốn kỹ thuật lập trình cốt lõi cho Attention&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Ổn định số học cho Softmax (Log-Sum-Exp Trick)&lt;/strong&gt;:
Trừ đi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt; trên trục tính softmax trước khi lấy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;exp&lt;/code&gt; giúp tránh tràn số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;exp(1000) = inf&lt;/code&gt;, đảm bảo kết quả luôn hữu hạn và chính xác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xử lý Mask an toàn với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;masked_fill(mask == 0, -1e9)&lt;/code&gt; (hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-float(&apos;inf&apos;)&lt;/code&gt;)&lt;/strong&gt;:
Lưu ý trường hợp biên: nếu cả một hàng bị mask toàn bộ thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt; (ví dụ một câu toàn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;PAD&amp;gt;&lt;/code&gt;), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softmax&lt;/code&gt; sẽ sinh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; — vì thế cần kiểm tra kỹ mask hoặc dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nan_to_num&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tách rõ chiều &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L_q&lt;/code&gt; (Query) và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L_k&lt;/code&gt; (Key/Value)&lt;/strong&gt;:
Trong Self-Attention thì \(L_q = L_k\), nhưng trong Cross-Attention (dịch máy, hỏi đáp ảnh) thì \(L_q \ne L_k\) — viết code luôn phân biệt rõ hai chiều này giúp hàm tái sử dụng được cho cả hai chế độ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng Soft Alignment bằng bảng trọng số&lt;/strong&gt;:
Quan sát tổng mỗi hàng bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.000&lt;/code&gt; và kiểm tra xem khi làm sắc nét điểm số (tăng độ lớn query/key), phân phối hội tụ dần về hard alignment (chỉ chọn 1 vị trí).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-bước-ổn-định-số-học-softmax-khi-có-giá-trị-lớn-và-vị-trí-bị-mask&quot;&gt;Giải thích: Tính tay bước ổn định số học Softmax khi có giá trị lớn và vị trí bị Mask&lt;/h3&gt;

&lt;p&gt;Giả sử một hàng điểm chú ý trước softmax là \(\mathbf{s} = [100{,}0, \; 102{,}0, \; 500{,}0]\) nhưng vị trí thứ 3 là token &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;PAD&amp;gt;&lt;/code&gt; (bị mask):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Áp dụng Mask trước Softmax&lt;/strong&gt;:
\(\mathbf{s}_{\text{masked}} = [100{,}0, \; 102{,}0, \; -\infty]\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Trừ đi giá trị lớn nhất của các phần tử hợp lệ&lt;/strong&gt; (\(m = \max(100{,}0, 102{,}0) = 102{,}0\)):
\(\mathbf{s}_{\text{shift}} = [-2{,}0, \; 0{,}0, \; -\infty]\)
(Nếu không trừ \(102{,}0\), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;exp(102)&lt;/code&gt; bằng \(1{,}98 \times 10^{44}\) sẽ tràn ngay giới hạn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float16&lt;/code&gt; tối đa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;65504&lt;/code&gt;!)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Tính hàm mũ và chuẩn hóa&lt;/strong&gt;:
\(e^{-2} \approx 0{,}1353, \quad e^{0} = 1{,}0000, \quad e^{-\infty} = 0\)
\(\boldsymbol{\alpha} = \left[\frac{0{,}1353}{1{,}1353}, \; \frac{1{,}0000}{1{,}1353}, \; 0\right] \approx \mathbf{[0{,}1192, \; 0{,}8808, \; 0{,}0000]}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Không hề có tràn số FP16, tổng xác suất bằng đúng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.0000&lt;/code&gt;, và vị trí &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;PAD&amp;gt;&lt;/code&gt; nhận trọng số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0000&lt;/code&gt; tuyệt đối!&lt;/p&gt;

&lt;h1 id=&quot;cài-đặt-attention-cốt-lõi&quot;&gt;Cài đặt Attention Cốt lõi&lt;/h1&gt;

&lt;p&gt;Bài này chuyển các phương trình attention thành mã nguồn chạy được. Ta sẽ cài đặt attention cộng tính (Bahdanau) cho mô hình encoder–decoder và scaled self-attention bằng cả NumPy lẫn PyTorch, chú trọng vào kích thước tensor và độ ổn định số học.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Mọi cài đặt attention chuẩn đều thực hiện bốn bước cơ bản:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Tính &lt;strong&gt;điểm số&lt;/strong&gt; giữa các queries và keys.&lt;/li&gt;
  &lt;li&gt;Áp &lt;strong&gt;mask&lt;/strong&gt; (nếu có) trực tiếp lên điểm số trước softmax.&lt;/li&gt;
  &lt;li&gt;Tính &lt;strong&gt;softmax&lt;/strong&gt; dọc theo trục keys.&lt;/li&gt;
  &lt;li&gt;Nhân ma trận trọng số với &lt;strong&gt;values&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Các phần còn lại thuộc về thiết kế giao diện lập trình: tổ chức hàm hay lớp, dùng NumPy hay &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn&lt;/code&gt;, hỗ trợ theo batch và mở rộng sang multi-head (sẽ trình bày ở bài tiếp theo).&lt;/p&gt;

&lt;p&gt;Ta bắt đầu từ &lt;strong&gt;Bahdanau&lt;/strong&gt; để thấy rõ cơ chế tính điểm trên từng trạng thái encoder, sau đó chuyển sang &lt;strong&gt;scaled dot-product attention dạng ma trận&lt;/strong&gt; dùng trong Transformer.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-nhắc-lại-công-thức-phục-vụ-cài-đặt&quot;&gt;2. Nhắc lại công thức phục vụ cài đặt&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Điểm số Bahdanau:&lt;/strong&gt;&lt;/p&gt;

\[e_{i} = \mathbf{v}^\top \tanh(\mathbf{W}_h\mathbf{h}_i + \mathbf{W}_s\mathbf{s}).\]

&lt;p&gt;&lt;strong&gt;Scaled dot-product attention:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{A}=\mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}+\mathbf{M}\right),\quad
\mathbf{Y}=\mathbf{A}\mathbf{V}.\]

&lt;p&gt;&lt;strong&gt;Softmax ổn định số học&lt;/strong&gt; cho vectơ \(\mathbf{z}\):&lt;/p&gt;

\[\mathrm{softmax}(\mathbf{z})_i=\frac{\exp(z_i-\max_j z_j)}{\sum_j\exp(z_j-\max_j z_j)}.\]

&lt;p&gt;Khi tự cài đặt softmax, luôn trừ đi giá trị lớn nhất trên trục tính toán để tránh tràn số ở hàm mũ.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-trực-giác-cho-ví-dụ-minh-họa&quot;&gt;3. Trực giác cho ví dụ minh họa&lt;/h2&gt;

&lt;p&gt;Ta mô phỏng một bài toán dịch máy thu gọn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Câu nguồn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;I love deep learning&lt;/code&gt; tạo ra bốn trạng thái encoder.&lt;/li&gt;
  &lt;li&gt;Tại mỗi bước sinh từ đích, một trạng thái decoder truy vấn bốn trạng thái này.&lt;/li&gt;
  &lt;li&gt;Bảng trọng số attention in ra cho biết từ nguồn nào đang nhận mức chú ý cao nhất.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Do trọng số được khởi tạo ngẫu nhiên và chưa qua huấn luyện, mục tiêu của đoạn minh họa là kiểm chứng &lt;strong&gt;luồng dữ liệu và kích thước tensor&lt;/strong&gt;; khi huấn luyện trên dữ liệu thật, bảng căn chỉnh này sẽ phản ánh đúng mối liên hệ ngữ nghĩa giữa hai ngôn ngữ.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;
&lt;h3 id=&quot;41-tiện-ích&quot;&gt;4.1 Tiện ích&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax_last&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Softmax trên trục cuối với trừ max.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;42-attention-bahdanau-rõ-ràng-dạng-vòng-lặp&quot;&gt;4.2 Attention Bahdanau (rõ ràng, dạng vòng lặp)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BahdanauAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Additive attention cho mô hình encoder-decoder.

    decoder_state: (d,) hoặc (d, 1)
    encoder_states: (L, d)   — một hàng mỗi vị trí nguồn
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Ws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,))&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__call__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decoder_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;encoder_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;asarray&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;# (d,)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;asarray&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                    &lt;span class=&quot;c1&quot;&gt;# (L, d)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ndim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;

        &lt;span class=&quot;c1&quot;&gt;# scores[i] = v^T tanh(Wh h_i + Ws s)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;proj_h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;                            &lt;span class=&quot;c1&quot;&gt;# (L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;proj_s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Ws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;                              &lt;span class=&quot;c1&quot;&gt;# (d,)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;proj_h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;proj_s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                      &lt;span class=&quot;c1&quot;&gt;# broadcast (L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;                               &lt;span class=&quot;c1&quot;&gt;# (L,)
&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax_last&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                      &lt;span class=&quot;c1&quot;&gt;# (L,)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;                               &lt;span class=&quot;c1&quot;&gt;# (d,)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;43-demo-bảng-soft-alignment&quot;&gt;4.3 Demo: bảng soft alignment&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;encoder_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;source&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;I&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;love&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;deep&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;learning&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;J&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;aime&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;apprentissage&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;profond&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BahdanauAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Target&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | attention over source&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;decoder_state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;encoder_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;join&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;source&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;isclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;44-scaled-self-attention-numpy-véc-tơ-hóa&quot;&gt;4.4 Scaled self-attention (NumPy véc-tơ hóa)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Hỗ trợ shape:
      (Lq, d), (Lk, d), (Lk, dv)
      hoặc batch (..., Lq, d), (..., Lk, d), (..., Lk, dv)
    mask: boolean mask broadcast được, True = key bị cấm
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;swapaxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax_last&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Self-attention trên chuỗi ngắn
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;no future mass:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;atol&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;45-module-pytorch-scaled-attention-một-head&quot;&gt;4.5 Module PyTorch (scaled attention một head)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ScaledDotProductAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Q,K,V: (B, L, d)  — một head cho rõ
        attn_mask: mask cộng broadcast được tới (B, Lq, Lk)
                   dùng 0 để giữ, -inf để cấm
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSelfAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ScaledDotProductAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# causal mask cộng: (1, L, L)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;full&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-inf&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;diagonal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSelfAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2,7,32), (2,7,7)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;46-kiểm-tra-kích-thước-khi-gỡ-lỗi&quot;&gt;4.6 Kiểm tra kích thước khi gỡ lỗi&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;show_attn_shapes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;scores expected&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;


&lt;span class=&quot;nf&quot;&gt;show_attn_shapes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# scores: (2, 5, 9)  — mỗi trong 5 queries chú ý trên 9 keys
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Teacher forcing trong seq2seq&lt;/strong&gt;: trong huấn luyện, decoder nhận token nhãn đúng của bước trước làm đầu vào, còn cơ chế attention vẫn chạy ở từng bước.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Input feeding (Luong)&lt;/strong&gt;: đưa vectơ ngữ cảnh của bước trước quay lại làm một phần đầu vào cho bước decoder tiếp theo, thường giúp cải thiện chất lượng dịch máy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.MultiheadAttention&lt;/code&gt; và SDPA&lt;/strong&gt;: các cài đặt tối ưu dùng trong sản xuất; nên hiểu rõ cách cài đặt thủ công trong bài trước khi sử dụng chúng như thành phần đóng gói sẵn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đệm theo batch (batch padding)&lt;/strong&gt;: bắt buộc dùng padding mask khi huấn luyện theo batch gồm các chuỗi có độ dài khác nhau.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-tài-liệu-tham-khảo-liên-quan-đến-cài-đặt&quot;&gt;6. Tài liệu tham khảo liên quan đến cài đặt&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Bahdanau et al., 2015&lt;/a&gt; — thuật toán chuẩn cho attention cộng tính.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Luong et al., 2015&lt;/a&gt; — các hàm chấm điểm gọn nhẹ dùng phổ biến trong hệ thống dịch máy RNN.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Vaswani et al., 2017&lt;/a&gt; — scaled dot-product attention dạng ma trận và multi-head.&lt;/li&gt;
  &lt;li&gt;Tài liệu PyTorch: &lt;a href=&quot;https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.MultiheadAttention&lt;/code&gt;&lt;/a&gt; — hướng dẫn chi tiết về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_first&lt;/code&gt;, quy ước mask và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;average_attn_weights&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-cạm-bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;7. Cạm bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Lỗi&lt;/th&gt;
      &lt;th&gt;Triệu chứng&lt;/th&gt;
      &lt;th&gt;Cách khắc phục&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Softmax sai trục&lt;/td&gt;
      &lt;td&gt;Tổng trọng số bằng 1 theo chiều query hoặc batch thay vì chiều key&lt;/td&gt;
      &lt;td&gt;Áp softmax trên &lt;strong&gt;trục keys&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Gán &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; sau softmax&lt;/td&gt;
      &lt;td&gt;Token bị cấm vẫn ảnh hưởng đến gradient và phân phối&lt;/td&gt;
      &lt;td&gt;Cộng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt; &lt;strong&gt;trước&lt;/strong&gt; softmax&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Nhầm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Wh @ h&lt;/code&gt; với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h @ Wh&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Lỗi kích thước hoặc nhân nhầm chiều ẩn&lt;/td&gt;
      &lt;td&gt;Thống nhất quy ước chiều và viết unit-test&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Trộn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(d,)&lt;/code&gt; với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(d, 1)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Lỗi broadcast ngoài ý muốn&lt;/td&gt;
      &lt;td&gt;Chuẩn hóa kích thước bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reshape(-1)&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Không trừ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Xuất hiện &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; khi điểm số lớn&lt;/td&gt;
      &lt;td&gt;Luôn dùng softmax ổn định số học&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Mẹo:&lt;/strong&gt; với causal self-attention, hãy kiểm tra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;triu(weights, 1) == 0&lt;/code&gt; sau mỗi lần sửa mã nguồn mask.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mẹo:&lt;/strong&gt; in ma trận trọng số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alpha&lt;/code&gt; trên chuỗi ngắn 3–4 token để kiểm chứng trước khi mở rộng sang mô hình lớn.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-tóm-tắt-các-điểm-chính&quot;&gt;8. Tóm tắt các điểm chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Luồng cài đặt attention luôn theo thứ tự: &lt;strong&gt;tính điểm số → áp mask → softmax → nhân với values&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Cài đặt Bahdanau giúp dễ hình dung cơ chế từng bước, còn phép nhân ma trận có chia tỉ lệ là dạng chuẩn trong thực tế.&lt;/li&gt;
  &lt;li&gt;Các bước đảm bảo &lt;strong&gt;ổn định số học&lt;/strong&gt; (trừ giá trị cực đại, chia &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sqrt(d_k)&lt;/code&gt;, dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt; cho mask) là phần thiết yếu của thuật toán.&lt;/li&gt;
  &lt;li&gt;Viết kiểm thử đơn vị trên tensor nhỏ giúp phát hiện sớm phần lớn lỗi liên quan đến chiều và mask.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bài tiếp theo sẽ mở rộng sang &lt;strong&gt;multi-head attention&lt;/strong&gt;, minh họa mô hình seq2seq có attention và tổng hợp quy trình gỡ lỗi.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Cài đặt chi tiết từng dòng scaled dot-product attention (video dài; phần attention khớp trực tiếp với bài này).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown (tiếng Anh). Đối chiếu kích thước của Q, K, V khi viết mã.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mmzRYGCfTzc&quot;&gt;A Dive Into Multihead Attention, Self-Attention and Cross-Attention&lt;/a&gt; — Machine Learning Studio (tiếng Anh). Gợi ý các bước mở rộng sau khi đã hoàn thiện phiên bản một head.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-02-01 Toán học Attention</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_02_01_Attention_Math/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_02_01_Attention_Math</id>
   <content type="html">&lt;p&gt;Công thức \(\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{Q K^T}{\sqrt{d_k}}\right) V\) ngắn đến mức có thể in gọn lên một chiếc áo thun, nhưng bên trong nó hội tụ cả xác suất thống kê (kiểm soát phương sai), đại số tuyến tính (phép chiếu và nhân ma trận batch), lẫn giải tích (tránh vùng phẳng đạo hàm của softmax). Đọc chậm từng ký hiệu trong công thức này sẽ giúp bạn thông suốt cả Chương 07 và Chương 08.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-toán-học-của-scaled-dot-product-attention&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột toán học của Scaled Dot-Product Attention&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Họ các hàm chấm điểm tương đồng (Scoring Functions)&lt;/strong&gt;:
Từ Dot-Product (\(q^T k\)), Scaled Dot-Product (\(q^T k / \sqrt{d_k}\)), Bilinear/Luong (\(q^T W k\)) đến Additive/Bahdanau (\(v^T \tanh(W_q q + W_k k)\)) — khác nhau về số tham số và chi phí tính toán trên GPU.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định lý phương sai đằng sau hệ số \(\frac{1}{\sqrt{d_k}}\)&lt;/strong&gt;:
Nếu \(q_i, k_i \sim \mathcal{N}(0, 1)\) độc lập thì \(\operatorname{Var}(q_i k_i) = \operatorname{Var}(q_i)\operatorname{Var}(k_i) = 1\), suy ra \(\operatorname{Var}(q^T k) = d_k\); chia cho \(\sqrt{d_k}\) giúp \(\operatorname{Var}\!\left(\frac{q^T k}{\sqrt{d_k}}\right) = 1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dạng ma trận theo batch và độ phức tạp \(O(L^2 d)\)&lt;/strong&gt;:
Với \(Q \in \mathbb{R}^{B \times L_q \times d_k}\), \(K \in \mathbb{R}^{B \times L_k \times d_k}\), \(V \in \mathbb{R}^{B \times L_k \times d_v}\), ma trận điểm số \(Q K^T\) có kích thước \(B \times L_q \times L_k\) — nguồn gốc của chi phí bộ nhớ và tính toán bậc hai theo độ dài chuỗi \(L\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế mặt nạ (Masking) bằng phép cộng \(M \in \{0, -\infty\}\)&lt;/strong&gt;:
Cộng \(-\infty\) (thực tế &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-1e9&lt;/code&gt; hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt;) vào các vị trí bị cấm &lt;em&gt;trước&lt;/em&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softmax&lt;/code&gt; khiến \(e^{-\infty} = 0\) tuyệt đối, bảo toàn tổng xác suất các vị trí hợp lệ luôn bằng đúng 1.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-trọn-vẹn-ma-trận-operatornameattentionq-k-v-cho-chuỗi-2-token-d_k--4&quot;&gt;Giải thích: Tính tay trọn vẹn ma trận \(\operatorname{Attention}(Q, K, V)\) cho chuỗi 2 token (\(d_k = 4\))&lt;/h3&gt;

&lt;p&gt;Cho \(L = 2, \; d_k = 4 \implies \sqrt{d_k} = 2\), với các ma trận (mỗi hàng là 1 token):
\(Q = \begin{bmatrix} 2 &amp;amp; 0 &amp;amp; 0 &amp;amp; 0 \\ 0 &amp;amp; 2 &amp;amp; 0 &amp;amp; 0 \end{bmatrix}, \quad K = \begin{bmatrix} 1 &amp;amp; 0 &amp;amp; 0 &amp;amp; 0 \\ 1 &amp;amp; 2 &amp;amp; 0 &amp;amp; 0 \end{bmatrix}, \quad V = \begin{bmatrix} 10 &amp;amp; 0 \\ 0 &amp;amp; 20 \end{bmatrix}\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Tính tích ma trận điểm số \(S = Q K^T\)&lt;/strong&gt;:
\(Q K^T = \begin{bmatrix} 2\cdot 1 &amp;amp; 2\cdot 1 \\ 0 &amp;amp; 2\cdot 2 \end{bmatrix} = \begin{bmatrix} 2 &amp;amp; 2 \\ 0 &amp;amp; 4 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Chia tỉ lệ cho \(\sqrt{d_k} = 2\)&lt;/strong&gt;:
\(\frac{Q K^T}{2} = \begin{bmatrix} 1 &amp;amp; 1 \\ 0 &amp;amp; 2 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Tính Softmax theo từng hàng&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Hàng 1 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1, 1]&lt;/code&gt;): \(\left[\frac{e^1}{2e^1}, \; \frac{e^1}{2e^1}\right] = \mathbf{[0{,}500, \; 0{,}500]}\)&lt;/li&gt;
      &lt;li&gt;Hàng 2 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0, 2]&lt;/code&gt;, với \(e^2 \approx 7{,}389\)): \(\left[\frac{1}{8{,}389}, \; \frac{7{,}389}{8{,}389}\right] \approx \mathbf{[0{,}119, \; 0{,}881]}\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 4 — Nhân với \(V\) để ra đầu ra Attention&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Token 1: \(0{,}500[10, 0] + 0{,}500[0, 20] = \mathbf{[5{,}00, \; 10{,}00]}\)&lt;/li&gt;
      &lt;li&gt;Token 2: \(0{,}119[10, 0] + 0{,}881[0, 20] = \mathbf{[1{,}19, \; 17{,}62]}\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nếu thêm &lt;strong&gt;Causal Mask&lt;/strong&gt; (cấm token 1 nhìn thấy token 2 tương lai), ô &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(0, 1)&lt;/code&gt; trong bước 2 bị cộng \(-\infty\), hàng 1 lập tức biến thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1.0, 0.0]&lt;/code&gt; và đầu ra token 1 chỉ còn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[10.0, 0.0]&lt;/code&gt;.&lt;/p&gt;

&lt;h1 id=&quot;toán-học-attention&quot;&gt;Toán học Attention&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/tensorflow/nmt/master/nmt/g3doc/img/attention_mechanism.jpg&quot; alt=&quot;Attention Mechanism Visualization&quot; /&gt;
&lt;em&gt;Attention trong dịch máy neuron cổ điển: trạng thái decoder tạo truy vấn trên keys và values của encoder. Nguồn: TensorFlow NMT tutorial&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Bài này xây dựng attention dưới góc độ toán học chặt chẽ. Tiếp nối phần trực giác ở bài 07-01, ta thống nhất hệ thống ký hiệu, so sánh các họ hàm chấm điểm, biểu diễn toàn bộ phép tính ở dạng ma trận theo batch, đồng thời hình thức hóa multi-head attention và masking thành các phương trình rõ ràng.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Về bản chất, attention là một &lt;strong&gt;phép tra cứu mềm có tham số và khả vi&lt;/strong&gt;. Với một vectơ truy vấn (query) biểu thị thông tin cần tìm, attention đối chiếu query với tập các khóa (keys), chuyển điểm tương đồng thành phân phối xác suất rồi trả về tổ hợp có trọng số của các giá trị (values).&lt;/p&gt;

&lt;p&gt;Một cơ chế attention cụ thể được xác định bởi ba yếu tố thiết kế:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nguồn tạo Q, K, V&lt;/strong&gt; — decoder kết hợp encoder (cross-attention) hay cùng một chuỗi (self-attention).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm chấm điểm tương đồng&lt;/strong&gt; — cộng tính, song tuyến hay scaled dot product.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phạm vi vị trí hợp lệ&lt;/strong&gt; — attention đầy đủ, padding mask, causal mask hoặc mẫu thưa.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Các biến thể quen thuộc (Bahdanau, Luong, self-attention và multi-head attention trong Transformer) đều tương ứng với các lựa chọn cụ thể trên ba trục này.&lt;/p&gt;

&lt;p&gt;Biểu thức tổng quát:&lt;/p&gt;

\[\text{Attention}(\mathbf{q}, \{(\mathbf{k}_j,\mathbf{v}_j)\}_j)
= \sum_j \alpha_j \mathbf{v}_j,
\quad
\alpha = \mathrm{softmax}(\mathrm{score}(\mathbf{q},\mathbf{k}_\cdot)).\]

&lt;p&gt;Khi biểu diễn bằng ma trận, phép tổng trở thành phép nhân ma trận; multi-head attention thực hiện song song nhiều bản sao độc lập của ánh xạ này.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_qk_matmul.jpg&quot; alt=&quot;Bước 1: $$Q K^\top$$&quot; /&gt;
&lt;em&gt;Hình: Điểm số thô tính bằng tích \(Q\) với \(K^\top\) (mỗi token tương ứng một hàng query). (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_scaled_dot_product.jpg&quot; alt=&quot;Scaled softmax rồi × V&quot; /&gt;
&lt;em&gt;Hình: Chia cho \(\sqrt{d_k}\), áp dụng softmax rồi nhân với \(V\). (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;h3 id=&quot;21-attention-cho-một-query&quot;&gt;2.1 Attention cho một query&lt;/h3&gt;

&lt;p&gt;Xét:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Query \(\mathbf{q} \in \mathbb{R}^{d_q}\),&lt;/li&gt;
  &lt;li&gt;Keys \(\mathbf{k}_j \in \mathbb{R}^{d_k}\), với \(j=1,\ldots,L\),&lt;/li&gt;
  &lt;li&gt;Values \(\mathbf{v}_j \in \mathbb{R}^{d_v}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Điểm số:&lt;/strong&gt;&lt;/p&gt;

\[e_j = \mathrm{score}(\mathbf{q}, \mathbf{k}_j) \in \mathbb{R}.\]

&lt;p&gt;&lt;strong&gt;Trọng số:&lt;/strong&gt;&lt;/p&gt;

\[\alpha_j = \frac{\exp(e_j)}{\sum_{\ell=1}^{L}\exp(e_\ell)}.\]

&lt;p&gt;&lt;strong&gt;Đầu ra:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{c} = \sum_{j=1}^{L} \alpha_j \mathbf{v}_j \in \mathbb{R}^{d_v}.\]

&lt;p&gt;Khi không dùng mask, đầu ra luôn thỏa mãn các tính chất:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\alpha_j \ge 0\) và \(\sum_j \alpha_j = 1\),&lt;/li&gt;
  &lt;li&gt;\(\mathbf{c}\) nằm trong bao lồi của tập \(\{\mathbf{v}_j\}\),&lt;/li&gt;
  &lt;li&gt;Nếu một điểm số vượt trội so với phần còn lại, \(\mathbf{c}\) tiến gần tới value tương ứng (tương tự &lt;em&gt;soft argmax&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;22-các-họ-hàm-chấm-điểm&quot;&gt;2.2 Các họ hàm chấm điểm&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Cộng tính (Bahdanau):&lt;/strong&gt;&lt;/p&gt;

\[\mathrm{score}(\mathbf{q},\mathbf{k}) = \mathbf{v}_a^\top \tanh(\mathbf{W}_q\mathbf{q} + \mathbf{W}_k\mathbf{k}).\]

&lt;ul&gt;
  &lt;li&gt;Linh hoạt khi query và key ban đầu nằm ở các không gian có số chiều khác nhau.&lt;/li&gt;
  &lt;li&gt;Chi phí cao hơn trên GPU khi \(L\) lớn do chứa hàm phi tuyến và phép chiếu phụ \(\mathbf{v}_a\) thay vì chỉ nhân ma trận thuần túy.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Song tuyến / tổng quát:&lt;/strong&gt;&lt;/p&gt;

\[\mathrm{score}(\mathbf{q},\mathbf{k}) = \mathbf{q}^\top \mathbf{W} \mathbf{k}.\]

&lt;p&gt;Ma trận \(\mathbf{W}\) học độ đo tương đồng; khi \(\mathbf{W}=\mathbf{I}\), công thức rút gọn về tích vô hướng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tích vô hướng:&lt;/strong&gt;&lt;/p&gt;

\[\mathrm{score}(\mathbf{q},\mathbf{k}) = \mathbf{q}^\top \mathbf{k}.\]

&lt;p&gt;Tính toán nhanh và phù hợp khi \(\mathbf{q}\) và \(\mathbf{k}\) đã được chiếu về cùng không gian.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scaled dot product (Transformer):&lt;/strong&gt;&lt;/p&gt;

\[\mathrm{score}(\mathbf{q},\mathbf{k}) = \frac{\mathbf{q}^\top \mathbf{k}}{\sqrt{d_k}}.\]

&lt;h3 id=&quot;23-vì-sao-cần-chia-tỉ-lệ-lập-luận-phương-sai&quot;&gt;2.3 Vì sao cần chia tỉ lệ (lập luận phương sai)&lt;/h3&gt;

&lt;p&gt;Giả sử các thành phần của \(\mathbf{q}\) và \(\mathbf{k}\) độc lập, có cùng phân phối với kỳ vọng 0 và phương sai 1. Khi đó:&lt;/p&gt;

\[\mathrm{Var}(\mathbf{q}^\top\mathbf{k}) = d_k.\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Nếu \(d_k\) lớn, độ lớn $$&lt;/td&gt;
      &lt;td&gt;\mathbf{q}^\top\mathbf{k}&lt;/td&gt;
      &lt;td&gt;\(có xu hướng lớn theo\)\sqrt{d_k}$$, khiến hàm softmax bão hòa gần như one-hot:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[\alpha \approx \mathbf{e}_{j^\star}, \quad j^\star=\arg\max_j e_j,\]

&lt;p&gt;làm gradient theo các vị trí khác gần như triệt tiêu. Chia cho \(\sqrt{d_k}\) đưa phương sai về xấp xỉ 1 không phụ thuộc vào chiều \(d_k\), giúp quá trình huấn luyện duy trì phân phối trọng số mềm và học ổn định hơn.&lt;/p&gt;

&lt;h3 id=&quot;24-dạng-ma-trận-theo-batch&quot;&gt;2.4 Dạng ma trận theo batch&lt;/h3&gt;

&lt;p&gt;Gộp \(L_q\) queries và \(L_k\) keys thành ma trận:&lt;/p&gt;

\[\mathbf{Q}\in\mathbb{R}^{L_q\times d_k},\quad
\mathbf{K}\in\mathbb{R}^{L_k\times d_k},\quad
\mathbf{V}\in\mathbb{R}^{L_k\times d_v}.\]

&lt;p&gt;Khi đó:&lt;/p&gt;

\[\mathbf{A} = \mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\in\mathbb{R}^{L_q\times L_k},
\qquad
\mathrm{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V})=\mathbf{A}\mathbf{V}\in\mathbb{R}^{L_q\times d_v}.\]

&lt;p&gt;Khi mở rộng thêm chiều batch \(B\) và số head \(H\):&lt;/p&gt;

\[\mathbf{Q},\mathbf{K},\mathbf{V}\in\mathbb{R}^{B\times H\times L\times d_k}
\quad\Rightarrow\quad
\text{scores }\in\mathbb{R}^{B\times H\times L_q\times L_k}.\]

&lt;p&gt;Toàn bộ điểm tương đồng giữa mọi cặp vị trí quy về một phép nhân ma trận theo batch, tận dụng rất tốt kiến trúc tính toán song song của GPU.&lt;/p&gt;

&lt;h3 id=&quot;25-attention-encoderdecoder-cross-attention&quot;&gt;2.5 Attention encoder–decoder (cross-attention)&lt;/h3&gt;

&lt;p&gt;Tại bước decoder \(t\) với trạng thái \(\mathbf{s}_t\) và ma trận trạng thái encoder \(\mathbf{H}=[\mathbf{h}_1;\ldots;\mathbf{h}_{L_x}]\in\mathbb{R}^{L_x\times d}\):&lt;/p&gt;

\[\mathbf{q}_t = f_q(\mathbf{s}_t),\quad
\mathbf{K}=\mathbf{H}\mathbf{W}^K,\quad
\mathbf{V}=\mathbf{H}\mathbf{W}^V,\]

\[\mathbf{c}_t = \mathrm{Attention}(\mathbf{q}_t,\mathbf{K},\mathbf{V}).\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_cross_qkv_projections.jpg&quot; alt=&quot;Cross-attention: Q decoder, K/V encoder&quot; /&gt;
&lt;em&gt;Hình: Query lấy từ decoder (đã áp causal mask), còn keys và values lấy từ encoder. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_cross_attention_pipeline.jpg&quot; alt=&quot;Pipeline cross-attention đầy đủ&quot; /&gt;
&lt;em&gt;Hình: Quy trình cross-attention: chiếu tuyến tính → \(QK^\top\) → softmax → nhân V → đầu ra. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Dạng Bahdanau cổ điển dùng hàm cộng tính trực tiếp giữa \(\mathbf{s}_t\) và từng \(\mathbf{h}_i\) mà không tách riêng \(\mathbf{W}^K, \mathbf{W}^V\) như Transformer, nhưng sự phân vai vẫn hoàn toàn tương tự: query từ decoder, bộ nhớ từ encoder.&lt;/p&gt;

&lt;h3 id=&quot;26-self-attention&quot;&gt;2.6 Self-attention&lt;/h3&gt;

&lt;p&gt;Với ma trận đầu vào \(\mathbf{X}\in\mathbb{R}^{L\times d_{\mathrm{model}}}\):&lt;/p&gt;

\[\mathbf{Q}=\mathbf{X}\mathbf{W}^Q,\quad
\mathbf{K}=\mathbf{X}\mathbf{W}^K,\quad
\mathbf{V}=\mathbf{X}\mathbf{W}^V,\]

\[\mathrm{SelfAttn}(\mathbf{X})=\mathrm{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V}).\]

&lt;p&gt;Hàng thứ \(i\) của đầu ra là tổ hợp có trọng số của mọi hàng value, với trọng số xác định bởi mức khớp giữa query \(i\) và từng key.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Độ dài đường truyền thông tin.&lt;/strong&gt; Bất kỳ hai vị trí nào trong chuỗi cũng tương tác trực tiếp trong &lt;strong&gt;một&lt;/strong&gt; lớp attention (độ dài đường truyền \(O(1)\)), thay vì phải đi qua \(O(L)\) bước tuần tự như RNN. Đây là ưu thế cấu trúc giúp self-attention học phụ thuộc tầm xa dễ dàng hơn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Độ phức tạp tính toán.&lt;/strong&gt; Self-attention đầy đủ tốn \(O(L^2 d)\) phép toán và \(O(L^2)\) bộ nhớ để lưu ma trận điểm số — hiệu quả với độ dài \(L\) trung bình nhưng trở thành nút thắt với văn bản rất dài, thúc đẩy các biến thể attention thưa hoặc tuyến tính.&lt;/p&gt;

&lt;h3 id=&quot;27-multi-head-attention&quot;&gt;2.7 Multi-head attention&lt;/h3&gt;

&lt;p&gt;Với \(H\) head và \(d_k=d_v=d_{\mathrm{model}}/H\):&lt;/p&gt;

\[\mathrm{head}_h=\mathrm{Attention}(\mathbf{X}\mathbf{W}_h^Q,\mathbf{X}\mathbf{W}_h^K,\mathbf{X}\mathbf{W}_h^V),\]

\[\mathrm{MultiHead}(\mathbf{X})=\mathrm{Concat}(\mathrm{head}_1,\ldots,\mathrm{head}_H)\,\mathbf{W}^O.\]

&lt;p&gt;Kích thước các ma trận chiếu:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathbf{W}_h^Q,\mathbf{W}_h^K\in\mathbb{R}^{d_{\mathrm{model}}\times d_k}\),&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}_h^V\in\mathbb{R}^{d_{\mathrm{model}}\times d_v}\),&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}^O\in\mathbb{R}^{H d_v\times d_{\mathrm{model}}}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Lý do dùng nhiều head:&lt;/strong&gt; Softmax chỉ tạo ra một phân phối trọng số duy nhất cho mỗi query và dễ tập trung vào một kiểu quan hệ trội. Tách thành nhiều head cho phép mô hình duy trì đồng thời nhiều phân phối chú ý khác nhau (ví dụ một head theo dõi cú pháp, head khác theo dõi lân cận hoặc liên kết xa), sau đó tổng hợp lại qua \(\mathbf{W}^O\).&lt;/p&gt;

&lt;h3 id=&quot;28-masking-như-phép-cộng-trước-softmax&quot;&gt;2.8 Masking như phép cộng trước softmax&lt;/h3&gt;

&lt;p&gt;Đặt \(\mathbf{S}=\mathbf{Q}\mathbf{K}^\top/\sqrt{d_k}\). Định nghĩa ma trận mặt nạ cộng \(\mathbf{M}\) có kích thước tương thích:&lt;/p&gt;

\[\mathbf{M}_{ij}=\begin{cases}
0 &amp;amp; \text{nếu vị trí }j\text{ được phép với query }i,\\
-\infty &amp;amp; \text{nếu bị cấm.}
\end{cases}\]

&lt;p&gt;Khi đó:&lt;/p&gt;

\[\mathbf{A}=\mathrm{softmax}(\mathbf{S}+\mathbf{M}).\]

&lt;p&gt;Do \(\exp(-\infty)=0\), các vị trí bị cấm vừa có trọng số bằng 0 vừa đảm bảo gradient chính xác — khác với cách gán 0 &lt;em&gt;sau&lt;/em&gt; softmax vốn làm sai phân phối chuẩn hóa và rò rỉ gradient.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Padding mask:&lt;/strong&gt; che các key tương ứng token đệm theo từng mẫu trong batch.&lt;br /&gt;
&lt;strong&gt;Causal mask:&lt;/strong&gt; che các vị trí tương lai \(j&amp;gt;i\) khi giải mã tự hồi quy bằng ma trận tam giác trên \(\mathbf{M}=\mathrm{triu}(-\infty)\) nằm phía trên đường chéo chính.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_with_causal_mask_formula.jpg&quot; alt=&quot;Công thức attention + mask nhân quả&quot; /&gt;
&lt;em&gt;Hình: Cộng ma trận mask \(M\) (gồm \(0\) và \(-\infty\)) &lt;strong&gt;trước&lt;/strong&gt; bước softmax. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_mask_applied_scores.jpg&quot; alt=&quot;Áp mask lên điểm số&quot; /&gt;
&lt;em&gt;Hình: Phần tam giác trên mang giá trị \(-\infty\) để chặn việc nhìn thấy token tương lai. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_future_leak.jpg&quot; alt=&quot;Rò rỉ tương lai nếu không mask&quot; /&gt;
&lt;em&gt;Hình: Thiếu causal mask khiến vị trí hiện tại đọc được phần sau của câu, gây rò rỉ dữ liệu khi huấn luyện. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_causal_generation_arcs.jpg&quot; alt=&quot;Cung chú ý khi sinh autoregressive&quot; /&gt;
&lt;em&gt;Hình: Khi sinh tự hồi quy, mỗi token chỉ chú ý tới chính nó và các token đứng trước. (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;29-kết-nối-phần-dư-trong-thực-tế&quot;&gt;2.9 Kết nối phần dư trong thực tế&lt;/h3&gt;

&lt;p&gt;Trong các kiến trúc sâu, khối attention hầu như luôn đi kèm chuẩn hóa lớp và kết nối phần dư:&lt;/p&gt;

\[\mathbf{X} \leftarrow \mathbf{X} + \mathrm{Dropout}(\mathrm{MultiHead}(\mathrm{Norm}(\mathbf{X})))\]

&lt;p&gt;(hoặc biến thể post-norm). Bản thân phép toán attention không bao gồm kết nối phần dư, nhưng khả năng huấn luyện ổn định ở nhiều lớp sâu phụ thuộc lớn vào cấu trúc ghép nối này.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;h3 id=&quot;31-tính-tay-cross-attention&quot;&gt;3.1 Tính tay cross-attention&lt;/h3&gt;

&lt;p&gt;Giả sử các trạng thái encoder (đồng thời làm key và value) có chiều \(d=2\):&lt;/p&gt;

\[\mathbf{h}_1=\begin{bmatrix}1\\0\end{bmatrix}\ (``I&quot;),\quad
\mathbf{h}_2=\begin{bmatrix}0\\1\end{bmatrix}\ (``love&quot;),\quad
\mathbf{h}_3=\begin{bmatrix}1\\1\end{bmatrix}\ (``ML&quot;).\]

&lt;p&gt;Với query decoder \(\mathbf{q}=\begin{bmatrix}0.9\\0.2\end{bmatrix}\), điểm số tích vô hướng là:&lt;/p&gt;

\[e=(0.9,\ 0.2,\ 1.1).\]

&lt;p&gt;Chuẩn hóa qua softmax (làm tròn hai chữ số thập phân):&lt;/p&gt;

\[\alpha \approx (0.37,\ 0.18,\ 0.45).\]

&lt;p&gt;Vectơ ngữ cảnh thu được:&lt;/p&gt;

\[\mathbf{c}\approx 0.37\begin{bmatrix}1\\0\end{bmatrix}
+0.18\begin{bmatrix}0\\1\end{bmatrix}
+0.45\begin{bmatrix}1\\1\end{bmatrix}
=\begin{bmatrix}0.82\\0.63\end{bmatrix}.\]

&lt;p&gt;Trọng số tập trung nhiều nhất vào &lt;em&gt;“ML”&lt;/em&gt; nhưng &lt;em&gt;“I”&lt;/em&gt; và &lt;em&gt;“love”&lt;/em&gt; vẫn đóng góp theo tỷ lệ tương ứng — thể hiện đúng bản chất căn chỉnh mềm.&lt;/p&gt;

&lt;h3 id=&quot;32-self-attention-như-phép-trộn-phụ-thuộc-dữ-liệu&quot;&gt;3.2 Self-attention như phép trộn phụ thuộc dữ liệu&lt;/h3&gt;

&lt;p&gt;Trong self-attention, \(\mathbf{A}\in\mathbb{R}^{L\times L}\) là một ma trận ngẫu nhiên theo hàng (&lt;em&gt;row-stochastic&lt;/em&gt;, tổng mỗi hàng bằng 1). Ánh xạ:&lt;/p&gt;

\[\mathbf{X}\mapsto \mathbf{A}\mathbf{V}\]

&lt;p&gt;là tổ hợp tuyến tính của các vectơ value, nhưng chính ma trận trọng số \(\mathbf{A}\) lại phụ thuộc phi tuyến vào dữ liệu đầu vào \(\mathbf{X}\) thông qua các phép chiếu QKV và softmax. Tính thích nghi theo dữ liệu này giúp attention linh hoạt hơn bộ lọc tích chập có trọng số cố định.&lt;/p&gt;

&lt;h3 id=&quot;33-vai-trò-chuyên-biệt-của-nhiều-head&quot;&gt;3.3 Vai trò chuyên biệt của nhiều head&lt;/h3&gt;

&lt;p&gt;Hãy hình dung hai head đảm nhiệm hai khía cạnh độc lập: head 1 chú ý các token lân cận, còn head 2 theo dõi quan hệ đồng tham chiếu xa. Phép nối (concat) giữ trọn cả hai kênh tín hiệu ở các lát đặc trưng khác nhau, sau đó ma trận \(\mathbf{W}^O\) kết hợp chúng lại — điều mà một head đơn lẻ khó thực hiện đồng thời mà không phải đánh đổi.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-đoạn-mã-minh-họa-toán-học&quot;&gt;4. Đoạn mã minh họa toán học&lt;/h2&gt;

&lt;p&gt;Đoạn mã ngắn dưới đây phản ánh trực tiếp các phương trình vừa trình bày; các ví dụ cài đặt đầy đủ hơn nằm ở phần tiếp theo.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;attention_math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Q: (Lq, dk), K: (Lk, dk), V: (Lk, dv)
    mask: (Lq, Lk) với True = cấm
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;S&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;S&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Causal self-attention trên đặc trưng ngẫu nhiên
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;causal&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;attention_math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;causal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;atol&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# không có khối lượng tương lai
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Làm trơn nhân (Kernel smoothing / ước lượng Nadaraya–Watson)&lt;/strong&gt;: có thể xem attention như bộ ước lượng nhân có tham số học được trên tập các value.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bộ nhớ truy xuất theo nội dung&lt;/strong&gt;: keys đóng vai trò địa chỉ nội dung, queries là khóa tra cứu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Truyền tin trên đồ thị (Message passing)&lt;/strong&gt;: self-attention tương đương truyền tin trên đồ thị đầy đủ với trọng số cạnh phụ thuộc dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập&lt;/strong&gt;: đối lập giữa bộ lọc cục bộ có trọng số cố định và cơ chế tổng hợp toàn cục có trọng số động.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Attention thưa / tuyến tính&lt;/strong&gt;: các phương pháp xấp xỉ nhằm giảm độ phức tạp khi chi phí \(O(L^2)\) quá lớn.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Bahdanau et al., 2015 — Align and Translate&lt;/a&gt; — attention cộng tính cho dịch máy neuron.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Luong et al., 2015 — Effective Approaches…&lt;/a&gt; — hàm chấm điểm nhân tính, attention cục bộ và toàn cục.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Vaswani et al., 2017 — Attention Is All You Need&lt;/a&gt; — scaled dot-product multi-head self-attention.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1803.02155&quot;&gt;Shaw et al., 2018 — Relative Position Representations&lt;/a&gt; — bổ sung thông tin khoảng cách tương đối vào điểm số attention.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2006.16236&quot;&gt;Katharopoulos et al., 2020 — Transformers are RNNs&lt;/a&gt; — biến thể attention có độ phức tạp tuyến tính (đọc thêm nâng cao).&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-cạm-bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;7. Cạm bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Nhầm trục \(L_q\) và \(L_k\)&lt;/strong&gt; khi xây dựng ma trận mask.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp mask sau softmax&lt;/strong&gt;, gây sai lệch chuẩn hóa xác suất và sai gradient.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bỏ qua hệ số chia \(\sqrt{d_k}\)&lt;/strong&gt; khi số chiều lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giả định nhầm \(\mathbf{A}\) là ma trận đối xứng&lt;/strong&gt; trong self-attention; thực tế mỗi hàng là một phân phối xác suất chuẩn hóa theo key nên nhìn chung \(\mathbf{A} \neq \mathbf{A}^\top\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mẹo kiểm thử:&lt;/strong&gt; kiểm tra causal attention bằng điều kiện &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;triu(A, 1) ≈ 0&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mẹo kiểm thử multi-head:&lt;/strong&gt; viết unit-test cho bước reshape trên một tensor nhỏ biết trước giá trị để chắc chắn không bị xáo trộn chiều.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-tóm-tắt-các-điểm-chính&quot;&gt;8. Tóm tắt các điểm chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Attention luôn theo khung &lt;strong&gt;điểm số → softmax → tổng có trọng số các value&lt;/strong&gt;; các biến thể chỉ khác nhau ở hàm chấm điểm, nguồn QKV và mask.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chia tỉ lệ theo \(\sqrt{d_k}\)&lt;/strong&gt; kiểm soát phương sai của tích vô hướng ở chiều cao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dạng ma trận&lt;/strong&gt; \(\mathrm{softmax}(QK^\top/\sqrt{d_k})V\) là chuẩn tính toán hiệu quả trên phần cứng hiện đại.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Self-attention&lt;/strong&gt; đạt độ dài đường truyền \(O(1)\) nhưng có độ phức tạp bộ nhớ và tính toán \(O(L^2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multi-head&lt;/strong&gt; kết hợp song song nhiều phân phối chú ý rồi trộn đầu ra qua \(\mathbf{W}^O\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Masking&lt;/strong&gt; phải tác động lên điểm số trước softmax, không xử lý hậu kỳ trên trọng số.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Tiếp theo, ta sẽ chuyển các phương trình này thành mã nguồn thực thi trong bài &lt;strong&gt;07-02-02&lt;/strong&gt;, bắt đầu từ các module attention cốt lõi.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến); các đường dẫn dưới đây được lưu lại để tra cứu và ghi nhận nguồn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1467113421464723&quot;&gt;LLM Tập 4: Attention Mechanism (Q–K–V, quan hệ kết nối toàn phần)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1806844676942638&quot;&gt;Công thức Attention: tự tay tính Q, K, V&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1007473105556936&quot;&gt;Attention trong Transformer (Self, Masked, Cross, Multi-Head)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown (tiếng Anh). Dẫn giải chi tiết nguồn gốc công thức \(\mathrm{softmax}(QK^\top / \sqrt{d})\,V\) thay vì chỉ nêu kết quả.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PSs6nxngL6k&quot;&gt;Attention for Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Ví dụ số nhỏ minh họa cùng phép tính tổng có trọng số.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mmzRYGCfTzc&quot;&gt;A Dive Into Multihead Attention, Self-Attention and Cross-Attention&lt;/a&gt; — Machine Learning Studio (tiếng Anh). Giải thích cách mở rộng từ một công thức attention đơn thành nhiều head song song.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-02 Cơ chế Chú ý Đi sâu</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_01_Attention_Mechanisms/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_01_Attention_Mechanisms</id>
   <content type="html">&lt;p&gt;Nếu bài học trước cho bạn thấy động lực ra đời của Attention trong bài toán dịch máy Seq2Seq, thì phần đi sâu này sẽ nâng Attention lên thành một &lt;strong&gt;phép toán tensor tổng quát&lt;/strong&gt; có thể đứng độc lập mà không cần RNN. Đây chính là bước chuyển hóa biến Attention từ một “phụ kiện” gắn kèm LSTM trở thành trái tim của toàn bộ kiến trúc Transformer.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-khi-đi-sâu-vào-cơ-chế-chú-ý&quot;&gt;Kiến thức cần nhớ: Ba trụ cột khi đi sâu vào Cơ chế Chú ý&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Toán học của Scaled Dot-Product Attention và lập luận phương sai&lt;/strong&gt;:
Hiểu chính xác tại sao phải chia tích vô hướng \(Q K^T\) cho \(\sqrt{d_k}\) trước khi đưa qua &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softmax&lt;/code&gt;, và cách viết toàn bộ phép tính gọn gàng thành một tích ma trận theo batch.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mở rộng sang Multi-Head Attention (MHA)&lt;/strong&gt;:
Tách không gian \(d_{\text{model}}\) thành \(H\) đầu chú ý độc lập kích thước \(d_k = d_{\text{model}} / H\) để mô hình đồng thời theo dõi nhiều loại quan hệ khác nhau (cú pháp, tham chiếu đại từ, ngữ nghĩa).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt chuẩn xác và tránh lỗi mặt nạ (Masking)&lt;/strong&gt;:
Nắm vững kỹ thuật che bằng \(-\infty\) (trước softmax, không phải nhân 0 sau softmax) cho cả &lt;strong&gt;padding mask&lt;/strong&gt; lẫn &lt;strong&gt;causal mask&lt;/strong&gt;, cùng kiểm chứng hình dạng tensor 4D &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, H, L, d_k)&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-sự-bùng-nổ-phương-sai-khi-không-chia-cho-sqrtd_k&quot;&gt;Giải thích: Tính tay sự bùng nổ phương sai khi KHÔNG chia cho \(\sqrt{d_k}\)&lt;/h3&gt;

&lt;p&gt;Giả sử các phần tử của \(\mathbf{q}, \mathbf{k} \in \mathbb{R}^{d_k}\) độc lập, có trung bình \(0\) và phương sai \(1\). Khi đó tích vô hướng \(s = \sum_{i=1}^{d_k} q_i k_i\) có phương sai bằng đúng \(d_k\) (độ lệch chuẩn \(\sigma = \sqrt{d_k}\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Chiều \(d_k\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Độ lệch chuẩn \(\sigma\) của \(s = \mathbf{q}\cdot\mathbf{k}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Độ lệch chuẩn sau khi chia \(\sqrt{d_k}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Tác động lên Softmax&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(d_k = 4\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(1\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Ổn định&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(d_k = 64\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(8\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(1\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Nếu không chia: điểm số trải từ \(-16\) đến \(+16 \Rightarrow e^{16} \approx 8{,}9 \times 10^6\), softmax bão hòa gần 1-hot!&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(d_k = 512\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(22{,}6\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(1\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Nếu không chia: gradient của softmax co về gần \(0\), mạng ngừng học&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chia cho \(\sqrt{d_k}\) đưa phương sai của điểm chú ý về lại đúng &lt;strong&gt;\(1\)&lt;/strong&gt; ở mọi kích thước mô hình!&lt;/p&gt;

&lt;h1 id=&quot;07-02-cơ-chế-chú-ý-đi-sâu&quot;&gt;07-02 Cơ chế Chú ý Đi sâu&lt;/h1&gt;

&lt;p&gt;Phần này mở rộng sâu hơn so với bài cơ sở (07-01). Sau khi đã hiểu lý do tồn tại của attention và các công thức nền tảng, ta sẽ hệ thống hóa chặt chẽ phần toán học rồi cài đặt đầy đủ từng thành phần.&lt;/p&gt;

&lt;h2 id=&quot;nội-dung-chính&quot;&gt;Nội dung chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Toán học Attention&lt;/strong&gt;&lt;br /&gt;
Thống nhất các hàm chấm điểm, dạng ma trận QKV theo batch, self-attention như phép tương tác \(L\times L\), đại số multi-head, lý thuyết padding/causal mask trước softmax, độ phức tạp tính toán và lập luận về độ dài đường truyền thông tin.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Cài đặt Attention&lt;/strong&gt;&lt;br /&gt;
Cài đặt từ đầu attention Bahdanau và scaled dot-product attention, xây dựng module multi-head, minh họa masking, phác thảo mô hình seq2seq có attention, điểm qua các bài báo nền tảng và các lỗi thường gặp trong thực tế.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;lộ-trình-đọc&quot;&gt;Lộ trình đọc&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Thứ tự&lt;/th&gt;
      &lt;th&gt;Bài&lt;/th&gt;
      &lt;th&gt;Mục tiêu đạt được&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;07-02-01 Toán học Attention&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Nắm chắc và tự viết lại được toàn bộ các công thức cốt lõi&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;07-02-02 Cài đặt&lt;/strong&gt; (tổng quan)&lt;/td&gt;
      &lt;td&gt;Đối chiếu từ công thức toán sang cấu trúc các module mã nguồn&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;07-02-02-01 Cài đặt cốt lõi&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Chạy và kiểm chứng được mã nguồn Bahdanau và self-attention&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;07-02-02-02 Multi-Head, Papers, Cạm bẫy&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Nắm vững multi-head, causal mask, tài liệu nền tảng và quy trình gỡ lỗi&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Nếu một biểu thức trong bài &lt;strong&gt;07-02-01&lt;/strong&gt; còn trừu tượng, bạn có thể xem trước đoạn mã minh họa tương ứng ở &lt;strong&gt;07-02-02-01&lt;/strong&gt; rồi quay lại đối chiếu.&lt;/p&gt;

&lt;h2 id=&quot;liên-kết-trong-khóa-học&quot;&gt;Liên kết trong khóa học&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem lại bài 07-01&lt;/strong&gt; nếu cần ôn lại trực giác và bối cảnh lịch sử của attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tiếp nối sang Chương 08 (Transformer)&lt;/strong&gt; để kết hợp self-attention với mạng feed-forward, kết nối phần dư và mã hóa vị trí.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Khi đã sẵn sàng, hãy bắt đầu với bài &lt;strong&gt;Toán học Attention&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown (tiếng Anh). Trình bày chi tiết scaled dot-product attention, trọng tâm của phần đi sâu này.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PSs6nxngL6k&quot;&gt;Attention for Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Minh họa dạng attention cho mô hình chuỗi để đối chiếu với self-attention.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mmzRYGCfTzc&quot;&gt;A Dive Into Multihead Attention, Self-Attention and Cross-Attention&lt;/a&gt; — Machine Learning Studio (tiếng Anh). Phân tách rõ ba dạng multi-head, self-attention và cross-attention đúng theo cấu trúc phần này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-01 Cơ sở về Cơ chế Chú ý</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_01_Attention_Basics/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_01_Attention_Basics</id>
   <content type="html">&lt;p&gt;Năm 2014, Dzmitry Bahdanau, Kyunghyun Cho và Yoshua Bengio công bố bài báo dịch máy thần kinh kinh điển với một phát hiện làm thay đổi toàn bộ NLP: ngay khi cho phép bộ giải mã tự tính trọng số chú ý lên mọi trạng thái ẩn của bộ mã hóa, điểm BLEU trên các câu dài trên 30 từ không còn lao dốc thảm hại nữa — và đẹp hơn cả, khi vẽ ma trận trọng số \(\alpha_{ti}\) lên biểu đồ nhiệt, mô hình đã tự học được &lt;strong&gt;bảng gióng hàng (alignment)&lt;/strong&gt; giữa hai ngôn ngữ mà chưa từng được dạy ngữ pháp!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-mảnh-ghép-nền-tảng-của-attention-trong-seq2seq&quot;&gt;Kiến thức cần nhớ: Bốn mảnh ghép nền tảng của Attention trong Seq2Seq&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nút thắt thông tin trong Encoder–Decoder cổ điển&lt;/strong&gt;:
Dù câu nguồn dài 5 từ hay 80 từ, Seq2Seq truyền thống buộc phải nén toàn bộ vào một vector \(h_T \in \mathbb{R}^{d}\) cố định — thông tin ở đầu câu bị ghi đè dần khi câu dài ra.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bahdanau Attention (Additive / Concat Attention, 2015)&lt;/strong&gt;:
Tính điểm khớp bằng một mạng MLP 1 tầng ẩn: \(e_{ti} = v_a^T \tanh(W_a s_{t-1} + U_a h_i)\), kết hợp trạng thái giải mã trước đó \(s_{t-1}\) với từng trạng thái mã hóa \(h_i\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Luong Attention (Multiplicative / Dot-Product Attention, 2015)&lt;/strong&gt;:
Thay MLP cộng tính bằng phép nhân trực tiếp \(e_{ti} = s_t^T W_a h_i\) (hoặc \(s_t^T h_i\)), tận dụng phép nhân ma trận siêu nhanh trên GPU và đặt nền móng trực tiếp cho Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính diễn giải qua bản đồ gióng hàng (Alignment Heatmap)&lt;/strong&gt;:
Hàng \(t\) của ma trận \(\alpha\) cho biết khi sinh từ đích thứ \(t\), mô hình đang “nhìn” vào những từ nguồn nào — thậm chí xử lý mượt mà hiện tượng đảo trật tự từ giữa tiếng Anh (&lt;em&gt;“white house”&lt;/em&gt;) và tiếng Việt (&lt;em&gt;“nhà trắng”&lt;/em&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-1-bước-bahdanau-additive-attention&quot;&gt;Giải thích: Tính tay 1 bước Bahdanau Additive Attention&lt;/h3&gt;

&lt;p&gt;Giả sử câu nguồn có 2 từ với trạng thái encoder vô hướng \(h_1 = 1{,}0, \; h_2 = -0{,}5\), trạng thái decoder hiện tại \(s_{t-1} = 0{,}5\), và tham số học được \(W_a = 1{,}0, \; U_a = 1{,}0, \; v_a = 2{,}0\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính điểm năng lượng \(e_{t,i} = v_a \tanh(W_a s_{t-1} + U_a h_i)\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Với từ 1: \(e_{t,1} = 2{,}0 \cdot \tanh(0{,}5 + 1{,}0) = 2{,}0 \cdot \tanh(1{,}5) \approx 2{,}0 \times 0{,}905 = \mathbf{1{,}810}\)&lt;/li&gt;
      &lt;li&gt;Với từ 2: \(e_{t,2} = 2{,}0 \cdot \tanh(0{,}5 - 0{,}5) = 2{,}0 \cdot \tanh(0) = \mathbf{0{,}000}\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa Softmax&lt;/strong&gt;:
\(e^{1{,}810} \approx 6{,}110, \quad e^{0} = 1{,}000 \implies \alpha_{t,1} = \frac{6{,}110}{7{,}110} \approx \mathbf{0{,}859}, \quad \alpha_{t,2} \approx \mathbf{0{,}141}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng hợp vector ngữ cảnh \(c_t\)&lt;/strong&gt;:
\(c_t = 0{,}859(1{,}0) + 0{,}141(-0{,}5) = 0{,}859 - 0{,}0705 = \mathbf{0{,}7885}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Ở bước này, decoder tập trung tới &lt;strong&gt;85,9%&lt;/strong&gt; sự chú ý vào từ nguồn thứ nhất để sinh từ tiếp theo.&lt;/p&gt;

&lt;h1 id=&quot;cơ-sở-về-cơ-chế-chú-ý&quot;&gt;Cơ sở về Cơ chế Chú ý&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/multihead_attention.png&quot; alt=&quot;Multi-Head Attention&quot; /&gt;
&lt;em&gt;Sơ đồ multi-head attention được sử dụng trong Transformer. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Cơ chế chú ý&lt;/strong&gt; (&lt;em&gt;attention&lt;/em&gt;) cho phép mô hình &lt;em&gt;tập trung động&lt;/em&gt; vào những phần phù hợp nhất của đầu vào khi sinh từng phần đầu ra. Thay vì nén toàn bộ chuỗi qua một vectơ tóm tắt có kích thước cố định, attention thực hiện cơ chế &lt;strong&gt;chọn lọc mềm&lt;/strong&gt; (&lt;em&gt;soft selection&lt;/em&gt;): tại mỗi bước tính toán, mô hình gán trọng số cho các vị trí đầu vào rồi lấy tổ hợp có trọng số của các biểu diễn tương ứng.&lt;/p&gt;

&lt;p&gt;Ý tưởng này tuy gọn gàng nhưng đã giải quyết được hạn chế cấu trúc của các mô hình chuỗi thời kỳ đầu và trở thành nền tảng cho xử lý ngôn ngữ tự nhiên cũng như nhiều bài toán thị giác máy tính hiện đại.&lt;/p&gt;

&lt;h3 id=&quot;nút-thắt-thông-tin-tạo-động-lực-cho-attention&quot;&gt;Nút thắt thông tin tạo động lực cho attention&lt;/h3&gt;

&lt;p&gt;Mô hình &lt;strong&gt;encoder–decoder&lt;/strong&gt; (seq2seq) cổ điển trong dịch máy vận hành qua ba bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Encoder&lt;/strong&gt; (RNN) đọc lần lượt từng từ của câu nguồn.&lt;/li&gt;
  &lt;li&gt;Encoder nén toàn bộ câu nguồn vào một trạng thái ẩn cuối cùng có kích thước cố định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decoder&lt;/strong&gt; (RNN) nhận vectơ duy nhất đó để sinh câu đích.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Sơ đồ:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&quot;The cat sat on the mat&quot;
        │
        ▼
   [Encoder RNN]
        │
        ▼
   fixed context vector  z ∈ R^d     ← bottleneck
        │
        ▼
   [Decoder RNN] → &quot;Le chat était assis sur le tapis&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Cách thiết kế này bộc lộ hai điểm yếu rõ rệt:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nút thắt thông tin.&lt;/strong&gt; Dù câu nguồn dài 5 từ hay 50 từ, toàn bộ thông tin đều bị ép vào một vectơ \(z\) duy nhất. Với câu dài, nhiều chi tiết quan trọng dễ bị mờ nhạt hoặc thất thoát.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dùng chung một vectơ tóm tắt cho mọi từ đích.&lt;/strong&gt; Khi dịch một câu, ta không chỉ nhìn vào một bản tóm tắt cố định cho mọi từ: khi sinh &lt;em&gt;“chat”&lt;/em&gt;, ta cần chú ý tới &lt;em&gt;“cat”&lt;/em&gt;; khi sinh &lt;em&gt;“tapis”&lt;/em&gt;, ta cần chú ý tới &lt;em&gt;“mat”&lt;/em&gt;. Một vectơ \(z\) cố định không hỗ trợ khả năng &lt;em&gt;căn chỉnh động&lt;/em&gt; (&lt;em&gt;dynamic alignment&lt;/em&gt;) này.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Giải pháp của attention:&lt;/strong&gt; giữ lại &lt;em&gt;toàn bộ&lt;/em&gt; các trạng thái encoder \(\mathbf{h}_1, \ldots, \mathbf{h}_T\), và tại mỗi bước decoder \(t\), tính riêng một vectơ ngữ cảnh:&lt;/p&gt;

\[\mathbf{c}_t = \sum_{i=1}^{T} \alpha_{t,i}\,\mathbf{h}_i\]

&lt;p&gt;trong đó các trọng số \(\alpha_{t,i}\) được học từ dữ liệu và thay đổi theo trạng thái decoder hiện tại. Nhờ vậy, mỗi từ đích có thể tập trung vào các vị trí nguồn phù hợp nhất.&lt;/p&gt;

&lt;h3 id=&quot;liên-hệ-trực-quan&quot;&gt;Liên hệ trực quan&lt;/h3&gt;

&lt;p&gt;Có thể hình dung cơ chế này giống như việc trả lời câu hỏi khi đang mở sách giáo khoa trước mặt. Thay vì cố thuộc lòng cả chương thành một câu tóm tắt duy nhất rồi đóng sách lại, với mỗi ý cần viết ta sẽ tra lại đúng đoạn tương ứng. Attention chính là phiên bản khả vi và học được của thao tác tra cứu đó.&lt;/p&gt;

&lt;h3 id=&quot;nội-dung-bài-học-này&quot;&gt;Nội dung bài học này&lt;/h3&gt;

&lt;p&gt;Bài này xây dựng nền tảng khái niệm và lịch sử của attention gồm:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Attention trong encoder–decoder (Bahdanau và Luong),&lt;/li&gt;
  &lt;li&gt;Khuôn khổ Query–Key–Value,&lt;/li&gt;
  &lt;li&gt;Scaled dot-product attention,&lt;/li&gt;
  &lt;li&gt;Phân biệt self-attention và cross-attention,&lt;/li&gt;
  &lt;li&gt;Giới thiệu multi-head attention.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Các bài sau trong chương sẽ đi sâu vào toán học và cài đặt, trước khi ghép thành kiến trúc Transformer hoàn chỉnh ở Chương 8.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;h3 id=&quot;21-attention-trong-encoderdecoder-dạng-tổng-quát&quot;&gt;2.1 Attention trong encoder–decoder dạng tổng quát&lt;/h3&gt;

&lt;p&gt;Tại bước giải mã \(t\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Ký hiệu&lt;/th&gt;
      &lt;th&gt;Ý nghĩa&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\mathbf{s}_t\)&lt;/td&gt;
      &lt;td&gt;Trạng thái ẩn của decoder (thông tin phục vụ sinh từ ở bước hiện tại)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\mathbf{h}_i\)&lt;/td&gt;
      &lt;td&gt;Trạng thái ẩn của encoder tại vị trí nguồn \(i\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(e_{t,i}\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Điểm căn chỉnh&lt;/strong&gt; (&lt;em&gt;alignment score&lt;/em&gt;) chưa chuẩn hóa giữa bước decoder \(t\) và vị trí nguồn \(i\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\alpha_{t,i}\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Trọng số attention&lt;/strong&gt; biểu thị mức độ chú ý vào vị trí nguồn \(i\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\mathbf{c}_t\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Vectơ ngữ cảnh&lt;/strong&gt; (&lt;em&gt;context vector&lt;/em&gt;) tóm lược mềm câu nguồn cho bước \(t\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Bước 1 — Tính điểm số.&lt;/strong&gt; Đánh giá mức độ phù hợp giữa trạng thái decoder và từng trạng thái encoder:&lt;/p&gt;

\[e_{t,i} = \mathrm{score}(\mathbf{s}_t, \mathbf{h}_i)\]

&lt;p&gt;&lt;strong&gt;Bước 2 — Chuẩn hóa bằng softmax.&lt;/strong&gt;&lt;/p&gt;

\[\alpha_{t,i} = \frac{\exp(e_{t,i})}{\sum_{j=1}^{T}\exp(e_{t,j})}\]

&lt;p&gt;Khi đó \(\alpha_{t,i} \ge 0\) và \(\sum_i \alpha_{t,i} = 1\), tạo thành một phân phối xác suất trên các vị trí nguồn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 3 — Tổng hợp vectơ ngữ cảnh.&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{c}_t = \sum_{i=1}^{T} \alpha_{t,i}\,\mathbf{h}_i\]

&lt;p&gt;&lt;strong&gt;Bước 4 — Dự đoán đầu ra.&lt;/strong&gt; Kết hợp vectơ ngữ cảnh với trạng thái decoder để dự đoán token tiếp theo:&lt;/p&gt;

\[\tilde{\mathbf{s}}_t = \tanh\!\big(\mathbf{W}_c[\mathbf{c}_t;\mathbf{s}_t]\big), \qquad
p(y_t \mid y_{&amp;lt;t}, x) = \mathrm{softmax}(\mathbf{W}_o\tilde{\mathbf{s}}_t)\]

&lt;p&gt;Tùy bài báo, cách ghép \(\mathbf{c}_t\) và \(\mathbf{s}_t\) có thể khác nhau đôi chút, nhưng nguyên tắc chung vẫn là &lt;strong&gt;dự đoán dựa trên vectơ ngữ cảnh động \(\mathbf{c}_t\) thay vì một nút thắt cố định&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;22-attention-bahdanau-attention-cộng-tính-2015&quot;&gt;2.2 Attention Bahdanau (attention cộng tính, 2015)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Bahdanau et al.&lt;/a&gt; đề xuất hàm chấm điểm học được:&lt;/p&gt;

\[e_{t,i} = \mathbf{v}_a^\top \tanh\!\big(\mathbf{W}_a\mathbf{s}_t + \mathbf{U}_a\mathbf{h}_i\big)\]

&lt;p&gt;&lt;strong&gt;Cơ chế hoạt động:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathbf{W}_a\) và \(\mathbf{U}_a\) chiếu trạng thái decoder và encoder về cùng một không gian chung trước khi kết hợp.&lt;/li&gt;
  &lt;li&gt;Hàm \(\tanh\) tạo tính phi tuyến để đo mức độ liên quan linh hoạt hơn phép nhân vô hướng thuần túy.&lt;/li&gt;
  &lt;li&gt;Vectơ \(\mathbf{v}_a\) ánh xạ biểu diễn đó thành một điểm số vô hướng.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Kiểu này được gọi là attention &lt;strong&gt;cộng tính&lt;/strong&gt; (&lt;em&gt;additive&lt;/em&gt;) do thành phần query và key được cộng với nhau bên trong hàm \(\tanh\). Đây là dạng attention được ứng dụng rộng rãi đầu tiên trong dịch máy neuron (NMT), giúp cải thiện rõ rệt chất lượng dịch trên các câu dài.&lt;/p&gt;

&lt;h3 id=&quot;23-attention-luong-dạng-nhân-và-tổng-quát-2015&quot;&gt;2.3 Attention Luong (dạng nhân và tổng quát, 2015)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Luong et al.&lt;/a&gt; khảo sát các hàm chấm điểm gọn hơn và nhanh hơn trong thực tế:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tích vô hướng&lt;/strong&gt; (&lt;em&gt;dot product&lt;/em&gt;):&lt;/p&gt;

\[e_{t,i} = \mathbf{s}_t^\top \mathbf{h}_i\]

&lt;p&gt;&lt;strong&gt;Dạng tổng quát / song tuyến&lt;/strong&gt; (&lt;em&gt;general / bilinear&lt;/em&gt;):&lt;/p&gt;

\[e_{t,i} = \mathbf{s}_t^\top \mathbf{W}_a \mathbf{h}_i\]

&lt;p&gt;&lt;strong&gt;Dạng ghép nối (&lt;em&gt;concat&lt;/em&gt;)&lt;/strong&gt; (tương tự Bahdanau):&lt;/p&gt;

\[e_{t,i} = \mathbf{v}_a^\top \tanh\!\big(\mathbf{W}_a[\mathbf{s}_t;\mathbf{h}_i]\big)\]

&lt;p&gt;Tích vô hướng đo độ tương đồng hướng giữa hai vectơ: khi trạng thái decoder và trạng thái encoder cùng hướng, điểm số sẽ cao. Dạng song tuyến chèn thêm ma trận học được \(\mathbf{W}_a\) để linh hoạt hơn khi \(\mathbf{s}_t\) và \(\mathbf{h}_i\) không nằm trong cùng không gian biểu diễn.&lt;/p&gt;

&lt;h3 id=&quot;24-khuôn-khổ-querykeyvalue-q-k-v&quot;&gt;2.4 Khuôn khổ Query–Key–Value (Q, K, V)&lt;/h3&gt;

&lt;p&gt;Trong các kiến trúc hiện đại, attention được chuẩn hóa theo ba vai trò:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Vai trò&lt;/th&gt;
      &lt;th&gt;Câu hỏi tương ứng&lt;/th&gt;
      &lt;th&gt;Nguồn thường gặp&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Query&lt;/strong&gt; \(\mathbf{q}\)&lt;/td&gt;
      &lt;td&gt;“Hiện tại đang cần tìm thông tin gì?”&lt;/td&gt;
      &lt;td&gt;Trạng thái decoder, hoặc vị trí \(i\) trong self-attention&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Key&lt;/strong&gt; \(\mathbf{k}_j\)&lt;/td&gt;
      &lt;td&gt;“Vị trí \(j\) có đặc trưng gì để đối chiếu?”&lt;/td&gt;
      &lt;td&gt;Trạng thái encoder, hoặc mọi vị trí trong chuỗi&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Value&lt;/strong&gt; \(\mathbf{v}_j\)&lt;/td&gt;
      &lt;td&gt;“Nếu vị trí \(j\) khớp, cần lấy nội dung gì?”&lt;/td&gt;
      &lt;td&gt;Cùng nguồn với keys, qua ma trận chiếu riêng&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Quy trình chung gồm ba bước: (1) tính điểm giữa query và các keys, (2) chuẩn hóa bằng softmax thành trọng số, (3) tính tổng có trọng số của các values. Cách biểu diễn này bao quát cả &lt;strong&gt;cross-attention&lt;/strong&gt; (query từ một chuỗi, key/value từ chuỗi khác) lẫn &lt;strong&gt;self-attention&lt;/strong&gt; (cả ba đều xuất phát từ cùng một chuỗi).&lt;/p&gt;

&lt;p&gt;Trong các mô hình ngôn ngữ lớn (LLM), quy trình này thường được nhìn như một &lt;em&gt;mạng quan hệ kết nối toàn phần&lt;/em&gt;: embedding đầu vào → chiếu sang Q/K/V → tính điểm attention → chuẩn hóa Softmax → (nhiều head song song) → tổng hợp ngữ cảnh đầu ra.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/llm_attn_qkv_pipeline_active.jpg&quot; alt=&quot;Pipeline attention kiểu LLM&quot; /&gt;
&lt;em&gt;Hình: Luồng xử lý Q–K–V → Softmax → multi-head → tổng hợp ngữ cảnh. (Minh họa từ video LLM Attention Mechanism)&lt;/em&gt;&lt;/p&gt;

&lt;h4 id=&quot;ví-dụ-số-minh-họa-câu-3-token--q-k-v&quot;&gt;Ví dụ số minh họa: Câu 3 token → Q, K, V&lt;/h4&gt;

&lt;p&gt;Xét một câu ví dụ gồm 3 từ (“tôi / yêu / bạn”), mỗi từ biểu diễn bằng vectơ embedding 2 chiều để dễ quan sát (trong thực tế thường dùng \(d_{\mathrm{model}}=512\)):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_toy_sentence_embeddings.jpg&quot; alt=&quot;Embedding 3 từ&quot; /&gt;
&lt;em&gt;Hình: Ma trận đầu vào \(\mathbf{X}\) kích thước 3 token × \(d\). (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Ba ma trận trọng số học được \(W^Q, W^K, W^V\) chiếu \(\mathbf{X}\) sang ba không gian query, key và value:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_weights_wq_wk_wv.jpg&quot; alt=&quot;W^Q, W^K, W^V&quot; /&gt;
&lt;em&gt;Hình: Ba ma trận chiếu riêng biệt cho Q, K và V. (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_project_x_to_qkv.jpg&quot; alt=&quot;X × W → Q, K, V&quot; /&gt;
&lt;em&gt;Hình: Phép chiếu \(\mathbf{Q}=\mathbf{X}W^Q\), \(\mathbf{K}=\mathbf{X}W^K\), \(\mathbf{V}=\mathbf{X}W^V\). (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;25-scaled-dot-product-attention&quot;&gt;2.5 Scaled dot-product attention&lt;/h3&gt;

&lt;p&gt;Phép tính attention tiêu chuẩn trong Transformer là:&lt;/p&gt;

\[\mathrm{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V})
= \mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_matrices_and_formula.jpg&quot; alt=&quot;Q, K, V và công thức Attention&quot; /&gt;
&lt;em&gt;Hình: Ba ma trận Q, K, V sau phép chiếu cùng công thức scaled dot-product attention. (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Với một chuỗi đơn (tạm bỏ chiều batch), kích thước các ma trận như sau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
\[\mathbf{Q} \in \mathbb{R}^{L_q \times d_k}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbf{K} \in \mathbb{R}^{L_k \times d_k}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbf{V} \in \mathbb{R}^{L_k \times d_v}\]
  &lt;/li&gt;
  &lt;li&gt;Đầu ra \(\in \mathbb{R}^{L_q \times d_v}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Các bước tính trên ví dụ 3 từ:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tích vô hướng&lt;/strong&gt;: nhân từng hàng của \(Q\) với từng cột của \(K^\top\) để thu điểm tương đồng giữa mọi cặp từ:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_dot_product_row_example.jpg&quot; alt=&quot;Tính từng phần tử QK^T&quot; /&gt;
&lt;em&gt;Hình: Ví dụ hàng “tôi” tính tích vô hướng với tất cả các key. (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_unscaled_similarities.jpg&quot; alt=&quot;Ma trận similarity chưa scale&quot; /&gt;
&lt;em&gt;Hình: Ma trận độ tương đồng chưa chia tỉ lệ \(\mathbf{Q}K^\top\). (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chia tỉ lệ (scaling)&lt;/strong&gt;: chia cho \(\sqrt{d_k}\) (trong ví dụ này \(d_k=2\) nên chia cho \(\sqrt{2}\)):&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_scale_by_sqrt_dk.jpg&quot; alt=&quot;Chia √d_k&quot; /&gt;
&lt;em&gt;Hình: Chuyển từ độ tương đồng chưa chia tỉ lệ sang đã chia tỉ lệ. (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vì sao cần chia cho \(\sqrt{d_k}\)?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Nếu các thành phần của query và key gần như độc lập với trung bình 0 và phương sai 1, tích vô hướng \(\mathbf{q}^\top \mathbf{k}\) sẽ có phương sai bằng \(d_k\). Khi \(d_k\) lớn (ví dụ 64 đến 512), độ lớn điểm số tăng mạnh khiến softmax rơi vào vùng bão hòa (gần giống one-hot) và làm gradient suy giảm gần về 0. Chia cho \(\sqrt{d_k}\) đưa phương sai về khoảng 1 để mô hình học được phân phối trọng số mềm và ổn định hơn.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Softmax theo hàng&lt;/strong&gt;: chuẩn hóa từng hàng thành một phân phối xác suất trên các keys:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_softmax_over_rows.jpg&quot; alt=&quot;Softmax theo hàng&quot; /&gt;
&lt;em&gt;Hình: Áp dụng softmax dọc theo từng hàng của ma trận điểm số. (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_attention_weights.jpg&quot; alt=&quot;Attention weights&quot; /&gt;
&lt;em&gt;Hình: Ma trận trọng số attention với tổng mỗi hàng bằng 1. (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nhân với V&lt;/strong&gt;: lấy tổ hợp có trọng số của các hàng trong \(V\) để thu đầu ra attention:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_weights_times_v.jpg&quot; alt=&quot;Weights × V&quot; /&gt;
&lt;em&gt;Hình: Nhân ma trận trọng số attention với V để tạo đầu ra. (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;26-self-attention-so-với-cross-attention&quot;&gt;2.6 Self-attention so với cross-attention&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Cross-attention (attention encoder–decoder).&lt;/strong&gt;&lt;br /&gt;
Query đến từ decoder, còn key và value đến từ encoder. Đây là mô hình chú ý trong dịch máy gốc: khi sinh một từ đích, mô hình tra cứu xem những từ nguồn nào liên quan nhất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Self-attention.&lt;/strong&gt;&lt;br /&gt;
Query, key và value đều được chiếu từ &lt;em&gt;cùng một&lt;/em&gt; chuỗi đầu vào, cho phép mọi vị trí thu thập ngữ cảnh từ tất cả các vị trí khác:&lt;/p&gt;

\[\mathbf{Q} = \mathbf{X}\mathbf{W}^Q,\quad
\mathbf{K} = \mathbf{X}\mathbf{W}^K,\quad
\mathbf{V} = \mathbf{X}\mathbf{W}^V\]

&lt;p&gt;Mỗi token ban đầu là một vectơ nhúng, sau đó sinh ra bộ Q, K, V riêng:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_tokens_as_vectors.jpg&quot; alt=&quot;Token = cột số&quot; /&gt;
&lt;em&gt;Hình: Biểu diễn câu dưới dạng các vectơ embedding. (Minh họa từ video Transformer / Self-Attention nhập môn)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_per_token_qkv_columns.jpg&quot; alt=&quot;Mỗi từ một cột Q/K/V&quot; /&gt;
&lt;em&gt;Hình: Self-attention tạo bộ Q, K, V riêng cho từng vị trí trong câu. (Minh họa từ video Transformer / Self-Attention nhập môn)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_qkv_roles_apple_phone_orange.jpg&quot; alt=&quot;Vai trò Q/K/V theo từ&quot; /&gt;
&lt;em&gt;Hình: Quy trình QKV áp dụng cho các từ “táo / điện thoại / cam” nhằm đối chiếu ngữ cảnh và tổng hợp giá trị. (Minh họa từ video Transformer / Self-Attention nhập môn)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Ví dụ, trong câu:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The animal didn’t cross the street because &lt;strong&gt;it&lt;/strong&gt; was too tired.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Self-attention có thể học liên kết trực tiếp giữa &lt;em&gt;“it”&lt;/em&gt; và &lt;em&gt;“animal”&lt;/em&gt; mà không cần truyền tín hiệu qua nhiều bước hồi quy trung gian.&lt;/p&gt;

&lt;h3 id=&quot;27-multi-head-attention-mức-nhập-môn&quot;&gt;2.7 Multi-head attention (mức nhập môn)&lt;/h3&gt;

&lt;p&gt;Một đầu chú ý (&lt;em&gt;attention head&lt;/em&gt;) thường chỉ tập trung vào một kiểu quan hệ nhất định, trong khi ngôn ngữ chứa đồng thời nhiều loại quan hệ như cú pháp, đồng tham chiếu, lân cận hay ngữ nghĩa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Multi-head attention&lt;/strong&gt; thực hiện song song \(H\) phép attention trên các không gian chiếu độc lập, sau đó ghép kết quả lại và chiếu qua ma trận đầu ra:&lt;/p&gt;

\[\mathrm{head}_h = \mathrm{Attention}(\mathbf{Q}\mathbf{W}_h^Q, \mathbf{K}\mathbf{W}_h^K, \mathbf{V}\mathbf{W}_h^V)\]

\[\mathrm{MultiHead}(\mathbf{Q},\mathbf{K},\mathbf{V})
= \mathrm{Concat}(\mathrm{head}_1,\ldots,\mathrm{head}_H)\,\mathbf{W}^O\]

&lt;p&gt;Thông thường ta chọn \(d_k = d_v = d_{\mathrm{model}} / H\) để tổng chi phí tính toán tương đương một head đầy đủ nhưng khả năng biểu diễn đa dạng hơn. Chẳng hạn với \(d_{\mathrm{model}}=512\) và \(H=8\), mỗi head làm việc với \(d_k=64\):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_multihead_dk_split.jpg&quot; alt=&quot;Chia d_model cho số head&quot; /&gt;
&lt;em&gt;Hình: Chia đều \(512/8=64\) chiều Q/K/V cho mỗi head. (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_multihead_output_stack.jpg&quot; alt=&quot;Stack đầu ra multi-head&quot; /&gt;
&lt;em&gt;Hình: Ghép 8 head kích thước (L × 64) thành ma trận (L × 512). (Minh họa từ video công thức Attention QKV)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;28-masking-mặt-nạ-chú-ý&quot;&gt;2.8 Masking (mặt nạ chú ý)&lt;/h3&gt;

&lt;p&gt;Hai loại mặt nạ thường dùng trong thực tế là:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Padding mask.&lt;/strong&gt; Khi gộp nhiều chuỗi có độ dài khác nhau vào một batch, các chuỗi ngắn hơn được đệm thêm token &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PAD&lt;/code&gt;. Để mô hình không chú ý vào các vị trí đệm, ta cộng một số âm rất lớn (hoặc \(-\infty\)) vào điểm số của chúng trước softmax để trọng số đầu ra tiến về 0.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Causal (look-ahead) mask.&lt;/strong&gt; Trong bài toán sinh tự hồi quy (mô hình ngôn ngữ, decoder của Transformer), vị trí \(i\) chỉ được phép nhìn các vị trí từ \(i\) trở về trước và bị cấm nhìn các vị trí tương lai \(j &amp;gt; i\). Ta dùng mặt nạ tam giác trên để thực thi ràng buộc này.&lt;/p&gt;

&lt;p&gt;Nếu thiếu mặt nạ phù hợp, mô hình có thể rò rỉ thông tin từ tương lai khi huấn luyện hoặc phân bổ trọng số vô nghĩa vào các vị trí đệm.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;h3 id=&quot;31-căn-chỉnh-mềm-trong-dịch-máy&quot;&gt;3.1 Căn chỉnh mềm trong dịch máy&lt;/h3&gt;

&lt;p&gt;Xét câu nguồn &lt;strong&gt;I love deep learning&lt;/strong&gt; (4 token) và bước giải mã đang sinh từ tiếng Pháp &lt;strong&gt;apprentissage&lt;/strong&gt; (&lt;em&gt;“learning”&lt;/em&gt;). Giả sử truy vấn từ decoder cho ra các điểm số sau:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Token nguồn&lt;/th&gt;
      &lt;th&gt;Điểm thô \(e\)&lt;/th&gt;
      &lt;th&gt;Sau softmax \(\alpha\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;I&lt;/td&gt;
      &lt;td&gt;0.2&lt;/td&gt;
      &lt;td&gt;0.05&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;love&lt;/td&gt;
      &lt;td&gt;0.5&lt;/td&gt;
      &lt;td&gt;0.07&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;deep&lt;/td&gt;
      &lt;td&gt;1.5&lt;/td&gt;
      &lt;td&gt;0.19&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;learning&lt;/td&gt;
      &lt;td&gt;2.8&lt;/td&gt;
      &lt;td&gt;0.69&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Vectơ ngữ cảnh thu được tập trung chủ yếu vào &lt;em&gt;“learning”&lt;/em&gt; kèm một phần đóng góp từ &lt;em&gt;“deep”&lt;/em&gt;. Khi chuyển sang sinh từ đích khác (như &lt;em&gt;“J’aime”&lt;/em&gt; tương ứng &lt;em&gt;“I love”&lt;/em&gt;), trọng số sẽ dịch chuyển sang hai từ &lt;em&gt;“I”&lt;/em&gt; và &lt;em&gt;“love”&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;32-self-attention-như-cơ-chế-ngữ-cảnh-hóa&quot;&gt;3.2 Self-attention như cơ chế ngữ cảnh hóa&lt;/h3&gt;

&lt;p&gt;Xét ba token với các vectơ value 2 chiều minh họa:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Token&lt;/th&gt;
      &lt;th&gt;Vectơ value&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The&lt;/td&gt;
      &lt;td&gt;\((1, 0)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;cat&lt;/td&gt;
      &lt;td&gt;\((0, 1)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;sat&lt;/td&gt;
      &lt;td&gt;\((1, 1)\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Nếu &lt;em&gt;“sat”&lt;/em&gt; gán trọng số \([0.1, 0.6, 0.3]\) cho ba vị trí &lt;em&gt;(The, cat, sat)&lt;/em&gt;, biểu diễn mới của nó là:&lt;/p&gt;

\[0.1(1,0) + 0.6(0,1) + 0.3(1,1) = (0.4,\ 0.9)\]

&lt;p&gt;Biểu diễn của &lt;em&gt;“sat”&lt;/em&gt; lúc này đã tích hợp thông tin từ ngữ cảnh xung quanh (đặc biệt là &lt;em&gt;“cat”&lt;/em&gt;). Đây là bản chất của biểu diễn ngữ cảnh hóa trong các kiến trúc xếp chồng self-attention như BERT và GPT.&lt;/p&gt;

&lt;h3 id=&quot;33-giới-hạn-của-attention&quot;&gt;3.3 Giới hạn của attention&lt;/h3&gt;

&lt;p&gt;Attention cung cấp cơ chế &lt;em&gt;truy cập động&lt;/em&gt; vào các biểu diễn sẵn có, chứ không tự tạo ra bộ nhớ trạng thái theo thời gian như ô LSTM. Nếu đặc trưng đầu vào yếu, việc tái trọng số cũng không khắc phục được. Ngoài ra, bản thân self-attention thuần không phân biệt được thứ tự vị trí (có tính đồng biến theo hoán vị), nên Transformer bắt buộc phải bổ sung mã hóa vị trí (&lt;em&gt;positional encoding&lt;/em&gt;).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-mã-minh-họa&quot;&gt;4. Mã minh họa&lt;/h2&gt;
&lt;h3 id=&quot;41-scaled-dot-product-attention-numpy&quot;&gt;4.1 Scaled dot-product attention (NumPy)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ổn định số
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Q: (..., Lq, dk)
    K: (..., Lk, dk)
    V: (..., Lk, dv)
    mask: broadcast được tới (..., Lq, Lk); True/1 nghĩa là &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;loại bỏ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    trả về: output (..., Lq, dv), weights (..., Lq, Lk)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;swapaxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (..., Lq, Lk)
&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Ví dụ self-attention đồ chơi
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demo: dùng X làm Q, K, V (chưa có phép chiếu học)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# (4, 8)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# (4, 4)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;rows sum to 1:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;42-causal-mask&quot;&gt;4.2 Causal mask&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mask[i, j] = True nếu j &amp;gt; i (cấm chú ý tới tương lai).&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tam giác trên (tương lai) phải ~0
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;43-multi-head-attention-numpy-khái-niệm&quot;&gt;4.3 Multi-head attention (NumPy khái niệm)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.02&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, L, d_model) -&amp;gt; (B, H, L, dk)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, H, L, dk) -&amp;gt; (B, L, d_model)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Self-attention cho đơn giản
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 6, 32)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 4, 6, 6)  — batch, heads, query pos, key pos
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;44-pytorch-dùng-trong-thực-tế&quot;&gt;4.4 PyTorch (dùng trong thực tế)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;torch_sdp_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    q,k,v: (B, H, L, d) hoặc (B, L, d)
    attn_mask: mask cộng broadcast được tới scores; dùng -inf cho vị trí cấm
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Module có sẵn (ưu tiên cho mô hình thật)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MultiheadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embed_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;average_attn_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Trong mã nguồn thực tế, nên ưu tiên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.MultiheadAttention&lt;/code&gt; hoặc hàm tích hợp tối ưu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.functional.scaled_dot_product_attention&lt;/code&gt; để đảm bảo tốc độ và độ ổn định số học.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;RNN và LSTM.&lt;/strong&gt; Attention ban đầu được gắn lên trên bộ mã hóa RNN: RNN tạo các trạng thái tuần tự còn attention chọn lọc thông tin từ chúng. Sau này, Transformer thay thế hoàn toàn phần hồi quy bằng self-attention kết hợp mã hóa vị trí.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nút thắt seq2seq.&lt;/strong&gt; Attention tháo gỡ trực tiếp giới hạn của vectơ ngữ cảnh kích thước cố định trong mô hình encoder–decoder (Chương 5–6).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Softmax như cơ chế chọn lọc mềm.&lt;/strong&gt; Trọng số attention áp dụng cùng phép biến đổi softmax vốn quen thuộc trong bài toán phân loại, nhưng thực hiện trên các &lt;em&gt;vị trí&lt;/em&gt; hoặc khe nhớ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Góc nhìn bộ nhớ và truy xuất.&lt;/strong&gt; Keys đóng vai trò địa chỉ, values là nội dung lưu trữ và queries là yêu cầu truy vấn — cách nhìn này kết nối attention với các hệ thống bộ nhớ khả vi và mô hình tăng cường truy xuất (RAG).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Transformer.&lt;/strong&gt; Một khối Transformer cơ bản gồm multi-head self-attention, mạng feed-forward, kết nối phần dư (residual) và chuẩn hóa lớp (LayerNorm), với QKV là phép toán trung tâm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Khả năng diễn giải.&lt;/strong&gt; Bản đồ nhiệt trọng số attention rất hữu ích khi gỡ lỗi, nhưng không nên xem là lời giải thích nhân quả tuyệt đối cho quyết định của mô hình.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Neural Machine Translation by Jointly Learning to Align and Translate (Bahdanau et al., 2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Đề xuất attention cộng tính cho dịch máy neuron, cho phép decoder tìm kiếm mềm trên các trạng thái nguồn khi sinh từng từ đích.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Effective Approaches to Attention-based Neural Machine Translation (Luong et al., 2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
So sánh attention toàn cục và cục bộ cùng các hàm chấm điểm nhân tính gọn nhẹ, dễ triển khai.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need (Vaswani et al., 2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Thay thế hồi quy bằng multi-head scaled dot-product self-attention, định hình kiến trúc Transformer.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1502.03044&quot;&gt;Show, Attend and Tell (Xu et al., 2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Ứng dụng attention thị giác vào bài toán sinh chú thích ảnh, mở rộng attention ra ngoài dữ liệu văn bản thuần túy.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;BERT (Devlin et al., 2019)&lt;/a&gt;&lt;/strong&gt; / &lt;strong&gt;&lt;a href=&quot;https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf&quot;&gt;dòng GPT (Radford et al.)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Chứng minh sức mạnh của việc xếp chồng nhiều lớp self-attention trong học biểu diễn và sinh ngôn ngữ quy mô lớn.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-cạm-bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;7. Cạm bẫy thường gặp và mẹo thực hành&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Nhầm điểm số với trọng số.&lt;/strong&gt;&lt;br /&gt;
\(e_{t,i}\) là điểm thô chưa chuẩn hóa; chỉ sau softmax mới thu được trọng số \(\alpha_{t,i}\) có tổng bằng 1. Không dùng trực tiếp điểm thô để tính trung bình trạng thái.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quên chia \(\sqrt{d_k}\).&lt;/strong&gt;&lt;br /&gt;
Khi \(d_k\) lớn, thiếu hệ số chia tỉ lệ khiến phân phối softmax quá nhọn và làm huấn luyện mất ổn định.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nhầm quy ước cực tính của mask.&lt;/strong&gt;&lt;br /&gt;
Cần kiểm tra rõ xem &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; (hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;True&lt;/code&gt;) biểu thị vị trí “giữ lại” hay “bị che”. Nhầm quy ước có thể âm thầm gây rò rỉ token tương lai hoặc loại bỏ nhầm token hợp lệ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Không che vị trí padding.&lt;/strong&gt;&lt;br /&gt;
Luôn áp padding mask khi huấn luyện theo batch có độ dài biến thiên để mô hình không phân bổ trọng số vào token &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PAD&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Diễn giải quá mức bản đồ attention.&lt;/strong&gt;&lt;br /&gt;
Trọng số attention là công cụ trực quan hóa hữu ích để kiểm tra tiêu điểm của mô hình, không phải bằng chứng nhân quả hoàn chỉnh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mẹo về nhiệt độ (temperature).&lt;/strong&gt;&lt;br /&gt;
Chia điểm số cho tham số nhiệt độ \(\tau\) trước softmax giúp điều chỉnh độ sắc nét của phân phối attention khi cần phân tích hoặc tinh chỉnh chuyên biệt.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mẹo về residual và LayerNorm.&lt;/strong&gt;&lt;br /&gt;
Khi xếp nhiều lớp attention sâu, luôn kết hợp kết nối phần dư (residual) và chuẩn hóa lớp (LayerNorm) để đảm bảo gradient lan truyền ổn định.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mẹo học theo trình tự.&lt;/strong&gt;&lt;br /&gt;
Nếu multi-head self-attention ban đầu khó hình dung, hãy nắm chắc cross-attention (“decoder nhìn sang encoder”) trước rồi chuyển sang trường hợp hai phía là cùng một chuỗi.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-tóm-tắt-các-điểm-chính&quot;&gt;8. Tóm tắt các điểm chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Attention thay thế nút thắt cố định bằng cơ chế truy xuất có trọng số động&lt;/strong&gt; trên toàn bộ các trạng thái đầu vào.&lt;/li&gt;
  &lt;li&gt;Quy trình &lt;strong&gt;tính điểm → chuẩn hóa softmax → tổng có trọng số các value&lt;/strong&gt; là khung chung cho Bahdanau, Luong và Transformer.&lt;/li&gt;
  &lt;li&gt;Khuôn khổ &lt;strong&gt;Q, K, V&lt;/strong&gt; thống nhất cả cross-attention lẫn self-attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chia tỉ lệ cho \(\sqrt{d_k}\)&lt;/strong&gt; giúp softmax giữ gradient ổn định khi số chiều lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multi-head attention&lt;/strong&gt; cho phép học đồng thời nhiều mẫu quan hệ khác nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Masking&lt;/strong&gt; (padding và causal) là thành phần bắt buộc của thuật toán chứ không phải chi tiết phụ.&lt;/li&gt;
  &lt;li&gt;Attention là cầu nối trực tiếp từ RNN seq2seq sang &lt;strong&gt;Transformer&lt;/strong&gt; ở chương tiếp theo.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Khi bạn có thể tự tính bằng tay một ví dụ nhỏ về cách bước decoder tạo ra \(\mathbf{c}_t\) từ các trạng thái encoder, bạn đã nắm vững nền tảng cho các mô hình attention hiện đại.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến); các đường dẫn dưới đây được lưu lại để tra cứu và ghi nhận nguồn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1467113421464723&quot;&gt;LLM Tập 4: Attention Mechanism (Q–K–V, quan hệ kết nối toàn phần)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/930207546288223&quot;&gt;Transformer là gì? Self-Attention siêu dễ hiểu (Phần 1)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1806844676942638&quot;&gt;Công thức Attention: tự tay tính Q, K, V&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PSs6nxngL6k&quot;&gt;Attention for Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Giải thích attention như cơ chế kết nối trực tiếp từ các trạng thái đầu vào tới từng bước giải mã trước khi sang Transformer.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown (tiếng Anh). Minh họa chi tiết phép tính Q, K, V tương ứng với phần toán học trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=L_2bT6hnGSQ&quot;&gt;Cách cơ chế Attention trong kiến trúc Transformer&lt;/a&gt; — namkuner (tiếng Việt). Trình bày cơ chế attention trong Transformer bằng tiếng Việt.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07 Cơ chế Chú ý</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter07/07_00_Introduction</id>
   <content type="html">&lt;p&gt;Hãy tưởng tượng bạn đang dịch một câu tiếng Anh dài 60 từ sang tiếng Việt, nhưng luật chơi bắt buộc bạn phải đọc hết cả 60 từ, gấp sách lại, nhồi toàn bộ ý nghĩa vào một mẩu giấy nhớ nhỏ xíu rồi mới được đặt bút dịch từ đầu đến cuối. Đó chính xác là “nút thắt cổ chai” mà kiến trúc Seq2Seq dùng RNN/LSTM từng mắc phải — cho đến khi &lt;strong&gt;Cơ chế Chú ý (Attention)&lt;/strong&gt; xuất hiện, cho phép mô hình “liếc nhìn trực tiếp” vào đúng những từ nguồn liên quan nhất tại mỗi bước sinh từ.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-cơ-chế-chú-ý&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Cơ chế Chú ý&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phá vỡ nút thắt vector ngữ cảnh cố định&lt;/strong&gt;:
Thay vì ép toàn bộ câu nguồn vào duy nhất trạng thái ẩn cuối \(h_T\), Attention tạo ra một vector ngữ cảnh động \(c_t = \sum_i \alpha_{ti} h_i\) thay đổi theo từng bước giải mã.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ngôn ngữ Query – Key – Value (Q, K, V)&lt;/strong&gt;:
Attention thực chất là một phép &lt;strong&gt;tra cứu từ điển mềm khả vi&lt;/strong&gt;: Query hỏi &lt;em&gt;“tôi đang cần thông tin gì?”&lt;/em&gt;, Key mô tả &lt;em&gt;“mỗi vị trí đang chứa gì?”&lt;/em&gt;, độ khớp giữa Q và K qua &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softmax&lt;/code&gt; tạo trọng số \(\alpha\) để trộn các Value.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bốn biến thể Attention cốt lõi trong Transformer&lt;/strong&gt;:
Self-Attention không che (encoder), Causal/Masked Self-Attention (decoder tự hồi quy), Cross-Attention (nối decoder với encoder), và Multi-Head Attention (nhiều không gian con song song).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối từ tuần tự sang đồ thị kết nối toàn phần&lt;/strong&gt;:
Với Self-Attention, khoảng cách truyền thông tin giữa từ thứ 1 và từ thứ 1.000 rút ngắn từ \(O(L)\) bước hồi quy xuống đúng &lt;strong&gt;\(O(1)\)&lt;/strong&gt; bước trực tiếp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-phép-tra-cứu-mềm-soft-dictionary-lookup-với-3-token&quot;&gt;Giải thích: Tính tay phép tra cứu mềm (Soft Dictionary Lookup) với 3 token&lt;/h3&gt;

&lt;p&gt;Giả sử Query hiện tại là \(\mathbf{q} = [1, 0]\), và ta có 3 cặp Key–Value tương ứng với 3 từ trong câu:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Từ 1: \(\mathbf{k}_1 = [1, 0], \; \mathbf{v}_1 = [10, 0]\)&lt;/li&gt;
  &lt;li&gt;Từ 2: \(\mathbf{k}_2 = [0, 1], \; \mathbf{v}_2 = [0, 10]\)&lt;/li&gt;
  &lt;li&gt;Từ 3: \(\mathbf{k}_3 = [1, 1], \; \mathbf{v}_3 = [4, 4]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính điểm tương đồng (dot product \(s_i = \mathbf{q} \cdot \mathbf{k}_i\))&lt;/strong&gt;:
\(s_1 = 1, \quad s_2 = 0, \quad s_3 = 1\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa bằng Softmax&lt;/strong&gt; (với \(e^1 \approx 2{,}718, \; e^0 = 1\), tổng mẫu số \(= 2{,}718 + 1 + 2{,}718 = 6{,}436\)):
\(\alpha_1 \approx \mathbf{0{,}422}, \quad \alpha_2 \approx \mathbf{0{,}156}, \quad \alpha_3 \approx \mathbf{0{,}422}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng có trọng số các Value&lt;/strong&gt;:
\(\mathbf{c} = 0{,}422[10, 0] + 0{,}156[0, 10] + 0{,}422[4, 4] = \mathbf{[5{,}908, \; 3{,}248]}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Thay vì chỉ lấy cứng một mục như từ điển Python (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dict[key]&lt;/code&gt;), Attention lấy trung bình có trọng số mượt mà — nhờ đó toàn bộ phép tra cứu đều khả vi để huấn luyện bằng lan truyền ngược!&lt;/p&gt;

&lt;h1 id=&quot;chương-07--cơ-chế-chú-ý&quot;&gt;Chương 07 — Cơ chế Chú ý&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attention_encoder_decoder.png&quot; alt=&quot;Attention Encoder-Decoder&quot; /&gt;
&lt;em&gt;Encoder–decoder với cơ chế chú ý: tại mỗi bước sinh, bộ giải mã nhìn lại toàn bộ các trạng thái của bộ mã hóa. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;vì-sao-cần-cơ-chế-chú-ý&quot;&gt;Vì sao cần cơ chế chú ý&lt;/h2&gt;

&lt;p&gt;Các mô hình hồi quy (Chương 5–6) xử lý chuỗi tuần tự từng bước và nén toàn bộ lịch sử vào một trạng thái ẩn. Cách tiếp cận này bộc lộ hai hạn chế lớn khi chuỗi dài:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nút thắt thông tin&lt;/strong&gt; (&lt;em&gt;information bottleneck&lt;/em&gt;) — đặc biệt rõ ở mô hình encoder–decoder cổ điển, nơi toàn bộ câu nguồn phải được nén vào một vectơ có kích thước cố định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khó truyền thông tin tầm xa&lt;/strong&gt; — tín hiệu từ vị trí \(i\) tới vị trí \(j\) phải đi qua nhiều bước tuần tự, dễ bị suy giảm do hiện tượng gradient biến mất.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Cơ chế chú ý&lt;/strong&gt; (&lt;em&gt;attention&lt;/em&gt;) giải quyết đồng thời cả hai vấn đề bằng cách cho phép mô hình &lt;em&gt;truy xuất động&lt;/em&gt; các phần liên quan của đầu vào (hoặc của chính chuỗi đó) tại mỗi bước tính toán. Thay vì dựa vào một vectơ tóm tắt cố định, mô hình tính một phân phối trọng số mềm trên các vị trí và lấy tổ hợp có trọng số của các biểu diễn tương ứng.&lt;/p&gt;

&lt;p&gt;Ban đầu được đề xuất để cải thiện dịch máy dùng RNN, cơ chế chú ý sau đó trở thành thành phần trung tâm của &lt;strong&gt;Transformer&lt;/strong&gt; — kiến trúc nền tảng cho các mô hình ngôn ngữ lớn, nhiều hệ thống thị giác máy tính và mô hình đa phương thức. Chương này xây dựng attention từ nguyên lý cơ bản để khi sang Chương 8, Transformer trở thành sự kết hợp tự nhiên của các khối đã quen thuộc.&lt;/p&gt;

&lt;h3 id=&quot;bảng-tóm-tắt-4-dạng-attention-trong-transformer&quot;&gt;Bảng tóm tắt 4 dạng attention trong Transformer&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Loại&lt;/th&gt;
      &lt;th&gt;Q lấy từ đâu&lt;/th&gt;
      &lt;th&gt;K, V lấy từ đâu&lt;/th&gt;
      &lt;th&gt;Mask&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Self-attention&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;cùng chuỗi&lt;/td&gt;
      &lt;td&gt;cùng chuỗi&lt;/td&gt;
      &lt;td&gt;tùy chọn (đầy đủ / padding)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Masked (causal) self-attention&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;decoder&lt;/td&gt;
      &lt;td&gt;decoder&lt;/td&gt;
      &lt;td&gt;che các vị trí tương lai&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Cross-attention&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;decoder&lt;/td&gt;
      &lt;td&gt;encoder&lt;/td&gt;
      &lt;td&gt;thường chỉ dùng padding mask&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Multi-head&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;như trên, chạy nhiều head song song&lt;/td&gt;
      &lt;td&gt;như trên&lt;/td&gt;
      &lt;td&gt;như trên&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_scaled_dot_product.jpg&quot; alt=&quot;Scaled dot-product attention&quot; /&gt;
&lt;em&gt;Hình: Self-attention — \(\mathrm{softmax}(QK^\top/\sqrt{d})\,V\). (Minh họa từ video Attention trong Transformer)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;self-attention-qua-trực-giác-từ-nào-liên-quan-đến-từ-nào&quot;&gt;Self-attention qua trực giác: “Từ nào liên quan đến từ nào?”&lt;/h3&gt;

&lt;p&gt;Với các từ đa nghĩa (chẳng hạn “Apple” có thể là quả táo hoặc hãng công nghệ), mô hình chỉ xác định được nghĩa chính xác khi &lt;strong&gt;dựa vào ngữ cảnh&lt;/strong&gt; của các từ xung quanh. Self-attention thiết lập các liên kết chú ý có trọng số giữa mọi token trong cùng một câu.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_context_arcs_disambiguation.jpg&quot; alt=&quot;Cung attention theo ngữ cảnh&quot; /&gt;
&lt;em&gt;Hình: Các từ ngữ cảnh (ví dụ “màu cam”, “điện thoại”) hướng trọng số chú ý tới “Apple” theo nghĩa công nghệ. (Minh họa từ video Transformer / Self-Attention nhập môn)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_scaled_sdp_block_diagram.jpg&quot; alt=&quot;Sơ đồ khối Scaled Dot-Product&quot; /&gt;
&lt;em&gt;Hình: Quy trình tính toán Q, K → chia tỉ lệ → áp mask (nếu có) → softmax → nhân V. (Minh họa từ video Transformer / Self-Attention nhập môn)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_qkv_database_metaphor.jpg&quot; alt=&quot;Ẩn dụ Q/K/V như tra bảng&quot; /&gt;
&lt;em&gt;Hình: Ẩn dụ tra cứu — Query là câu hỏi, Key là khóa đối chiếu, Value là nội dung trích xuất. (Minh họa từ video Transformer / Self-Attention nhập môn)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;góc-nhìn-trong-llm-mạng-quan-hệ-kết-nối-toàn-phần&quot;&gt;Góc nhìn trong LLM: Mạng quan hệ kết nối toàn phần&lt;/h3&gt;

&lt;p&gt;Trong mô hình ngôn ngữ lớn, lớp embedding ánh xạ mỗi token thành một vectơ; &lt;strong&gt;attention&lt;/strong&gt; là cơ chế giúp các token &lt;em&gt;trao đổi thông tin&lt;/em&gt; trực tiếp với nhau. Mọi vị trí đều có thể liên kết với mọi vị trí khác (như một đồ thị kết nối đầy đủ) với trọng số liên kết được tính &lt;strong&gt;động&lt;/strong&gt; theo nội dung.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/llm_attn_title_fully_connected.jpg&quot; alt=&quot;Tiêu đề: attention = quan hệ kết nối toàn phần&quot; /&gt;
&lt;em&gt;Hình: Attention dưới góc nhìn mạng quan hệ kết nối toàn phần, nơi Q–K–V tạo ra trọng số liên kết động. (Minh họa từ video LLM Attention Mechanism)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/llm_attn_qkv_pipeline_diagram.jpg&quot; alt=&quot;Pipeline Q → score → Softmax → multi-head → ngữ cảnh&quot; /&gt;
&lt;em&gt;Hình: Luồng xử lý từ đầu vào → Query / Key / Value → ma trận điểm số → Softmax → (multi-head) → tổng hợp ngữ cảnh → đầu ra. (Minh họa từ video LLM Attention Mechanism)&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;mục-tiêu-học-tập&quot;&gt;Mục tiêu học tập&lt;/h2&gt;

&lt;p&gt;Sau chương này, bạn sẽ có thể:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Giải thích nút thắt thông tin của encoder–decoder và cách attention tháo gỡ nó.&lt;/li&gt;
  &lt;li&gt;Viết quy trình tính attention tổng quát: &lt;strong&gt;tính điểm số → chuẩn hóa softmax → tổng có trọng số các giá trị&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;So sánh attention &lt;strong&gt;Bahdanau (cộng tính)&lt;/strong&gt; và &lt;strong&gt;Luong (nhân tính)&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Sử dụng khuôn khổ &lt;strong&gt;Query / Key / Value&lt;/strong&gt; cho cả chú ý chéo (&lt;em&gt;cross-attention&lt;/em&gt;) và tự chú ý (&lt;em&gt;self-attention&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Chứng minh lý do scaled dot-product attention cần hệ số chia \(1/\sqrt{d_k}\).&lt;/li&gt;
  &lt;li&gt;Cài đặt attention và multi-head attention với kích thước tensor, mask và độ ổn định số học chính xác.&lt;/li&gt;
  &lt;li&gt;Nhận diện các bài báo nền tảng và những lỗi cài đặt thường gặp (padding mask, causal mask, quên chia tỉ lệ).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;lộ-trình-học&quot;&gt;Lộ trình học&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Bài&lt;/th&gt;
      &lt;th&gt;Trọng tâm&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;07-01 Cơ sở&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Trực giác, bối cảnh lịch sử, Bahdanau/Luong, QKV, scaled attention, giới thiệu multi-head&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;07-02 Đi sâu&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Phân tích toán học chi tiết và cài đặt đầy đủ&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;07-02-01 Toán học&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Các hàm chấm điểm, đại số self-attention, multi-head và lý thuyết masking&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;07-02-02 Cài đặt&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Cài đặt từ đầu bằng NumPy/PyTorch, ví dụ minh họa, bài báo và bẫy thường gặp&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Bạn nên đọc bài &lt;strong&gt;07-01&lt;/strong&gt; trước ngay cả khi đã quen với Transformer, vì các thuật ngữ nền tảng (vectơ ngữ cảnh, căn chỉnh, QKV, mask) được thống nhất từ đó.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-tiên-quyết&quot;&gt;Kiến thức tiên quyết&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Kiến thức cơ bản về mạng neuron (lớp tuyến tính, softmax, lan truyền ngược).&lt;/li&gt;
  &lt;li&gt;Nắm khái niệm mô hình chuỗi RNN/LSTM (trạng thái ẩn encoder, các bước sinh của decoder).&lt;/li&gt;
  &lt;li&gt;Quen thuộc với kích thước tensor: batch, độ dài chuỗi và chiều embedding.&lt;/li&gt;
  &lt;li&gt;Hiểu vai trò của softmax trong việc tạo phân phối xác suất rời rạc.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;mô-hình-tư-duy-cốt-lõi&quot;&gt;Mô hình tư duy cốt lõi&lt;/h2&gt;

&lt;p&gt;Có thể xem attention là một &lt;strong&gt;bộ nhớ mềm truy xuất theo nội dung&lt;/strong&gt; (&lt;em&gt;content-addressable soft memory&lt;/em&gt;):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Query&lt;/strong&gt;: thông tin hiện tại đang cần tìm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Keys&lt;/strong&gt;: đặc trưng đại diện của từng vị trí bộ nhớ để đối chiếu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Values&lt;/strong&gt;: nội dung thực sự được trích xuất khi vị trí đó khớp.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mọi biến thể khác — từ Bahdanau, Luong đến multi-head hay causal mask — đều là các lựa chọn thiết kế xoay quanh cơ chế cốt lõi này. Khi bạn có thể tự vẽ luồng tính toán đó trên giấy cho cả &lt;em&gt;dịch máy&lt;/em&gt; (decoder chú ý tới encoder) và &lt;em&gt;self-attention&lt;/em&gt; (chuỗi chú ý tới chính nó), bạn đã sẵn sàng cho phần còn lại của chương và cho Transformer.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video sau (Machine Learning Thực Chiến); các đường dẫn dưới đây được lưu lại để tra cứu và ghi nhận nguồn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1467113421464723&quot;&gt;LLM Tập 4: Attention Mechanism (Q–K–V, quan hệ kết nối toàn phần)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/930207546288223&quot;&gt;Transformer là gì? Self-Attention siêu dễ hiểu (Phần 1)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1806844676942638&quot;&gt;Công thức Attention: tự tay tính Q, K, V&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1007473105556936&quot;&gt;Attention trong Transformer (Self, Masked, Cross, Multi-Head)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau khi nắm vững toán học attention, bạn có thể đọc thêm bài &lt;strong&gt;07-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về FlashAttention, PagedAttention và grouped-query attention trong các hệ thống LLM.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown (tiếng Anh). Giải thích trực quan từng bước quy trình Query, Key và Value xuyên suốt chương này.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PSs6nxngL6k&quot;&gt;Attention for Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Minh họa cách bổ sung attention vào mô hình chuỗi trước thời đại Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dqoEU9Ac3ek&quot;&gt;MIT 6.S191 (2024): Recurrent Neural Networks, Transformers, and Attention&lt;/a&gt; — Alexander Amini (tiếng Anh). Bài giảng MIT 2024 kết nối cơ chế attention vào kiến trúc Transformer.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Gần 30 năm sau khi khai sinh ra LSTM (1997), chính cha đẻ của nó — Sepp Hochreiter — bất ngờ quay trở lại vào năm 2024 với &lt;strong&gt;xLSTM (Extended LSTM)&lt;/strong&gt; và chứng minh rằng: chỉ cần thay cổng sigmoid bằng cổng hàm mũ (exponential gating) và mở rộng bộ nhớ tế bào từ vector thành &lt;strong&gt;ma trận&lt;/strong&gt;, họ kiến trúc LSTM hoàn toàn có thể mở rộng lên hàng tỷ tham số và cạnh tranh sòng phẳng với Transformer và Mamba!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-ứng-dụng-và-đột-phá-hiện-đại-của-hồi-quy-có-cổng-20222026&quot;&gt;Kiến thức cần nhớ: Bốn ứng dụng và đột phá hiện đại của Hồi quy có cổng (2022–2026)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;xLSTM (2024) — Hai biến thể sLSTM và mLSTM&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;sLSTM&lt;/strong&gt;: dùng cổng hàm mũ \(i_t = \exp(\tilde{i}_t), \; f_t = \exp(\tilde{f}_t)\) kèm biến chuẩn hóa \(n_t\) để khắc phục nhược điểm khó “sửa sai” quyết định lưu trữ của LSTM cũ.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;mLSTM&lt;/strong&gt;: nâng cấp bộ nhớ tế bào từ vector \(c_t \in \mathbb{R}^d\) thành &lt;strong&gt;ma trận&lt;/strong&gt; \(C_t \in \mathbb{R}^{d \times d}\) cập nhật kiểu hiệp phương sai \(C_t = f_t C_{t-1} + i_t v_t k_t^T\), cho phép &lt;strong&gt;huấn luyện song song hoàn toàn&lt;/strong&gt; như Transformer!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuỗi thời gian tài chính, cảm biến IoT và luồng sự kiện dạng bảng&lt;/strong&gt;:
Trên dữ liệu cảm biến nhiễu có kích thước vừa phải và độ trễ mili-giây, LSTM/GRU (hoặc kiến trúc lai CNN–LSTM) vẫn là baseline cực mạnh, dễ triển khai và ít đòi hỏi dữ liệu khổng lồ như Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xử lý giọng nói thời gian thực (Streaming ASR / TTS / VAD)&lt;/strong&gt;:
Hệ thống nhận dạng giọng nói trực tuyến và lọc nhiễu âm thanh (như RNNoise dựa trên GRU) cần xử lý từng khung âm thanh 10–20 ms mà không nhìn trước tương lai — sân chơi tự nhiên của mô hình hồi quy có cổng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc lai trong hệ thống quy mô lớn&lt;/strong&gt;:
Các mô hình kết hợp tầng hồi quy có cổng / mLSTM với vài tầng Attention mang lại dung lượng nhớ dài mà vẫn giữ chi phí suy luận thấp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-bước-nâng-cấp-từ-bộ-nhớ-vector-lstm-sang-bộ-nhớ-ma-trận-mlstm&quot;&gt;Giải thích: Tính tay bước nâng cấp từ Bộ nhớ Vector (LSTM) sang Bộ nhớ Ma trận (mLSTM)&lt;/h3&gt;

&lt;p&gt;Giả sử kích thước ẩn \(d = 2\), tại bước \(t\) ta có bộ nhớ ma trận cũ \(C_{t-1} = \begin{bmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{bmatrix}\), khóa mới \(k_t = \begin{bmatrix} 1 \\ 2 \end{bmatrix}\), giá trị mới \(v_t = \begin{bmatrix} 3 \\ -1 \end{bmatrix}\), cổng quên \(f_t = 0{,}5\) và cổng nhập \(i_t = 1{,}0\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính tích ngoài (Outer Product) lưu cặp khóa–giá trị \(v_t k_t^T\)&lt;/strong&gt;:
\(v_t k_t^T = \begin{bmatrix} 3 \\ -1 \end{bmatrix} \begin{bmatrix} 1 &amp;amp; 2 \end{bmatrix} = \begin{bmatrix} 3 &amp;amp; 6 \\ -1 &amp;amp; -2 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật bộ nhớ ma trận \(C_t = f_t C_{t-1} + i_t (v_t k_t^T)\)&lt;/strong&gt;:
\(C_t = 0{,}5 \begin{bmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{bmatrix} + 1{,}0 \begin{bmatrix} 3 &amp;amp; 6 \\ -1 &amp;amp; -2 \end{bmatrix} = \begin{bmatrix} 3{,}5 &amp;amp; 6{,}0 \\ -1{,}0 &amp;amp; -1{,}5 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Truy xuất bằng vector truy vấn \(q_t = [1, 0]^T\)&lt;/strong&gt;:
\(h_t \propto C_t q_t = \begin{bmatrix} 3{,}5 \\ -1{,}0 \end{bmatrix}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bằng cách tăng dung lượng bộ nhớ từ \(d\) số (vector) lên \(d^2\) số (ma trận), mLSTM biến ô LSTM cổ điển thành một &lt;strong&gt;bộ nhớ kết hợp khóa–giá trị&lt;/strong&gt; có khả năng lưu trữ và truy xuất nhiều mục song song vượt trội hơn hẳn!&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-hồi-quy-có-cổng-sau-lstm--xlstm-và-các-ứng-dụng-hiện-đại&quot;&gt;Tùy chọn: Hồi quy có cổng sau LSTM — xLSTM và các ứng dụng hiện đại&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết về cổng LSTM/GRU. Nội dung tóm lược hướng phát triển mới của RNN có cổng năm 2024 (xLSTM) cùng những bài toán thực tế nơi LSTM/GRU vẫn là lựa chọn phù hợp.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Phương trình trạng thái tế bào của LSTM:&lt;/p&gt;

\[\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t\]

&lt;p&gt;vẫn là một trong những biểu diễn trực quan nhất cho khái niệm &lt;strong&gt;bộ nhớ có thể ghi và xóa&lt;/strong&gt;. Dù Transformer chiếm ưu thế trong các mô hình ngôn ngữ lớn, các kiến trúc hồi quy có cổng vẫn giữ vai trò riêng trong nhiều hệ thống thực tế.&lt;/p&gt;

&lt;h2 id=&quot;1-xlstm-2024-cổng-hàm-mũ-và-bộ-nhớ-dạng-ma-trận&quot;&gt;1. xLSTM (2024): Cổng hàm mũ và bộ nhớ dạng ma trận&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2405.04517&quot;&gt;Beck et al., 2024&lt;/a&gt; mở rộng kiến trúc LSTM với hai biến thể chính:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;sLSTM&lt;/strong&gt; — sử dụng bộ nhớ vô hướng với cổng vào/quên dạng hàm mũ kèm cơ chế chuẩn hóa để tăng tính ổn định so với ô LSTM cổ điển.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;mLSTM&lt;/strong&gt; — sử dụng bộ nhớ dạng &lt;em&gt;ma trận&lt;/em&gt; cập nhật theo quy tắc tương tự ma trận hiệp phương sai, cho phép huấn luyện song song như khối Transformer.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Kết quả trong bài báo cho thấy xLSTM tiệm cận hiệu năng của Transformer trên bài toán mô hình hóa ngôn ngữ ở quy mô vừa. Điều này chứng minh cơ chế &lt;strong&gt;cổng kết hợp bộ nhớ&lt;/strong&gt; vẫn tiếp tục được nghiên cứu và cải tiến, dù không đồng nghĩa với việc thay thế hoàn toàn attention.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-thực-tế-hiện-nay&quot;&gt;2. Ứng dụng thực tế hiện nay&lt;/h2&gt;

&lt;h3 id=&quot;chuỗi-thời-gian-và-luồng-sự-kiện-dạng-bảng&quot;&gt;Chuỗi thời gian và luồng sự kiện dạng bảng&lt;/h3&gt;

&lt;p&gt;Nhiều hệ thống dự báo thực tế (nhu cầu bán lẻ, chỉ số sinh hiệu ICU, dữ liệu cảm biến công nghiệp) vẫn dùng &lt;strong&gt;bộ mã hóa LSTM/GRU&lt;/strong&gt;, thường kết hợp trong kiến trúc Temporal Fusion Transformer hoặc mô hình seq2seq gọn nhẹ. Cơ chế cổng giúp các mô hình này xử lý ổn định dữ liệu có nhiễu và tần suất lấy mẫu không đều.&lt;/p&gt;

&lt;h3 id=&quot;xử-lý-giọng-nói-và-dữ-liệu-trực-tuyến-streaming&quot;&gt;Xử lý giọng nói và dữ liệu trực tuyến (streaming)&lt;/h3&gt;

&lt;p&gt;Các hệ thống phát hiện từ đánh thức (wake-word) trên thiết bị biên và một số bộ mã hóa nhận dạng giọng nói trực tuyến vẫn ưu tiên GRU vì trạng thái bộ nhớ chỉ chiếm vài kilobyte. Các mô hình ASR quy mô lớn như Whisper (Chương 19) dùng Transformer; ranh giới lựa chọn nằm ở &lt;strong&gt;độ trễ và dung lượng bộ nhớ&lt;/strong&gt; hơn là riêng độ chính xác trên tập chuẩn như LibriSpeech.&lt;/p&gt;

&lt;h3 id=&quot;kiến-trúc-lai&quot;&gt;Kiến trúc lai&lt;/h3&gt;

&lt;p&gt;Một mẫu thiết kế phổ biến giai đoạn 2024–2026 là dùng Transformer (hoặc Mamba) làm mô hình nền, kết hợp &lt;strong&gt;bộ giải mã LSTM&lt;/strong&gt; hoặc &lt;strong&gt;bộ điều khiển GRU&lt;/strong&gt; ở đầu ra hành động trong lĩnh vực robot và hệ thống gợi ý theo phiên.&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-mã-nguồn-phổ-biến&quot;&gt;3. Thư viện và mã nguồn phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.GRU&lt;/code&gt; — các cài đặt tối ưu dùng trong sản xuất.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/NX-AI/xlstm&quot;&gt;NX-AI/xlstm&lt;/a&gt; — mã nguồn chính thức của xLSTM.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/sktime/sktime&quot;&gt;sktime&lt;/a&gt; / &lt;a href=&quot;https://github.com/awslabs/gluonts&quot;&gt;GluonTS&lt;/a&gt; — các thư viện dự báo chuỗi thời gian hỗ trợ mô hình hồi quy.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2405.04517&quot;&gt;xLSTM (Beck et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2312.00752&quot;&gt;Mamba (Gu &amp;amp; Dao, 2023)&lt;/a&gt; — đại diện nổi bật của nhóm mô hình không gian trạng thái hồi quy tuyến tính (đã giới thiệu ở Chương 05), thường được đặt cạnh xLSTM khi đối chiếu các kiến trúc hồi quy hiện đại.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1912.09363&quot;&gt;Temporal Fusion Transformers (Lim et al., 2021)&lt;/a&gt; — kiến trúc kết hợp bộ mã hóa LSTM và attention được ứng dụng rộng rãi giai đoạn 2022–2026.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-vai-trò-bổ-trợ-cho-nội-dung-cốt-lõi&quot;&gt;5. Vai trò bổ trợ cho nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên nắm vững phần suy diễn cổng quên, cổng vào và cổng ra ở bài lý thuyết trước. Bài đọc thêm này chỉ cập nhật thêm &lt;strong&gt;xLSTM&lt;/strong&gt; và các bài toán công nghiệp còn sử dụng LSTM/GRU, không làm thay đổi hệ phương trình cơ bản của chương.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=0aWGTNS03PU&quot;&gt;XLSTM - Extended LSTMs with sLSTM and mLSTM (paper explained)&lt;/a&gt; — AI Bites (tiếng Anh). Giải thích bài báo xLSTM (2024) với hai biến thể sLSTM và mLSTM được đề cập trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Ôn lại ô LSTM gốc năm 1997 làm mốc đối chiếu cho các cải tiến mới.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker (tiếng Anh). Hệ thống sơ đồ cổng giúp dễ nhận ra những điểm thay đổi ở sLSTM và mLSTM.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-01 Mạng Long Short-Term Memory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_01_LSTM_Architecture/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_01_LSTM_Architecture</id>
   <content type="html">&lt;p&gt;Nhìn vào sơ đồ nội bộ một ô LSTM lần đầu tiên, ai cũng dễ choáng ngợp trước mạng lưới mũi tên, dấu nhân chấm \(\odot\), dấu cộng \(+\), ba khối \(\sigma\) và hai khối \(\tanh\). Nhưng nếu đọc nó như một chiếc máy tính siêu nhỏ có &lt;strong&gt;bộ nhớ dài hạn (RAM)&lt;/strong&gt; và &lt;strong&gt;ba chiếc van điều khiển&lt;/strong&gt;, mọi phương trình sẽ lập tức trở nên sáng rõ và logic đến bất ngờ.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-tầng-hiểu-biết-để-làm-chủ-kiến-trúc-lstm&quot;&gt;Kiến thức cần nhớ: Ba tầng hiểu biết để làm chủ Kiến trúc LSTM&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giải phẫu phương trình 4 nhánh (\(f_t, i_t, \tilde{c}_t, o_t\))&lt;/strong&gt;:
Nắm rõ vì sao các cổng dùng \(\sigma \in (0,1)\) (vai trò tỷ lệ mở van) còn ứng viên nội dung \(\tilde{c}_t\) và đầu ra tế bào dùng \(\tanh \in (-1,1)\) (vai trò giá trị có dấu âm/dương).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổ chức cài đặt tối ưu hóa ma trận gộp&lt;/strong&gt;:
Thay vì gọi 4 phép nhân ma trận nhỏ riêng lẻ, các thư viện như PyTorch gộp cả 4 trọng số thành &lt;strong&gt;một ma trận lớn duy nhất&lt;/strong&gt; kích thước \(4 d_h \times (d_x + d_h)\) rồi dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chunk(4)&lt;/code&gt; để tách cổng — tận dụng tối đa băng thông GPU.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh thực nghiệm LSTM vs. GRU và phân tích hành vi cổng&lt;/strong&gt;:
Quan sát trực tiếp giá trị số của \(f_t, i_t\) trên chuỗi có nhiễu để thấy cổng tự đóng lại trước tín hiệu rác và mở rộng khi gặp thông tin quan trọng.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-kích-thước-bộ-tham-số-của-lstm-so-với-rnn-và-gru&quot;&gt;Giải thích: Tính tay kích thước bộ tham số của LSTM so với RNN và GRU&lt;/h3&gt;

&lt;p&gt;Với cùng kích thước đầu vào \(d_x = 16\) và kích thước ẩn \(d_h = 32\) (tính theo công thức chuẩn 1 bias cho mỗi cổng):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Kiến trúc&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Số nhánh biến đổi&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Công thức tham số&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Kết quả cụ thể (\(d_x=16, d_h=32\))&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Tỷ lệ so với RNN&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;RNN thuần&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1 \times d_h (d_x + d_h + 1)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;\(32 \times 49 = \mathbf{1{,}568}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1\times\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;GRU&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;3 (\(r, z, \tilde{h}\))&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(3 \times d_h (d_x + d_h + 1)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;\(3 \times 1{,}568 = \mathbf{4{,}704}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(3\times\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;LSTM&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;4 (\(f, i, \tilde{c}, o\))&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4 \times d_h (d_x + d_h + 1)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;\(4 \times 1{,}568 = \mathbf{6{,}272}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(4\times\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Cái giá để đánh đổi khả năng nhớ dài hạn rất rõ ràng: LSTM cần đúng &lt;strong&gt;gấp 4 lần&lt;/strong&gt; số tham số của RNN, còn GRU tiết kiệm đúng &lt;strong&gt;25%&lt;/strong&gt; so với LSTM (tỷ lệ \(3 : 4\)).&lt;/p&gt;

&lt;p&gt;Bài học này trình bày về LSTM và các kiến trúc hồi quy có cổng liên quan qua hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết LSTM và GRU&lt;/strong&gt; — cơ chế cổng, trạng thái tế bào, nền tảng toán học và trực giác qua ví dụ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Triển khai LSTM&lt;/strong&gt; — mã nguồn đầy đủ, phân tích cổng, so sánh GRU, bài báo nền tảng và các bẫy thường gặp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Tổng quan ngắn gọn trước khi đi vào phần lý thuyết và mã nguồn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker (tiếng Anh). Minh họa từng cổng tương ứng với cấu trúc mã nguồn trong bài cài đặt.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Simple Explanation of GRU (Gated Recurrent Units)&lt;/td&gt;
          &lt;td&gt;Deep Learning Tutorial 37 (Tensorflow &amp;amp; Python)](https://www.youtube.com/watch?v=tOuXgORsXJ4) — codebasics (tiếng Anh). Giới thiệu biến thể GRU với cấu trúc cổng tinh giản hơn.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-01-02 Triển khai LSTM</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_01_02_LSTM_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_01_02_LSTM_Implementation</id>
   <content type="html">&lt;p&gt;Khi bạn chuyển từ sơ đồ LSTM sang code chạy thực tế, một quyết định tưởng nhỏ — như khởi tạo bias cổng quên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_f = 1.0&lt;/code&gt; hay chọn đúng tuple &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(h_n, c_n)&lt;/code&gt; trả về từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM&lt;/code&gt; — có thể quyết định mô hình hội tụ sau 20 epoch hay đứng im không học được gì. Mục này nối thẳng phương trình toán học vào cài đặt thực chiến và kiểm thử trên các tác vụ bộ nhớ dài hạn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-triển-khai-lstmgru-hiệu-quả&quot;&gt;Kiến thức cần nhớ: Ba trụ cột triển khai LSTM/GRU hiệu quả&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Thiết kế bài kiểm tra bộ nhớ dài hạn (Adding / Memorization Problem)&lt;/strong&gt;:
Muốn chứng minh LSTM thực sự hơn RNN, ta cần bài toán chuẩn mà thông tin quan trọng nằm ở đầu chuỗi, ở giữa là hàng chục bước nhiễu, và đầu ra chỉ yêu cầu ở bước cuối (như dự đoán tổng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;first + last&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quản lý bộ đôi trạng thái &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(h, c)&lt;/code&gt; và kiến trúc đa tầng / hai chiều (Bidirectional)&lt;/strong&gt;:
Với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM(num_layers=L, bidirectional=True)&lt;/code&gt;, cả &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h_0&lt;/code&gt; lẫn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;c_0&lt;/code&gt; đều có hình dạng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(2*L, batch, hidden_size)&lt;/code&gt; — khác biệt quan trọng so với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.GRU&lt;/code&gt; vốn chỉ có một tensor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h_0&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỹ thuật khởi tạo cổng quên và chẩn đoán qua nhật ký cổng&lt;/strong&gt;:
Theo khuyến nghị của Jozefowicz et al. (2015), đặt bias cổng quên dương (\(b_f = 1\) hoặc \(2\)) và in phân phối \(f_t, i_t\) giúp phát hiện sớm hiện tượng bão hòa cổng.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-nhanh-kích-thước-tensor-cho-nnlstm-đa-tầng-hai-chiều&quot;&gt;Giải thích: Tính nhanh kích thước tensor cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM&lt;/code&gt; đa tầng hai chiều&lt;/h3&gt;

&lt;p&gt;Giả sử bạn khai báo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lstm = nn.LSTM(input_size=64, hidden_size=128, num_layers=2, batch_first=True, bidirectional=True)&lt;/code&gt; và đưa vào một batch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt; có shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(32, 50, 64)&lt;/code&gt; (32 câu, mỗi câu dài 50 token):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Biến trả về&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Công thức shape&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Shape thực tế&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Ý nghĩa&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, T, D * H)&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(32, 50, 256)&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Trạng thái ẩn tầng cuối tại mọi bước thời gian (128 xuôi + 128 ngược)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h_n&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(D * L, B, H)&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 32, 128)&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Trạng thái ẩn cuối của 2 tầng \(\times\) 2 chiều&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;c_n&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(D * L, B, H)&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 32, 128)&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Trạng thái tế bào cuối của 2 tầng \(\times\) 2 chiều&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Để lấy biểu diễn tổng hợp cho cả câu (dùng cho phân loại văn bản), ta nối hai chiều của &lt;strong&gt;tầng cuối cùng&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.cat([h_n[-2], h_n[-1]], dim=-1)&lt;/code&gt; \(\to\) shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(32, 256)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Phần cài đặt LSTM gồm hai nội dung chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Triển khai Cốt lõi&lt;/strong&gt; — xây dựng và huấn luyện LSTM bằng NumPy và PyTorch trên bài toán bộ nhớ tầm xa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân tích Cổng, GRU và Bẫy thường gặp&lt;/strong&gt; — phân tích hoạt động của các cổng, so sánh LSTM với GRU, các bài báo nền tảng và lưu ý thực hành.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker (tiếng Anh). Theo dõi rõ từng cổng trước khi chuyển sang viết các phép toán tensor tương ứng.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Đối chiếu các phương trình toán học cần khớp với phần cài đặt.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Simple Explanation of GRU (Gated Recurrent Units)&lt;/td&gt;
          &lt;td&gt;Deep Learning Tutorial 37 (Tensorflow &amp;amp; Python)](https://www.youtube.com/watch?v=tOuXgORsXJ4) — codebasics (tiếng Anh). Tài liệu bổ trợ cho phần cài đặt và so sánh GRU.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-01-02-02 Phân tích Cổng, GRU và Bẫy thường gặp</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_01_02_02_Gates_GRU_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_01_02_02_Gates_GRU_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Làm sao biết chiếc LSTM bạn vừa huấn luyện thực sự “học được cách nhớ và quên” chứ không phải chỉ đang ghi nhớ vẹt? Cách trực quan nhất là &lt;strong&gt;mở nắp ca-pô&lt;/strong&gt; và ghi lại giá trị mở của từng cổng \(f_t, i_t, o_t\) qua từng bước thời gian — đồng thời đặt LSTM lên bàn cân trực tiếp với đối thủ gọn nhẹ hơn là &lt;strong&gt;GRU&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-chủ-đề-phân-tích-sâu-về-cổng-gru-và-cạm-bẫy&quot;&gt;Kiến thức cần nhớ: Bốn chủ đề phân tích sâu về Cổng, GRU và Cạm bẫy&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giải phẫu hành vi cổng trên chuỗi nhiễu&lt;/strong&gt;:
Trên chuỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[5, nhiễu, nhiễu, ..., 3]&lt;/code&gt;, một LSTM tốt sẽ mở \(i_1 \approx 1\) khi thấy số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt;, sau đó giữ \(f_t \approx 1, i_t \approx 0\) suốt đoạn nhiễu để khóa kín bộ nhớ, và chỉ mở lại \(i_T, o_T\) ở bước cuối.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh thực chiến LSTM vs. GRU&lt;/strong&gt;:
GRU có ít hơn 25% tham số, huấn luyện nhanh hơn một chút và ít overfitting hơn trên tập nhỏ; LSTM nhỉnh hơn trên các bài toán đếm hoặc phụ thuộc cực dài nhờ tách biệt \(c_t\) khỏi \(h_t\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bốn cạm bẫy kinh điển khi huấn luyện LSTM/GRU&lt;/strong&gt;:
Quên áp dụng Dropout &lt;strong&gt;chỉ giữa các tầng&lt;/strong&gt; (không tùy tiện đặt dropout chuẩn lên kết nối hồi tiếp làm đứt trí nhớ), quên khởi tạo \(b_f &amp;gt; 0\), bỏ quên gradient clipping, và dùng chuỗi quá dài mà không dùng Attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định vị LSTM trong bức tranh tiến hóa&lt;/strong&gt;:
Biết rõ giới hạn của LSTM (tuần tự hóa \(O(T)\) không song song được trên GPU) để hiểu chính xác tại sao Chương 07 (Attention) và Chương 08 (Transformer) ra đời.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-cơ-chế-nội-suy-lồi-của-gru-so-với-lstm-khi-gặp-nhiễu&quot;&gt;Giải thích: Tính tay cơ chế nội suy lồi của GRU so với LSTM khi gặp nhiễu&lt;/h3&gt;

&lt;p&gt;Xét một đơn vị GRU 1 chiều với trạng thái cũ \(h_{t-1} = 5{,}0\) và ứng viên mới chứa tín hiệu nhiễu \(\tilde{h}_t = -1{,}0\). Phương trình cập nhật của GRU là:
\(h_t = (1 - z_t) \cdot h_{t-1} + z_t \cdot \tilde{h}_t\)&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Giá trị cổng cập nhật \(z_t\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Tỷ lệ giữ cũ \((1 - z_t)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Tỷ lệ nhận mới \(z_t\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Trạng thái mới \(h_t\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Ý nghĩa&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(z_t = 0{,}05\)&lt;/strong&gt; (đóng cửa trước nhiễu)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}95\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}05\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}95(5{,}0) + 0{,}05(-1{,}0) = \mathbf{4{,}70}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bỏ qua nhiễu, bảo toàn gần nguyên vẹn số 5&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(z_t = 0{,}50\)&lt;/strong&gt; (trộn đều)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}50(5{,}0) + 0{,}50(-1{,}0) = \mathbf{2{,}00}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Hòa trộn cũ và mới&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(z_t = 0{,}95\)&lt;/strong&gt; (ghi đè hoàn toàn)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}05\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}95\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}05(5{,}0) + 0{,}95(-1{,}0) = \mathbf{-0{,}70}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Xóa ký ức cũ, nhận thông tin mới&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Khác với LSTM (cho phép cả \(f_t\) và \(i_t\) cùng bằng 1 để &lt;em&gt;cộng dồn&lt;/em&gt; không giới hạn), GRU ràng buộc tổng trọng số cũ + mới luôn bằng đúng 1 — gọn nhẹ hơn nhưng cũng làm GRU khó học bài toán “đếm không giới hạn” bằng LSTM.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Phân tích hành vi cổng
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Phân tích Kích hoạt Cổng LSTM&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo LSTM thủ công đơn giản để theo dõi cổng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm_analyze&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo chuỗi: [5, noise, noise, ..., 3]
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_sequence&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;extend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Forward pass theo dõi tất cả cổng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hiddens&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cells&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lstm_analyze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                                         &lt;span class=&quot;n&quot;&gt;return_sequences&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kích hoạt cổng qua thời gian (trung bình qua các chiều ẩn):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Time | Forget | Input | Output | Cell State (avg)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;f_avg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;forget&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;i_avg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;o_avg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;c_avg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cells&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Độ lớn trạng thái tế bào
&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &amp;lt;-- Đầu vào quan trọng&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;or&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f_avg&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i_avg&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;o_avg&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c_avg&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Quan sát:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Cổng forget thường giữ cao (~0.9-1.0) để duy trì bộ nhớ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Cổng input mở cho đầu vào quan trọng (giá trị đầu và cuối)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Cổng output kiểm soát thông tin nào được phơi bày&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Trạng thái tế bào tích lũy thông tin, duy trì độ lớn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Tiếp theo là phần cài đặt GRU để đối chiếu trực tiếp với LSTM:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GRUCell&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    GRU cell — phương án đơn giản hơn so với LSTM.
    
    GRU gộp trạng thái tế bào và trạng thái ẩn, chỉ dùng 2 cổng (so với 3 của LSTM),
    dẫn đến ~25% ít tham số hơn. Thường cho hiệu năng tương đương LSTM
    trong khi huấn luyện nhanh hơn và dễ tinh chỉnh hơn.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Hai cổng thay vì ba
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reset
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Update
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Ứng viên
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;br&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        GRU không có trạng thái tế bào riêng — đơn giản hơn!
        
        Chỉ trả về trạng thái ẩn mới (đóng vai trò cả trạng thái ẩn và tế bào)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;vstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Cổng reset: dùng bao nhiêu quá khứ cho ứng viên
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;r_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;br&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Cổng update: nội suy bao nhiêu giữa cũ và mới
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bz&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Trạng thái ẩn ứng viên (dùng trạng thái trước đã reset)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;combined_reset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;vstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h_tilde&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_reset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Nội suy giữa cũ và mới
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Khi z_t ≈ 0: giữ cũ (h_t ≈ h_prev)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Khi z_t ≈ 1: dùng mới (h_t ≈ h_tilde)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_tilde&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;reset&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;update&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;candidate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_tilde&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# So sánh LSTM vs GRU trên cùng tác vụ
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;So sánh LSTM vs GRU&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LSTM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;lstm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GRUModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gru&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;GRU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gru&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện cả hai
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;gru_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GRUModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Đếm tham số
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lstm_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;gru_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gru_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;LSTM parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GRU parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gru_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GRU có &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gru_params&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm_params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% ít tham số hơn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cả hai đều có thể học phụ thuộc tầm xa hiệu quả.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GRU: Đơn giản hơn, nhanh hơn. LSTM: Linh hoạt hơn, đôi khi tốt hơn trên tác vụ phức tạp.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-các-khái-niệm-liên-quan&quot;&gt;5. Các khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Bước chuyển từ RNN cơ bản sang LSTM phản ánh một hướng tiếp cận phổ biến trong học sâu: phân tích rõ điểm yếu toán học của kiến trúc cũ để thiết kế cải tiến trực tiếp vào cấu trúc mạng. RNN cơ bản gặp khó trên chuỗi dài do gradient biến mất trong BPTT. LSTM giải quyết bằng cách bổ sung trạng thái tế bào với phép cập nhật cộng theo phần tử kết hợp các cổng điều tiết, giúp luồng gradient truyền ổn định hơn.&lt;/p&gt;

&lt;p&gt;Bước tinh giản từ LSTM sang GRU lại minh họa nguyên tắc tối giản hóa kiến trúc khi vẫn bảo toàn cơ chế cốt lõi. GRU đạt hiệu năng tương đương LSTM trên nhiều bài toán nhưng giảm khoảng 25% số tham số và bỏ trạng thái tế bào riêng biệt. Cổng &lt;em&gt;update&lt;/em&gt; đảm nhận vai trò kết hợp giữa cổng quên và cổng vào, trong khi cổng &lt;em&gt;reset&lt;/em&gt; kiểm soát mức độ tham gia của trạng thái trước đó vào ứng viên mới. Trong thực hành, ta thường bắt đầu với GRU vì đơn giản và huấn luyện nhanh hơn, rồi mới chuyển sang LSTM nếu bài toán thực sự cần thêm dung lượng biểu diễn.&lt;/p&gt;

&lt;p&gt;Cơ chế cổng — dùng hàm kích hoạt sigmoid có đầu ra trong khoảng (0, 1) để điều tiết luồng dữ liệu — xuất hiện rộng rãi trong nhiều kiến trúc học sâu khác. Highway Network dùng cổng để kiểm soát kết nối bỏ qua; cơ chế attention dùng trọng số chuẩn hóa để chọn lọc thông tin; Neural Turing Machine dùng cổng để điều khiển thao tác đọc và ghi bộ nhớ. Điểm chung của các thiết kế này là khả năng học quy tắc điều hướng thông tin một cách trơn và khả vi.&lt;/p&gt;

&lt;p&gt;So với cơ chế attention, LSTM giải quyết phụ thuộc tầm xa theo hướng khác. LSTM nén toàn bộ lịch sử vào trạng thái kích thước cố định được cập nhật qua các cổng, giữ độ phức tạp tuyến tính \(O(n)\). Attention cho phép truy cập trực tiếp mọi trạng thái quá khứ mà không qua nút thắt nén cố định, nhưng đổi lại chi phí bậc hai \(O(n^2)\). Với các bài toán xử lý ngôn ngữ có đủ tài nguyên tính toán, khả năng truy cập trực tiếp của Transformer thường chiếm ưu thế; còn với chuỗi rất dài hoặc yêu cầu xử lý trực tuyến với bộ nhớ hạn chế, LSTM và GRU vẫn có chỗ đứng.&lt;/p&gt;

&lt;p&gt;Cơ chế quản lý bộ nhớ trong LSTM cũng gần gũi với các bài toán quản lý bộ nhớ đệm (cache) trong khoa học máy tính: quyết định dữ liệu nào cần lưu, dữ liệu nào đã cũ cần loại bỏ và khi nào cần truy xuất. Thay vì dùng quy tắc cố định như trong hệ điều hành hay CPU, LSTM học chính sách quản lý bộ nhớ trực tiếp từ dữ liệu.&lt;/p&gt;

&lt;p&gt;Nhìn chung, chuỗi phát triển từ RNN sang LSTM rồi Transformer cho thấy quy luật tiến hóa của thiết kế kiến trúc mạng: phát hiện giới hạn qua phân tích, xây dựng cơ chế mới để tháo gỡ, rồi tiếp tục giải quyết các giới hạn mới phát sinh (như tính tuần tự và nút thắt trạng thái cố định).&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.bioinf.jku.at/publications/older/2604.pdf&quot;&gt;“Long Short-Term Memory” (1997)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Sepp Hochreiter, Jürgen Schmidhuber&lt;br /&gt;
Bài báo nền tảng này giới thiệu kiến trúc LSTM kèm phân tích toán học chặt chẽ lý giải vì sao RNN cơ bản thất bại khi học phụ thuộc tầm xa. Hai tác giả chứng minh trong lan truyền ngược theo thời gian, gradient sẽ biến mất hoặc bùng nổ theo hàm mũ trừ khi mạng có cơ chế truyền sai số ổn định. Họ đề xuất cơ chế &lt;em&gt;constant error carousel&lt;/em&gt; (trạng thái tế bào) để duy trì luồng gradient qua nhiều bước thời gian. Dù phải mất nhiều năm sau LSTM mới được ứng dụng rộng rãi khi năng lực tính toán và dữ liệu tăng lên, bài báo này đã đặt nền móng lý thuyết cho gần hai thập kỷ phát triển của mô hình hóa chuỗi.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://doi.org/10.1162/089976600300015015&quot;&gt;“Learning to Forget: Continual Prediction with LSTM” (2000)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Felix A. Gers, Jürgen Schmidhuber, Fred Cummins&lt;br /&gt;
Phiên bản LSTM năm 1997 không có cơ chế xóa trạng thái tế bào nên dễ bị bão hòa khi xử lý chuỗi dài. Bài báo này bổ sung cổng quên (&lt;em&gt;forget gate&lt;/em&gt;), cho phép mạng loại bỏ chọn lọc thông tin lỗi thời khỏi bộ nhớ. Cải tiến gọn nhẹ này nâng cao đáng kể hiệu năng trên các bài toán dự đoán liên tục và nhanh chóng trở thành thành phần chuẩn của mọi cài đặt LSTM.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1406.1078&quot;&gt;“Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Dzmitry Bahdanau, Fethi Bougares, Holger Schwenk, Yoshua Bengio&lt;br /&gt;
Bài báo giới thiệu Gated Recurrent Unit (GRU) như một phương án đơn giản hơn LSTM, đồng thời đề xuất khung kiến trúc encoder-decoder cho dịch máy neuron. Kết quả trên bài toán dịch máy cho thấy hai cổng (&lt;em&gt;reset&lt;/em&gt; và &lt;em&gt;update&lt;/em&gt;) đủ để kiểm soát luồng thông tin hiệu quả với ít tham số hơn và tốc độ huấn luyện nhanh hơn. Khung encoder-decoder từ công trình này cũng trở thành cấu trúc tiêu chuẩn cho nhiều bài toán chuỗi-sang-chuỗi về sau.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1412.3555&quot;&gt;“Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Junyoung Chung, Caglar Gulcehre, KyungHyun Cho, Yoshua Bengio&lt;br /&gt;
Bài báo thực hiện đánh giá thực nghiệm có kiểm soát đầu tiên giữa LSTM và GRU trên nhiều bài toán như mô hình hóa âm nhạc, nhận dạng giọng nói và mô hình ngôn ngữ. Kết quả cho thấy không có kiến trúc nào vượt trội tuyệt đối trong mọi trường hợp, nhưng GRU thường đạt độ chính xác tương đương LSTM với thời gian huấn luyện ngắn hơn. Công trình khẳng định việc chọn kiến trúc cần dựa vào đặc thù dữ liệu, độ dài chuỗi và ngân sách tính toán của từng bài toán cụ thể.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1506.02078&quot;&gt;“Visualizing and Understanding Recurrent Networks” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Andrej Karpathy, Justin Johnson, Li Fei-Fei&lt;br /&gt;
Bài báo phân tích biểu diễn nội bộ của LSTM trên mô hình ngôn ngữ cấp ký tự bằng cách theo dõi kích hoạt của từng đơn vị ẩn và các cổng. Nhóm tác giả phát hiện một số tế bào tự học cách theo dõi dấu ngoặc kép, mức thụt lề mã nguồn hay ranh giới câu mà không cần quy tắc lập trình sẵn. Công trình này góp phần định hình các phương pháp phân tích khả năng diễn giải cho mạng neuron sâu.&lt;/p&gt;

&lt;h2 id=&quot;các-bẫy-phổ-biến-và-thủ-thuật-thực-hành&quot;&gt;Các bẫy phổ biến và thủ thuật thực hành&lt;/h2&gt;

&lt;p&gt;Một lỗi phổ biến khi tự cài đặt LSTM là khởi tạo độ lệch (bias) của cổng quên bằng 0 giống các tham số khác. Khi đó giá trị ban đầu của cổng quên xấp xỉ \(\sigma(0) = 0.5\), khiến mạng quên đi một nửa thông tin trạng thái tế bào ngay sau mỗi bước thời gian và khó học các phụ thuộc tầm xa ở giai đoạn đầu. Giải pháp tiêu chuẩn là mẹo khởi tạo độ lệch cổng quên (&lt;em&gt;forget bias trick&lt;/em&gt;): đặt \(\mathbf{b}_f = \mathbf{1}\) để giá trị ban đầu của cổng quên đạt \(\sigma(0 + 1) \approx 0.73\), thiên về giữ lại thông tin trước rồi mới học cách quên dần khi cần.&lt;/p&gt;

&lt;p&gt;Hiện tượng gradient bùng nổ tuy ít xảy ra hơn so với RNN cơ bản nhưng vẫn có thể xuất hiện. Khi cổng quên tiến sát 1 và cổng vào liên tục mở cho các giá trị ứng viên cùng dấu, trạng thái tế bào cập nhật theo \(c_t = 1 \cdot c_{t-1} + 1 \cdot \tilde{c}_t\) sẽ tăng tuyến tính không bị chặn theo độ dài chuỗi, dẫn đến mất ổn định số học, mất mát tăng vọt hoặc xuất hiện &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;. Bên cạnh cắt ngưỡng gradient (&lt;em&gt;gradient clipping&lt;/em&gt;), các biện pháp hỗ trợ gồm:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Giới hạn giá trị ứng viên bằng hàm \(\tanh\) (đã tích hợp sẵn trong LSTM chuẩn).&lt;/li&gt;
  &lt;li&gt;Sử dụng Layer Normalization để giữ độ lớn trạng thái ổn định.&lt;/li&gt;
  &lt;li&gt;Khởi tạo trọng số phù hợp để tránh bão hòa cổng quá sớm.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Một điểm cần lưu ý khác là sự phối hợp giữa cổng quên và cổng vào. Do hai cổng hoạt động độc lập trong LSTM chuẩn, mô hình đôi khi có thể rơi vào trạng thái bất thường khi đồng thời quên hết thông tin cũ (\(f_t \approx 0\)) mà không ghi thông tin mới (\(i_t \approx 0\)), khiến trạng thái tế bào tiến về 0. GRU tránh tình huống này bằng cách ràng buộc trực tiếp hai trọng số là \(1 - z_t\) và \(z_t\). Khi gỡ lỗi huấn luyện LSTM không hội tụ, kiểm tra phân phối giá trị các cổng (xem chúng có bị kẹt sát 0 hoặc 1 hay không) thường giúp xác định nguyên nhân nhanh chóng.&lt;/p&gt;

&lt;p&gt;Về lựa chọn giữa LSTM và GRU, kinh nghiệm thực tế là bắt đầu bằng GRU để tận dụng tốc độ huấn luyện nhanh và ít tham số hơn. Nếu hiệu năng chững lại trên bài toán có dữ liệu lớn, chuỗi dài hoặc cấu trúc thời gian phức tạp, hãy thử chuyển sang LSTM để kiểm chứng xem trạng thái tế bào tách biệt có cải thiện kết quả hay không.&lt;/p&gt;

&lt;p&gt;Khi xếp chồng nhiều lớp LSTM, có thể áp dụng dropout lên đầu ra trạng thái ẩn truyền giữa các lớp, nhưng không nên áp dụng trực tiếp lên trạng thái tế bào hoặc kết nối hồi quy trong cùng một lớp theo cách thông thường. Tỷ lệ dropout cho LSTM thường nhỏ hơn mạng feedforward (khoảng 0.2 đến 0.3 thay vì 0.5) vì tỷ lệ quá cao sẽ làm gián đoạn luồng thông tin xuyên suốt chuỗi.&lt;/p&gt;

&lt;p&gt;LSTM hai chiều xử lý chuỗi theo cả chiều xuôi và chiều ngược rồi ghép hai trạng thái ẩn ở mỗi bước: \(\mathbf{h}_t = [\overrightarrow{\mathbf{h}}_t; \overleftarrow{\mathbf{h}}_t]\). Thiết kế này tăng gấp đôi số tham số và chi phí tính toán nhưng mang lại biểu diễn đầy đủ hơn cho các bài toán có sẵn toàn bộ đầu vào như dịch câu hoàn chỉnh hoặc nhận dạng đoạn âm thanh đã ghi sẵn; ngược lại, không thể dùng cho dự đoán trực tuyến thời gian thực hay sinh tự hồi quy.&lt;/p&gt;

&lt;p&gt;Cuối cùng, trực quan hóa giá trị kích hoạt của các cổng \(f_t\), \(i_t\), \(o_t\) theo từng bước thời gian là công cụ phân tích rất hữu ích. Quan sát thời điểm cổng quên hạ thấp (ví dụ tại ranh giới câu), cổng vào mở (tại các từ khóa chính) hay cổng ra kích hoạt giúp vừa gỡ lỗi huấn luyện, vừa kiểm chứng xem mô hình đã học đúng cấu trúc của dữ liệu hay chưa.&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính&quot;&gt;Điểm chính&lt;/h2&gt;

&lt;p&gt;LSTM khắc phục hiện tượng gradient biến mất của RNN cơ bản bằng cách bổ sung trạng thái tế bào (&lt;em&gt;cell state&lt;/em&gt;) với cơ chế cập nhật cộng theo phần tử được điều khiển bởi ba cổng (&lt;em&gt;forget&lt;/em&gt;, &lt;em&gt;input&lt;/em&gt;, &lt;em&gt;output&lt;/em&gt;). Cấu trúc này giúp gradient lan truyền ổn định qua hàng trăm bước thời gian và mang lại hiệu quả cao cho nhiều bài toán dữ liệu chuỗi. GRU tinh giản thiết kế của LSTM xuống còn hai cổng và một trạng thái duy nhất, thường đạt hiệu năng tương đương với chi phí tính toán thấp hơn. Hiểu rõ vai trò của từng cổng và lý do tồn tại của phép cập nhật cộng là chìa khóa để sử dụng và gỡ lỗi hiệu quả các mô hình hồi quy có cổng.&lt;/p&gt;

&lt;p&gt;Thành công của LSTM cũng cho thấy một bài học quan trọng trong thiết kế mạng sâu: phân tích chặt chẽ động lực gradient giúp tạo ra những thay đổi kiến trúc giải quyết tận gốc các giới hạn huấn luyện.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Simple Explanation of GRU (Gated Recurrent Units)&lt;/td&gt;
          &lt;td&gt;Deep Learning Tutorial 37 (Tensorflow &amp;amp; Python)](https://www.youtube.com/watch?v=tOuXgORsXJ4) — codebasics (tiếng Anh). Giải thích cách GRU gộp quyết định quên và ghi mới, khớp trực tiếp với phần so sánh trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker (tiếng Anh). Ôn lại chi tiết từng cổng LSTM làm nền cho phần đối chiếu với GRU.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Làm rõ cơ chế hoạt động và giới hạn dung lượng của trạng thái tế bào khi chuỗi quá dài.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-01-02-01 Triển khai Cốt lõi LSTM</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_01_02_01_LSTM_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_01_02_01_LSTM_Core_Code</id>
   <content type="html">&lt;p&gt;Đọc 6 phương trình của LSTM trên slide rất dễ thấy “hiển nhiên”, nhưng chỉ khi bạn tự gõ từng dòng forward và backward của một &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LSTMCell&lt;/code&gt; thuần NumPy — rồi đối chiếu nó với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM&lt;/code&gt; trên bài toán nhớ phần tử đầu qua hàng chục bước nhiễu — bạn mới thực sự chạm tay vào cơ chế hoạt động bên trong của bộ nhớ có cổng.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-kỹ-thuật-cốt-lõi-trong-mã-nguồn-lstm&quot;&gt;Kiến thức cần nhớ: Bốn kỹ thuật cốt lõi trong mã nguồn LSTM&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Ghép nối đầu vào \(z_t = [h_{t-1}; x_t]\)&lt;/strong&gt;:
Thay vì viết hai phép nhân tách biệt \(W_f h_{t-1} + U_f x_t\), ghép nối vector đầu vào thành \([h_{t-1}, x_t] \in \mathbb{R}^{d_h + d_x}\) giúp mã nguồn gọn gàng, sạch sẽ và giảm lỗi chỉ số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tách 4 cổng từ một phép nhân tuyến tính lớn&lt;/strong&gt;:
Tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gates = z_t @ W_all + b_all&lt;/code&gt; (kích thước \(4 d_h\)), sau đó tách làm 4 phần bằng nhau cho \(f_t, i_t, \tilde{c}_t, o_t\) — đúng cách các thư viện DL tăng tốc trên phần cứng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền ngược qua cả &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dh_next&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dc_next&lt;/code&gt;&lt;/strong&gt;:
Khác với RNN chỉ truyền ngược 1 biến &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dh_next&lt;/code&gt;, LSTM phải truyền ngược đồng thời &lt;strong&gt;cặp&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(dh_next, dc_next)&lt;/code&gt;. Đặc biệt, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dc&lt;/code&gt; cộng dồn từ hai nguồn: từ nhánh đầu ra \(h_t = o_t \odot \tanh(c_t)\) và từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dc_next&lt;/code&gt; của bước tương lai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xây dựng tác vụ kiểm chứng phụ thuộc tầm xa (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;first + last&lt;/code&gt;)&lt;/strong&gt;:
Một bài toán đồ chơi nhưng sắc bén: chuỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[a, noise, noise, ..., b]&lt;/code&gt; dài 20–50 bước có đích là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;a + b&lt;/code&gt;. RNN thuần sẽ dự đoán gần như ngẫu nhiên khi chiều dài tăng, trong khi LSTM giảm loss xuống gần 0.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-dòng-lan-truyền-ngược-qua-1-bước-của-cell-state-dc_t-to-dc_t-1-df_t-di_t&quot;&gt;Giải thích: Tính tay dòng lan truyền ngược qua 1 bước của Cell State (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dc_t&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dc_{t-1}&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;df_t&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;di_t&lt;/code&gt;)&lt;/h3&gt;

&lt;p&gt;Giả sử tại bước \(t\) trong lượt backward, ta đã có các giá trị forward: \(c_{t-1} = 2{,}0, \; f_t = 0{,}8, \; i_t = 0{,}5, \; \tilde{c}_t = -0{,}6\), và tổng gradient đổ vào trạng thái tế bào \(c_t\) là \(dc_t = \frac{\partial \mathcal{L}}{\partial c_t} = 1{,}0\). Từ \(c_t = f_t \odot c_{t-1} + i_t \odot \tilde{c}_t\), áp dụng quy tắc đạo hàm từng biến:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gradient truyền thẳng về quá khứ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dc_{t-1}&lt;/code&gt;&lt;/strong&gt;:
\(dc_{t-1} = dc_t \cdot f_t = 1{,}0 \times 0{,}8 = \mathbf{0{,}80}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient cho cổng quên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;df_t&lt;/code&gt;&lt;/strong&gt; (trước sigmoid):
\(df_t = dc_t \cdot c_{t-1} = 1{,}0 \times 2{,}0 = \mathbf{2{,}00}\)
Qua đạo hàm sigmoid \(\sigma&apos;(a_f) = f_t(1 - f_t) = 0{,}8 \times 0{,}2 = 0{,}16 \Rightarrow da_f = 2{,}00 \times 0{,}16 = \mathbf{0{,}32}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient cho cổng nhập &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;di_t&lt;/code&gt;&lt;/strong&gt; và ứng viên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;d\tilde{c}_t&lt;/code&gt;:
\(di_t = dc_t \cdot \tilde{c}_t = 1{,}0 \times (-0{,}6) = \mathbf{-0{,}60}, \qquad d\tilde{c}_t = dc_t \cdot i_t = 1{,}0 \times 0{,}5 = \mathbf{0{,}50}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Hãy nhìn vào Bước 1: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dc_{t-1}&lt;/code&gt; chỉ đơn giản bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dc_t * f_t&lt;/code&gt; — không hề có ma trận trọng số hay đạo hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tanh&lt;/code&gt; nào chen ngang trên trục chính của băng chuyền tế bào!&lt;/p&gt;

&lt;h2 id=&quot;4-đoạn-code&quot;&gt;4. Đoạn Code&lt;/h2&gt;

&lt;p&gt;Phần này trình bày cách cài đặt LSTM từ đầu bằng NumPy để quan sát rõ từng phép toán của các cổng, sau đó đối chiếu với phiên bản tối ưu bằng PyTorch:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMCell&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Một LSTM cell triển khai tính toán của một bước thời gian.
    
    Bản triển khai này làm tường minh mọi thao tác. Framework hiện đại
    hợp nhất các thao tác này để hiệu năng, nhưng mục tiêu của ta là hiểu,
    không phải tốc độ. Ta sẽ thấy chính xác cổng điều tiết luồng thông tin ra sao.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Khởi tạo LSTM cell với khởi tạo trọng số cẩn thận.
        
        Ta dùng khởi tạo Xavier/Glorot scale cho sigmoid và tanh.
        Lược đồ khởi tạo này được thiết kế đặc biệt để duy trì
        scale kích hoạt và gradient hợp lý, ngăn cả biến mất
        lẫn bùng nổ sớm trong huấn luyện.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Chiều đầu vào kết hợp (ẩn + đầu vào)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Khởi tạo trọng số cho bốn cổng
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Dùng khởi tạo Xavier: scale theo 1/√(combined_size)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wi&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;WC&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Khởi tạo bias
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Bias cổng forget thường khởi tạo = 1 để khuyến khích nhớ ban đầu
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Đây gọi là &quot;forget bias trick&quot; — bắt đầu bằng cách nhớ mọi thứ
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Bắt đầu với cổng forget cao!
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bi&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bC&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sigmoid ổn định số&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                       &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Một bước thời gian LSTM.
        
        x_t: đầu vào hiện tại (input_size, 1)
        h_prev: trạng thái ẩn trước (hidden_size, 1)
        c_prev: trạng thái tế bào trước (hidden_size, 1)
        
        Returns:
            h_t: trạng thái ẩn mới
            c_t: trạng thái tế bào mới
            gates: dictionary các giá trị cổng (để phân tích/debug)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Nối trạng thái ẩn trước và đầu vào hiện tại
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Vectơ kết hợp này ảnh hưởng mọi cổng
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;vstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính tất cả cổng
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Mỗi cổng là hàm sigmoid học được của đầu vào kết hợp
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;f_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cổng forget
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;i_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wi&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cổng input
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;C_tilde&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;WC&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bC&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Giá trị ứng viên
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;o_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cổng output
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Cập nhật trạng thái tế bào: quên cũ, thêm mới
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Đây là phương trình THEN CHỐT của LSTM
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Lưu ý: phi tuyến tối thiểu, chủ yếu tổ hợp tuyến tính
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;c_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C_tilde&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính trạng thái ẩn mới từ trạng thái tế bào
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# tanh nén trạng thái tế bào không giới hạn về [-1, 1]
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# cổng output điều tiết những gì được phơi bày
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;o_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Trả về trạng thái và cổng (cổng hữu ích để trực quan hóa/debug)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;forget&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;o_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;candidate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C_tilde&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Mạng LSTM đầy đủ cho xử lý chuỗi.
    
    Bọc LSTMCell để xử lý toàn bộ chuỗi, duy trì trạng thái qua
    các bước thời gian. Đây là LSTM hoàn chỉnh như dùng trong thực tế.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cell&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMCell&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Chiếu đầu ra (ánh xạ trạng thái ẩn sang dự đoán)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;return_sequences&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Xử lý toàn bộ chuỗi.
        
        inputs: list các vectơ đầu vào [x_1, ..., x_T]
        return_sequences: nếu True, trả về đầu ra ở mọi bước thời gian
                         nếu False, chỉ trả về đầu ra cuối
        
        Returns:
            outputs: dự đoán ở mỗi bước thời gian (nếu return_sequences=True)
                     hoặc chỉ dự đoán cuối (nếu False)
            hidden_states: tất cả trạng thái ẩn [h_0, ..., h_T]
            cell_states: tất cả trạng thái tế bào [c_0, ..., c_T]
            all_gates: giá trị cổng ở mỗi bước thời gian (để phân tích)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Khởi tạo trạng thái về zero
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Theo dõi tiến hóa qua thời gian
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cell_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Xử lý chuỗi từng bước
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật LSTM cell
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cell&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;cell_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Tính đầu ra từ trạng thái ẩn
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;y_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;return_sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cell_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Với phân loại chuỗi, chỉ dùng đầu ra cuối
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cell_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Minh họa LSTM học phụ thuộc tầm xa
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;LSTM: Học Phụ thuộc Tầm xa&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo tác vụ đòi hỏi bộ nhớ dài hạn
# Nhớ số đầu, bỏ qua các số giữa, dự đoán first + last
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_memory_task&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Tác vụ: Cho chuỗi [a, x, x, x, ..., x, b], dự đoán a + b
    
    Điều này đòi hỏi nhớ &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; qua seq_length-2 giá trị xen giữa,
    đúng loại phụ thuộc tầm xa mà RNN vanilla gặp khó.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;targets_list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Số đầu và cuối ngẫu nhiên
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;first&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;last&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Điền giữa bằng nhiễu
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;sequence&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;first&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])]&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;last&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]))&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;first&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;last&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;targets_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets_list&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo LSTM và dữ liệu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_memory_task&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vòng huấn luyện đơn giản (gradient descent trên dataset nhỏ)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện LSTM trên tác vụ phụ thuộc tầm xa...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tác vụ: Nhớ số đầu qua 13 số nhiễu, cộng với số cuối&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Xử lý từng chuỗi
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hiddens&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cells&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lstm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;return_sequences&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Loss (MSE)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Để minh họa, ta bỏ qua triển khai backward pass
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# (BPTT cho LSTM phức tạp — framework hiện đại xử lý)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Trong thực tế, dùng PyTorch!
&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Average Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lưu ý: Backpropagation LSTM đầy đủ phức tạp — dùng PyTorch trong thực tế!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Hãy xem triển khai của PyTorch...&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Triển khai LSTM PyTorch
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    LSTM dùng triển khai tối ưu của PyTorch.
    
    LSTM của PyTorch được tối ưu cao, dùng kernel cuDNN trên GPU
    cho hiệu năng tối đa. Nó xử lý tự động mọi tính toán cổng,
    quản lý trạng thái, và backpropagation.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LSTMNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Module LSTM của PyTorch
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# num_layers &amp;gt; 1 xếp chồng LSTM (đầu ra lớp này làm đầu vào lớp sau)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# dropout giữa các lớp giúp regularize LSTM xếp chồng
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LSTM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                           &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lớp đầu ra
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (batch, seq_len, input_size)
        hidden: tuple tùy chọn (h_0, c_0)
        
        Returns:
            output: (batch, seq_len, output_size) nếu return_sequences
                    hoặc (batch, output_size) nếu không
            (h_n, c_n): trạng thái ẩn và tế bào cuối
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# LSTM trả về:
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# - lstm_out: trạng thái ẩn ở mọi bước thời gian
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# - (h_n, c_n): trạng thái ẩn và tế bào cuối cho mọi lớp
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;lstm_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;lstm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Dùng bước thời gian cuối cho phân loại chuỗi
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# hoặc mọi bước thời gian cho chuỗi-sang-chuỗi
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;final_hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lstm_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Bước thời gian cuối
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;final_hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện trên tác vụ bộ nhớ
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện PyTorch LSTM trên Tác vụ Bộ nhớ Tầm xa&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Chuyển dữ liệu thành tensor
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;prepare_torch_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Chuyển list chuỗi thành tensor theo batch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Tìm độ dài max (để pad)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Pad chuỗi và stack
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Chuyển chuỗi thành tensor và pad
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;seq_tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; 
                                  &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Stack thành tensor theo batch
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (n_samples, seq_len, 1)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (n_samples, 1)
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;prepare_torch_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training data shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (200, 15, 1)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tạo model
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MSELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vòng huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;300&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# BPTT qua LSTM diễn ra tự động ở đây
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Gradient clipping (thực hành tốt cho RNN/LSTM)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip_grad_norm_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_norm&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm thử trên ví dụ mới
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kiểm thử Khả năng Bộ nhớ LSTM&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Tạo chuỗi kiểm thử
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;test_cases&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;8.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;9.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;10.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_sum&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_cases&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;seq_tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;First: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Last: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  True sum: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_sum&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Predicted: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Error: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;LSTM đã học thành công nhớ giá trị đầu qua nhiều bước!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Điều này minh họa ưu thế so với RNN vanilla cho phụ thuộc tầm xa.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Phần tiếp theo sẽ phân tích giá trị kích hoạt của các cổng, cài đặt GRU và tổng hợp các bẫy thường gặp trong bài &lt;strong&gt;Phân tích Cổng, GRU và Bẫy thường gặp&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker (tiếng Anh). Minh họa từng cổng dưới dạng phép biến đổi tuyến tính kết hợp sigmoid hoặc tanh, khớp với ô LSTM được cài đặt trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Hữu ích để phân biệt rõ tensor trạng thái tế bào và trạng thái ẩn trước khi lập trình.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Simple Explanation of GRU (Gated Recurrent Units)&lt;/td&gt;
          &lt;td&gt;Deep Learning Tutorial 37 (Tensorflow &amp;amp; Python)](https://www.youtube.com/watch?v=tOuXgORsXJ4) — codebasics (tiếng Anh). Giới thiệu ô GRU gọn hơn để thực hành tiếp sau khi đã hoàn thành ô LSTM.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-01-01 Lý thuyết LSTM và GRU</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_01_01_LSTM_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_01_01_LSTM_Theory</id>
   <content type="html">&lt;p&gt;Vì sao trong ô LSTM, cổng quên \(f_t\) lại nằm ngay phép nhân đầu tiên với \(c_{t-1}\), còn cổng xuất \(o_t\) lại đặt ở tận bước cuối cùng sau \(\tanh(c_t)\)? Mỗi phép toán trong 6 phương trình kinh điển của LSTM (và 4 phương trình của GRU) đều có một nhiệm vụ toán học không thể hoán đổi — tạo nên bộ máy điều phối bộ nhớ ngắn hạn và dài hạn tinh vi nhất trước kỷ nguyên Attention.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-toán-học-của-lstm-và-gru&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột toán học của LSTM và GRU&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tách biệt Bộ nhớ dài hạn (\(c_t\)) và Bộ nhớ làm việc (\(h_t\))&lt;/strong&gt;:
\(c_t\) lưu trữ thông tin bền bỉ qua nhiều bước mà không bị nén phi tuyến liên tục; \(h_t = o_t \odot \tanh(c_t)\) chỉ trích xuất phần thông tin đang cần dùng tại ngay bước \(t\) để dự đoán đầu ra.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Động lực học của 3 cổng (Forget – Input – Output)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(f_t = \sigma(W_f [h_{t-1}, x_t] + b_f)\): xóa bỏ ký ức lỗi thời (ví dụ khi đổi chủ ngữ mới trong đoạn văn).&lt;/li&gt;
      &lt;li&gt;\(i_t = \sigma(W_i [h_{t-1}, x_t] + b_i)\): mở van ghi thông tin mới \(\tilde{c}_t = \tanh(W_c [h_{t-1}, x_t] + b_c)\).&lt;/li&gt;
      &lt;li&gt;\(o_t = \sigma(W_o [h_{t-1}, x_t] + b_o)\): điều tiết lượng thông tin bộc lộ ra ngoài.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế cổng ghép của GRU (Update \(z_t\) và Reset \(r_t\))&lt;/strong&gt;:
GRU thay cặp \((f_t, i_t)\) độc lập bằng một phép nội suy lồi duy nhất: \(h_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t\) — hễ tăng ghi mới thì tự động giảm giữ cũ!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cầu nối Constant Error Carousel (CEC)&lt;/strong&gt;:
Trong lan truyền ngược qua \(c_t\), đạo hàm chủ yếu là phép nhân điểm từng phần tử với \(f_t\) thay vì nhân lặp ma trận đặc \(W_{hh}\) và đạo hàm \(\tanh&apos;\) — triệt tiêu gốc rễ của bài toán gradient biến mất.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-trọn-vẹn-1-bước-truyền-xuôi-của-một-ô-lstm-1-chiều&quot;&gt;Giải thích: Tính tay trọn vẹn 1 bước truyền xuôi của một ô LSTM 1 chiều&lt;/h3&gt;

&lt;p&gt;Giả sử ta có một ô LSTM vô hướng tại bước \(t\) với trạng thái cũ \(c_{t-1} = 2{,}0\) và các giá trị cổng vừa tính ra từ đầu vào mới là:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Cổng quên \(f_t = 0{,}8\) (giữ 80% ký ức cũ)&lt;/li&gt;
  &lt;li&gt;Cổng nhập \(i_t = 0{,}5\) (nhận 50% thông tin mới)&lt;/li&gt;
  &lt;li&gt;Ứng viên nội dung mới \(\tilde{c}_t = -0{,}6\)&lt;/li&gt;
  &lt;li&gt;Cổng xuất \(o_t = 0{,}9\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ta tính lần lượt từng bước:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật trạng thái tế bào (Cell State)&lt;/strong&gt;:
\(c_t = f_t \cdot c_{t-1} + i_t \cdot \tilde{c}_t = (0{,}8)(2{,}0) + (0{,}5)(-0{,}6) = 1{,}6 - 0{,}3 = \mathbf{1{,}30}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nén tế bào qua \(\tanh\)&lt;/strong&gt;:
\(\tanh(1{,}30) \approx \mathbf{0{,}8617}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính trạng thái ẩn đầu ra (Hidden State)&lt;/strong&gt;:
\(h_t = o_t \cdot \tanh(c_t) = 0{,}9 \times 0{,}8617 \approx \mathbf{0{,}7755}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Hãy thử so sánh: nếu bước sau gặp một chuỗi ký tự nhiễu, mạng chỉ cần đẩy \(i_{t+1} \approx 0\) và \(f_{t+1} \approx 1\) thì \(c_{t+1} \approx 1{,}30\) được bảo toàn nguyên vẹn như đặt trong két sắt!&lt;/p&gt;

&lt;h1 id=&quot;long-short-term-memory-khắc-phục-hiện-tượng-gradient-biến-mất&quot;&gt;Long Short-Term Memory: Khắc phục hiện tượng Gradient biến mất&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter06/lstm_architecture.png&quot; alt=&quot;LSTM Cell Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Cấu trúc chi tiết của một ô LSTM với các cổng điều khiển. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Mạng Long Short-Term Memory (LSTM) là một trong những bước tiến kiến trúc quan trọng nhất của dòng mạng neuron hồi quy. Do Hochreiter và Schmidhuber đề xuất năm 1997, LSTM được thiết kế để khắc phục hiện tượng gradient biến mất trong RNN cơ bản, giúp mô hình học được các phụ thuộc kéo dài hàng trăm hoặc hàng nghìn bước thời gian. Dù sơ đồ khối ban đầu trông khá phức tạp với nhiều cổng (&lt;em&gt;gate&lt;/em&gt;) và trạng thái tế bào (&lt;em&gt;cell state&lt;/em&gt;), mỗi thành phần đều đảm nhận một chức năng rõ ràng trong việc điều phối luồng thông tin theo thời gian.&lt;/p&gt;

&lt;p&gt;Để thấy rõ vai trò của LSTM, cần nhìn lại hạn chế của RNN cơ bản. Trong thuật toán lan truyền ngược theo thời gian (BPTT), gradient phải đi qua chuỗi phép nhân lặp lại với ma trận trọng số hồi quy và đạo hàm của hàm kích hoạt. Khi các thừa số này nhỏ hơn 1 (chẳng hạn đạo hàm hàm tanh khi đầu ra bão hòa), gradient suy giảm theo hàm mũ theo số bước thời gian. Vì vậy, RNN cơ bản rất khó học các phụ thuộc tầm xa, chẳng hạn liên kết một chủ ngữ ở đầu đoạn với động từ ở cuối đoạn.&lt;/p&gt;

&lt;p&gt;Giải pháp của LSTM tập trung vào một ý tưởng trực diện: tạo một đường truyền riêng cho thông tin dài hạn gọi là &lt;strong&gt;trạng thái tế bào&lt;/strong&gt; (&lt;em&gt;cell state&lt;/em&gt;), chạy song song với trạng thái ẩn. Trạng thái tế bào cho phép thông tin đi qua nhiều bước thời gian mà chỉ chịu các phép cập nhật tuyến tính theo phần tử, tránh các phép biến đổi phi tuyến lặp lại gây suy giảm gradient. Có thể xem trạng thái tế bào như đường truyền bộ nhớ dài hạn, trong khi trạng thái ẩn phục vụ tính toán tại từng thời điểm.&lt;/p&gt;

&lt;p&gt;Tuy nhiên, chỉ riêng trạng thái tế bào là chưa đủ; mô hình cần cơ chế quyết định thông tin nào cần giữ lại, thông tin nào cần ghi mới và thông tin nào cần đưa ra ngoài. Đó là nhiệm vụ của ba &lt;strong&gt;cổng&lt;/strong&gt; (&lt;em&gt;gate&lt;/em&gt;) — &lt;em&gt;forget&lt;/em&gt;, &lt;em&gt;input&lt;/em&gt; và &lt;em&gt;output&lt;/em&gt; — mỗi cổng là một lớp mạng dùng hàm kích hoạt sigmoid cho giá trị trong khoảng [0, 1]. Hàm sigmoid vừa trơn và khả vi để huấn luyện bằng lan truyền ngược, vừa có thể diễn giải như tỷ lệ kiểm soát: giữ lại bao nhiêu, thêm mới bao nhiêu và trích xuất bao nhiêu.&lt;/p&gt;

&lt;p&gt;Điểm mạnh của LSTM nằm ở sự phối hợp giữa ba cổng này để tạo thành một cơ chế quản lý bộ nhớ học được từ dữ liệu. Cổng quên loại bỏ thông tin đã lỗi thời khỏi trạng thái tế bào; cổng vào chọn lọc thông tin mới cần lưu; cổng ra kiểm soát phần thông tin nào được đưa sang trạng thái ẩn cho bước tính toán hiện tại. Toàn bộ quá trình này được điều khiển qua các tham số học được trong huấn luyện.&lt;/p&gt;

&lt;p&gt;LSTM đóng vai trò chủ đạo trong mô hình hóa chuỗi từ cuối thập niên 1990 đến giữa thập niên 2010, thúc đẩy nhiều tiến bộ trong dịch máy, nhận dạng giọng nói và nhận dạng chữ viết tay. Ngay cả khi Transformer đã trở thành lựa chọn phổ biến cho xử lý ngôn ngữ tự nhiên, LSTM vẫn có giá trị thực tiễn trong các bài toán yêu cầu bộ nhớ tuyến tính (\(O(n)\) so với \(O(n^2)\) của attention đầy đủ) hoặc xử lý trực tuyến từng bước.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Tại mỗi bước thời gian \(t\), với đầu vào \(\mathbf{x}_t \in \mathbb{R}^{d_x}\), trạng thái ẩn trước đó \(\mathbf{h}_{t-1} \in \mathbb{R}^{d_h}\) và trạng thái tế bào trước đó \(\mathbf{c}_{t-1} \in \mathbb{R}^{d_h}\), LSTM tính hai trạng thái mới \(\mathbf{h}_t\) và \(\mathbf{c}_t\) theo trình tự sau.&lt;/p&gt;

&lt;p&gt;Trước hết, ta ghép trạng thái ẩn trước đó với đầu vào hiện tại thành một vectơ duy nhất:&lt;/p&gt;

\[\mathbf{z}_t = [\mathbf{h}_{t-1}; \mathbf{x}_t] \in \mathbb{R}^{d_h + d_x}\]

&lt;p&gt;Vectơ ghép này là đầu vào chung của mọi cổng, giúp từng cổng đưa ra quyết định dựa trên cả dữ liệu hiện tại (\(\mathbf{x}_t\)) lẫn ngữ cảnh tích lũy trước đó (\(\mathbf{h}_{t-1}\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cổng quên (&lt;em&gt;forget gate&lt;/em&gt;)&lt;/strong&gt; xác định tỷ lệ thông tin cần giữ lại từ trạng thái tế bào cũ:&lt;/p&gt;

\[\mathbf{f}_t = \sigma(\mathbf{W}_f \mathbf{z}_t + \mathbf{b}_f) = \sigma(\mathbf{W}_f \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_f)\]

&lt;p&gt;trong đó \(\mathbf{W}_f \in \mathbb{R}^{d_h \times (d_h + d_x)}\) và \(\mathbf{b}_f \in \mathbb{R}^{d_h}\). Hàm sigmoid đảm bảo mỗi phần tử \(f_t^{(i)} \in (0, 1)\): khi \(f_t^{(i)} \approx 1\), thông tin ở chiều \(i\) được giữ gần như nguyên vẹn; khi \(f_t^{(i)} \approx 0\), thông tin ở chiều đó gần như bị xóa. Ví dụ, khi bắt đầu một câu mới, mô hình có thể học cách giảm cổng quên để xóa thông tin hòa hợp chủ–vị của câu trước.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cổng vào (&lt;em&gt;input gate&lt;/em&gt;)&lt;/strong&gt; và &lt;strong&gt;trạng thái ứng viên&lt;/strong&gt; kiểm soát phần thông tin mới được bổ sung vào bộ nhớ:&lt;/p&gt;

\[\mathbf{i}_t = \sigma(\mathbf{W}_i \mathbf{z}_t + \mathbf{b}_i) = \sigma(\mathbf{W}_i \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_i)\]

\[\tilde{\mathbf{c}}_t = \tanh(\mathbf{W}_C \mathbf{z}_t + \mathbf{b}_C) = \tanh(\mathbf{W}_C \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_C)\]

&lt;p&gt;Ứng viên \(\tilde{\mathbf{c}}_t\) dùng hàm \(\tanh\) để tạo các giá trị cập nhật trong khoảng \((-1, 1)\), còn cổng vào \(\mathbf{i}_t\) điều tiết tỷ lệ cập nhật thực sự được ghi vào trạng thái tế bào. Khi gặp thông tin quan trọng (như chủ ngữ của câu), cổng vào mở (\(i_t^{(i)} \approx 1\)); khi gặp từ ít thông tin, cổng vào đóng (\(i_t^{(i)} \approx 0\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cập nhật trạng thái tế bào&lt;/strong&gt; kết hợp hai quá trình quên thông tin cũ và ghi thông tin mới:&lt;/p&gt;

\[\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t\]

&lt;p&gt;Đây là phương trình trung tâm của LSTM. Tích Hadamard (nhân theo phần tử) \(\mathbf{f}_t \odot \mathbf{c}_{t-1}\) chọn lọc phần thông tin cũ cần giữ, còn \(\mathbf{i}_t \odot \tilde{\mathbf{c}}_t\) bổ sung thông tin mới. Vì phép cập nhật mang dạng cộng theo phần tử, không nhân qua ma trận trọng số hồi quy và không đi qua hàm \(\tanh\) ở mỗi bước, luồng gradient truyền qua trạng thái tế bào ổn định hơn nhiều so với RNN cơ bản.&lt;/p&gt;

&lt;p&gt;Cụ thể, đạo hàm trực tiếp của trạng thái tế bào qua một bước thời gian là:&lt;/p&gt;

\[\frac{\partial \mathbf{c}_t}{\partial \mathbf{c}_{t-1}} = \mathbf{f}_t\]

&lt;p&gt;Nếu mô hình giữ \(f_t^{(i)} = 0.99\) qua \(T = 100\) bước thời gian, thừa số gradient theo chiều \(i\) bằng \((0.99)^{100} \approx 0.37\) — vẫn duy trì đáng kể, trái ngược với RNN cơ bản nơi đạo hàm:&lt;/p&gt;

\[\frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-1}} = \text{diag}(\tanh&apos;(\mathbf{z}_t)) \mathbf{W}_{hh}\]

&lt;p&gt;thường suy giảm xuống cỡ \(10^{-30}\) do tích lặp lại của cả ma trận trọng số và đạo hàm hàm \(\tanh\) bị bão hòa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cổng ra (&lt;em&gt;output gate&lt;/em&gt;)&lt;/strong&gt; quyết định phần nào của trạng thái tế bào được đưa ra trạng thái ẩn \(\mathbf{h}_t\):&lt;/p&gt;

\[\mathbf{o}_t = \sigma(\mathbf{W}_o \mathbf{z}_t + \mathbf{b}_o) = \sigma(\mathbf{W}_o \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_o)\]

\[\mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t)\]

&lt;p&gt;Trạng thái tế bào được đưa qua hàm \(\tanh\) trước khi nhân với cổng ra nhằm chuẩn hóa giá trị về khoảng \([-1, 1]\), bởi các phép cộng lặp lại có thể khiến \(\mathbf{c}_t\) tăng lớn không bị chặn (chẳng hạn \(c_t = c_{t-1} + 0.1\) sau 1000 bước sẽ đạt \(c_{1000} = 100\)). Cổng ra giúp chọn lọc những phần thông tin liên quan cho dự đoán tại thời điểm hiện tại trong khi vẫn giữ phần còn lại trong bộ nhớ cho các bước sau.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Số lượng tham số và chi phí tính toán&lt;/strong&gt;: Với chiều đầu vào \(d_x\) và chiều ẩn \(d_h\), LSTM có bốn nhóm trọng số (\(\mathbf{W}_f, \mathbf{W}_i, \mathbf{W}_C, \mathbf{W}_o\)), mỗi nhóm gồm ma trận kích thước \(d_h \times (d_h + d_x)\) và vectơ độ lệch kích thước \(d_h\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Cổng quên: \((d_h + d_x) \times d_h + d_h\) tham số&lt;/li&gt;
  &lt;li&gt;Cổng vào: \((d_h + d_x) \times d_h + d_h\) tham số&lt;/li&gt;
  &lt;li&gt;Trạng thái ứng viên: \((d_h + d_x) \times d_h + d_h\) tham số&lt;/li&gt;
  &lt;li&gt;Cổng ra: \((d_h + d_x) \times d_h + d_h\) tham số&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tổng cộng LSTM có \(4[(d_h + d_x) \times d_h + d_h]\) tham số và chi phí mỗi bước là \(O(d_h^2 + d_h d_x)\), gấp khoảng 4 lần RNN cơ bản. Đổi lại, mô hình đạt luồng gradient ổn định hơn và khả năng học phụ thuộc tầm xa tốt hơn đáng kể.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gated Recurrent Unit (GRU)&lt;/strong&gt;, do Cho và cộng sự đề xuất năm 2014, tinh giản LSTM bằng cách gộp trạng thái tế bào với trạng thái ẩn và chỉ dùng hai cổng (giảm khoảng 25% số tham số):&lt;/p&gt;

&lt;p&gt;\(\mathbf{r}_t = \sigma(\mathbf{W}_r \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t])\) (cổng &lt;em&gt;reset&lt;/em&gt;: kiểm soát mức độ sử dụng trạng thái cũ khi tính ứng viên)&lt;/p&gt;

&lt;p&gt;\(\mathbf{z}_t = \sigma(\mathbf{W}_z \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t])\) (cổng &lt;em&gt;update&lt;/em&gt;: kiểm soát tỷ lệ nội suy giữa trạng thái cũ và mới)&lt;/p&gt;

&lt;p&gt;\(\tilde{\mathbf{h}}_t = \tanh(\mathbf{W} \cdot [\mathbf{r}_t \odot \mathbf{h}_{t-1}; \mathbf{x}_t])\) (trạng thái ẩn ứng viên)&lt;/p&gt;

&lt;p&gt;\(\mathbf{h}_t = (1 - \mathbf{z}_t) \odot \mathbf{h}_{t-1} + \mathbf{z}_t \odot \tilde{\mathbf{h}}_t\) (nội suy giữa trạng thái cũ và ứng viên mới)&lt;/p&gt;

&lt;p&gt;Cổng &lt;em&gt;update&lt;/em&gt; \(\mathbf{z}_t\) đảm nhiệm đồng thời vai trò của cổng quên và cổng vào trong LSTM: khi \(z_t^{(i)} \approx 0\), chiều \(i\) giữ lại trạng thái cũ (tương tự \(f_t^{(i)} = 1, i_t^{(i)} = 0\)); khi \(z_t^{(i)} \approx 1\), chiều \(i\) cập nhật theo ứng viên mới (tương tự \(f_t^{(i)} = 0, i_t^{(i)} = 1\)). Trong khi đó, cổng &lt;em&gt;reset&lt;/em&gt; \(\mathbf{r}_t\) cho phép bỏ qua trạng thái trước đó (khi \(r_t^{(i)} = 0\)) để tính biểu diễn ứng viên chỉ dựa trên đầu vào hiện tại.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;p&gt;Để minh họa cách LSTM xử lý phụ thuộc tầm xa, hãy xét câu tiếng Anh: &lt;em&gt;“The cat, which we found in the garden, was hungry”&lt;/em&gt;, với nhiệm vụ dự đoán động từ phù hợp ở dạng số ít hay số nhiều (&lt;em&gt;“was”&lt;/em&gt; hay &lt;em&gt;“were”&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Bài toán này gây khó khăn cho RNN cơ bản vì chủ ngữ &lt;em&gt;“cat”&lt;/em&gt; (số ít) đứng ở đầu câu, tiếp theo là mệnh đề quan hệ &lt;em&gt;“which we found in the garden”&lt;/em&gt; chứa đại từ số nhiều &lt;em&gt;“we”&lt;/em&gt;, rồi mới tới động từ cần chia theo &lt;em&gt;“cat”&lt;/em&gt;. RNN cơ bản phải giữ thông tin &lt;em&gt;“cat là số ít”&lt;/em&gt; qua 6 từ xen giữa, nơi mỗi bước biến đổi phi tuyến đều có thể làm mờ tín hiệu ban đầu.&lt;/p&gt;

&lt;p&gt;Trong LSTM, cơ chế cổng cho phép tách biệt các luồng thông tin này. Khi đọc &lt;em&gt;“cat”&lt;/em&gt;, cổng vào mở để ghi thông tin chủ ngữ số ít vào trạng thái tế bào. Khi đi qua mệnh đề quan hệ, cổng quên giữ gần bằng 1 ở các chiều lưu thông tin chủ ngữ (\(f_t \approx 1\)), đồng thời cổng vào cho phép lưu ngữ cảnh của mệnh đề phụ vào các chiều khác. Nhờ vậy, thông tin chủ ngữ đi qua 6 bước gần như nguyên vẹn. Đến vị trí cần dự đoán động từ, cổng ra mở cho các chiều lưu thông tin chủ ngữ và đóng (\(o_t \approx 0\)) ở các chiều thuộc mệnh đề phụ, giúp lớp đầu ra chọn đúng &lt;em&gt;“was”&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Xét một ví dụ số đơn giản hóa với trạng thái tế bào 2 chiều: chiều thứ nhất mã hóa số của chủ ngữ (&lt;em&gt;subject-number&lt;/em&gt;) và chiều thứ hai mã hóa ngữ cảnh mệnh đề phụ (&lt;em&gt;clause-context&lt;/em&gt;). Sau khi xử lý &lt;em&gt;“cat”&lt;/em&gt;:&lt;/p&gt;

&lt;p&gt;\(\mathbf{c}_{\text{cat}} = \begin{bmatrix} 0.9 \\ 0.1 \end{bmatrix}\) (giá trị cao cho chủ ngữ số ít, thấp cho ngữ cảnh mệnh đề phụ)&lt;/p&gt;

&lt;p&gt;Khi đi qua cụm &lt;em&gt;“which we found”&lt;/em&gt;, cổng quên giữ cao ở chiều chủ ngữ và thấp ở chiều mệnh đề phụ:&lt;/p&gt;

\[\mathbf{f}_{\text{which}} = \begin{bmatrix} 0.95 \\ 0.1 \end{bmatrix}\]

&lt;p&gt;Cổng vào và ứng viên cập nhật thông tin mệnh đề phụ:&lt;/p&gt;

&lt;p&gt;\(\mathbf{i}_{\text{which}} = \begin{bmatrix} 0.05 \\ 0.9 \end{bmatrix}\), \(\tilde{\mathbf{c}}_{\text{which}} = \begin{bmatrix} 0.2 \\ 0.7 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Sau bước cập nhật:&lt;/p&gt;

\[\mathbf{c}_{\text{which}} = \begin{bmatrix} 0.95 \\ 0.1 \end{bmatrix} \odot \begin{bmatrix} 0.9 \\ 0.1 \end{bmatrix} + \begin{bmatrix} 0.05 \\ 0.9 \end{bmatrix} \odot \begin{bmatrix} 0.2 \\ 0.7 \end{bmatrix} = \begin{bmatrix} 0.865 \\ 0.64 \end{bmatrix}\]

&lt;p&gt;Ta thấy thông tin về số của chủ ngữ chỉ giảm rất nhẹ (từ 0.9 xuống 0.865), trong khi ngữ cảnh mệnh đề phụ đã được cập nhật lên 0.64. Khả năng bảo toàn chọn lọc theo từng chiều này là cơ sở giúp LSTM học phụ thuộc tầm xa.&lt;/p&gt;

&lt;p&gt;Thiết kế ba cổng thoạt nhìn có vẻ cầu kỳ, nhưng mỗi cổng giải quyết một nhu cầu riêng biệt: cổng quên xử lý việc chuyển đổi ngữ cảnh (câu mới, chủ đề mới), cổng vào lọc mức độ liên quan của thông tin mới, còn cổng ra kiểm soát thời điểm trích xuất thông tin đã lưu. Cách phân tách này có nét tương đồng với trí nhớ làm việc ở người: bộ nhớ hiệu quả không chỉ cần lưu trữ mà còn cần khả năng chọn lọc thông tin để ghi, đọc và xóa đúng lúc.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Trình bày từng phương trình của cổng quên, cổng vào, cổng ra và trạng thái tế bào tương ứng với bài học.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker (tiếng Anh). Minh họa trực quan các cổng theo thứ tự tính toán, thuận tiện để đối chiếu khi tính tay.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Ôn lại kiến trúc RNN cơ bản để thấy rõ vấn đề mà các cổng LSTM khắc phục.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06 LSTM và GRU - Kiến trúc Hồi quy Nâng cao</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter06/06_00_Introduction</id>
   <content type="html">&lt;p&gt;Đọc câu: &lt;em&gt;“Tôi lớn lên ở Đà Lạt, nơi có những rừng thông bạt ngàn và sương mù buổi sáng; sau nhiều năm đi làm xa quê, mỗi khi nhớ nhà tôi lại mơ về thành phố…”&lt;/em&gt; — để điền đúng từ &lt;em&gt;“ngàn hoa”&lt;/em&gt; hay &lt;em&gt;“cao nguyên”&lt;/em&gt;, bộ não bạn phải giữ thông tin &lt;em&gt;“Đà Lạt”&lt;/em&gt; sống sót qua hơn 30 từ nhiễu ở giữa. RNN thuần túy thất bại hoàn toàn ở bài kiểm tra này vì gradient tắt lịm sau khoảng 10 bước; năm 1997, Sepp Hochreiter và Jürgen Schmidhuber đã tạo ra &lt;strong&gt;LSTM&lt;/strong&gt; — kiến trúc giữ ngôi vương xử lý chuỗi suốt gần hai thập kỷ.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-lstm-và-gru&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của LSTM và GRU&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Băng chuyền Trạng thái Tế bào (Cell State \(c_t\))&lt;/strong&gt;:
Thay vì liên tục nhân ma trận và bóp qua &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tanh&lt;/code&gt; ở mỗi bước như RNN, LSTM thiết kế một đường truyền cộng tính \(c_t = f_t \odot c_{t-1} + i_t \odot \tilde{c}_t\) giúp thông tin và gradient chảy thẳng qua hàng trăm bước thời gian.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ba cổng kiểm soát khả vi (Forget, Input, Output Gates)&lt;/strong&gt;:
Dùng hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sigmoid&lt;/code&gt; \(\sigma(\cdot) \in (0, 1)\) làm “van điều tiết mềm”: cổng quên \(f_t\) quyết định giữ lại bao nhiêu ký ức cũ, cổng nhập \(i_t\) lọc thông tin mới đáng ghi vào sổ, và cổng xuất \(o_t\) quyết định phần nào của trí nhớ được lộ ra ở trạng thái ẩn \(h_t\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GRU (Gated Recurrent Unit, 2014) — Phiên bản tinh gọn&lt;/strong&gt;:
Gộp trạng thái tế bào và trạng thái ẩn làm một, rút từ 3 cổng xuống còn 2 cổng (Reset \(r_t\) và Update \(z_t\)), cắt giảm 25% số tham số mà hiệu năng thường tương đương LSTM trên tập dữ liệu vừa và nhỏ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Di sản kiến trúc sang ResNet và Highway Networks&lt;/strong&gt;:
Ý tưởng cập nhật cộng tính có cổng \(c_t = f_t \odot c_{t-1} + \dots\) của LSTM thực chất chính là tiền thân trực tiếp của kết nối tắt \(y = x + F(x)\) trong ResNet năm 2015!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-vì-sao-cell-state-của-lstm-cứu-sống-gradient-sau-50-bước&quot;&gt;Giải thích: Tính tay vì sao Cell State của LSTM cứu sống Gradient sau 50 bước&lt;/h3&gt;

&lt;p&gt;Xét đạo hàm của trạng thái tế bào qua 1 bước thời gian (theo nhánh chủ đạo của băng chuyền):
\(\frac{\partial c_t}{\partial c_{t-1}} \approx f_t\)
Giả sử mạng học được rằng thông tin ở bước \(t=1\) (ví dụ chủ ngữ số ít/số nhiều) rất quan trọng nên mở cổng quên \(f_t = 0{,}98\) trong suốt \(k = 50\) bước (so với RNN thuần có hệ số suy giảm mỗi bước khoảng \(0{,}5\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Kiến trúc&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Hệ số truyền mỗi bước&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Tỷ lệ gradient sống sót sau \(k = 10\) bước&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Tỷ lệ gradient sống sót sau \(k = 50\) bước&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;RNN thuần túy&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\approx 0{,}50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}5^{10} \approx 9{,}8 \times 10^{-4}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}5^{50} \approx \mathbf{8{,}9 \times 10^{-16}}\) (tắt hoàn toàn)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;LSTM (cổng quên mở)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(f_t = 0{,}98\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}98^{10} \approx \mathbf{0{,}817}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}98^{50} \approx \mathbf{0{,}364}\) (vẫn còn 36,4%!)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Và nếu đặt bias khởi tạo cổng quên \(b_f = +1\) hay \(+2\), ngay từ epoch đầu tiên \(f_t = \sigma(b_f) \approx 0{,}73\text{–}0{,}88\), giúp LSTM mặc định “nhớ trước, học quên sau”.&lt;/p&gt;

&lt;h1 id=&quot;lstm-và-gru-khắc-phục-hiện-tượng-gradient-biến-mất&quot;&gt;LSTM và GRU: Khắc phục hiện tượng Gradient biến mất&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter06/lstm_architecture.png&quot; alt=&quot;LSTM Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc LSTM với trạng thái tế bào (cell state) và các cổng điều khiển. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Mạng Long Short-Term Memory (LSTM) và Gated Recurrent Unit (GRU) là hai cải tiến quan trọng trong lịch sử mạng neuron hồi quy. Cả hai được thiết kế để khắc phục &lt;strong&gt;vấn đề gradient biến mất&lt;/strong&gt; vốn hạn chế khả năng của RNN cơ bản, giúp mô hình học được các phụ thuộc kéo dài hàng trăm đến hàng nghìn bước thời gian.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter06/gru_architecture.png&quot; alt=&quot;GRU Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc GRU với hai cổng (reset và update). Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;vấn-đề-mà-lstm-giải-quyết&quot;&gt;Vấn đề mà LSTM giải quyết&lt;/h2&gt;

&lt;p&gt;Ở Chương 5, ta đã thấy RNN cơ bản gặp hiện tượng gradient biến mất: khi lan truyền ngược qua nhiều bước thời gian, gradient suy giảm theo hàm mũ, khiến mô hình rất khó học các phụ thuộc tầm xa. Thông tin ở đầu câu thường mờ dần và gần như mất tác dụng khi mạng đi tới cuối câu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ý tưởng cốt lõi của LSTM&lt;/strong&gt;: Thiết lập một đường truyền riêng để thông tin đi qua nhiều bước thời gian với mức biến đổi tối thiểu, tránh việc phải đi lặp lại qua các phép biến đổi phi tuyến vốn làm suy giảm gradient.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;trạng-thái-tế-bào-cell-state-đường-truyền-thông-tin-dài-hạn&quot;&gt;Trạng thái tế bào (&lt;em&gt;Cell State&lt;/em&gt;): Đường truyền thông tin dài hạn&lt;/h2&gt;

&lt;p&gt;LSTM bổ sung một &lt;strong&gt;trạng thái tế bào&lt;/strong&gt; (&lt;em&gt;cell state&lt;/em&gt;) \(\mathbf{c}_t\) chạy song song với trạng thái ẩn. Trạng thái tế bào cho phép thông tin truyền xuyên suốt nhiều bước thời gian chủ yếu qua các phép toán cộng và nhân theo phần tử:&lt;/p&gt;

\[\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t\]

&lt;p&gt;Khi cổng quên \(\mathbf{f}_t \approx 1\), thông tin từ bước trước được giữ lại gần như nguyên vẹn. Cách cập nhật này khác hẳn RNN cơ bản, nơi toàn bộ trạng thái ẩn phải đi qua phép nhân ma trận trọng số và hàm kích hoạt phi tuyến ở mỗi bước.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;cơ-chế-cổng-gate-kiểm-soát-luồng-thông-tin&quot;&gt;Cơ chế cổng (&lt;em&gt;Gate&lt;/em&gt;): Kiểm soát luồng thông tin&lt;/h2&gt;

&lt;p&gt;LSTM sử dụng ba &lt;strong&gt;cổng&lt;/strong&gt; (&lt;em&gt;gate&lt;/em&gt;) — các lớp mạng dùng hàm kích hoạt sigmoid có đầu ra trong khoảng [0, 1] — để điều tiết luồng thông tin:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Cổng&lt;/th&gt;
      &lt;th&gt;Chức năng&lt;/th&gt;
      &lt;th&gt;Phương trình&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Forget (Quên)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Quyết định phần thông tin cần loại bỏ khỏi trạng thái tế bào&lt;/td&gt;
      &lt;td&gt;\(\mathbf{f}_t = \sigma(\mathbf{W}_f[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_f)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Input (Vào)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Quyết định phần thông tin mới cần ghi thêm vào trạng thái tế bào&lt;/td&gt;
      &lt;td&gt;\(\mathbf{i}_t = \sigma(\mathbf{W}_i[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_i)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Output (Ra)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Quyết định phần thông tin của trạng thái tế bào sẽ đưa ra trạng thái ẩn&lt;/td&gt;
      &lt;td&gt;\(\mathbf{o}_t = \sigma(\mathbf{W}_o[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_o)\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Các cổng này hoạt động như những công tắc có thể học từ dữ liệu: mô hình tự điều chỉnh &lt;strong&gt;khi nào cần ghi nhớ&lt;/strong&gt;, &lt;strong&gt;khi nào cần quên&lt;/strong&gt; và &lt;strong&gt;khi nào cần trích xuất thông tin&lt;/strong&gt; cho đầu ra hiện tại.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;gru-biến-thể-tinh-giản&quot;&gt;GRU: Biến thể tinh giản&lt;/h2&gt;

&lt;p&gt;Gated Recurrent Unit (2014) đơn giản hóa cấu trúc của LSTM nhưng vẫn duy trì cơ chế kiểm soát bộ nhớ cốt lõi:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hai cổng&lt;/strong&gt; thay vì ba (cổng &lt;em&gt;reset&lt;/em&gt; và cổng &lt;em&gt;update&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không tách riêng trạng thái tế bào&lt;/strong&gt; — gộp chung vào một trạng thái ẩn duy nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ít hơn khoảng 25% tham số&lt;/strong&gt;, giúp huấn luyện nhanh hơn và dễ tinh chỉnh hơn.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trên nhiều bài toán thực tế, GRU đạt hiệu năng tương đương LSTM. Một kinh nghiệm thực hành phổ biến là &lt;strong&gt;thử GRU trước&lt;/strong&gt; nhờ cấu trúc gọn nhẹ, sau đó mới chuyển sang LSTM nếu cần thêm dung lượng biểu diễn.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;nội-dung-chính-của-chương&quot;&gt;Nội dung chính của chương&lt;/h2&gt;

&lt;h3 id=&quot;06-01-kiến-trúc-lstm&quot;&gt;06-01: Kiến trúc LSTM&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Hệ phương trình toán học đầy đủ của LSTM.&lt;/li&gt;
  &lt;li&gt;Phân tích luồng gradient: lý do LSTM giảm thiểu hiện tượng gradient biến mất.&lt;/li&gt;
  &lt;li&gt;Kiến trúc GRU và so sánh với LSTM.&lt;/li&gt;
  &lt;li&gt;Cài đặt LSTM từ đầu bằng NumPy.&lt;/li&gt;
  &lt;li&gt;Cài đặt bằng PyTorch trên bài toán bộ nhớ tầm xa.&lt;/li&gt;
  &lt;li&gt;Trực quan hóa và phân tích hoạt động của các cổng.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;vai-trò-lịch-sử-và-ứng-dụng&quot;&gt;Vai trò lịch sử và ứng dụng&lt;/h2&gt;

&lt;p&gt;Từ cuối thập niên 1990 đến giữa thập niên 2010, LSTM là kiến trúc chủ đạo trong mô hình hóa chuỗi, đóng góp vào nhiều hệ thống thực tế như:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Dịch máy (Google Translate, 2016)&lt;/li&gt;
  &lt;li&gt;Nhận dạng giọng nói (Siri, Google Voice)&lt;/li&gt;
  &lt;li&gt;Nhận dạng chữ viết tay&lt;/li&gt;
  &lt;li&gt;Tổng hợp âm nhạc&lt;/li&gt;
  &lt;li&gt;Dự báo chuỗi thời gian&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ngay cả khi Transformer đã trở thành kiến trúc phổ biến trong xử lý ngôn ngữ tự nhiên, LSTM và GRU vẫn giữ một số lợi thế nhất định:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Chi phí bộ nhớ thấp hơn&lt;/strong&gt;: độ phức tạp \(O(n)\) so với \(O(n^2)\) của attention đầy đủ trong Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xử lý trực tuyến (online)&lt;/strong&gt;: xử lý dữ liệu đến từng bước một cách tự nhiên.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phù hợp với tài nguyên hạn chế&lt;/strong&gt;: tiết kiệm bộ nhớ hơn khi làm việc với chuỗi dài trên thiết bị cấu hình thấp.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hiểu rõ cả ưu điểm lẫn hạn chế của LSTM là bước đệm quan trọng để nắm bắt lý do ra đời của cơ chế attention và kiến trúc Transformer.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-tiên-quyết&quot;&gt;Kiến thức tiên quyết&lt;/h2&gt;

&lt;p&gt;Trước khi học chương này, bạn nên nắm vững:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Kiến trúc và các hạn chế của RNN cơ bản (Chương 5).&lt;/li&gt;
  &lt;li&gt;Nguyên nhân gây ra hiện tượng gradient biến mất trong thuật toán lan truyền ngược theo thời gian.&lt;/li&gt;
  &lt;li&gt;Tính chất của hai hàm kích hoạt sigmoid và tanh.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau khi nắm vững các cổng LSTM/GRU, bạn có thể đọc thêm bài &lt;strong&gt;06-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về xLSTM và các bài toán thực tế nơi RNN có cổng vẫn hiệu quả. Phần đối chiếu phỏng vấn giữa ô LSTM và bộ nhớ đệm (cache) của Transformer nằm ở bài &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Giải thích trực quan trạng thái tế bào như đường truyền thông tin dài hạn mà LSTM bổ sung cho RNN cơ bản.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker (tiếng Anh). Minh họa từng cổng theo từng bước, kèm phần tinh giản sang GRU.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dqoEU9Ac3ek&quot;&gt;MIT 6.S191 (2024): Recurrent Neural Networks, Transformers, and Attention&lt;/a&gt; — Alexander Amini (tiếng Anh). Phần trình bày về LSTM trong bài giảng mô hình chuỗi của MIT, nối tiếp trực tiếp phần giới thiệu RNN.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Từng có thời điểm ngay sau khi Transformer bùng nổ, nhiều người cho rằng tư tưởng hồi quy (recurrence) đã khép lại sứ mệnh lịch sử. Nhưng khi ngữ cảnh LLM kéo dài lên hàng trăm nghìn rồi hàng triệu token, nút thắt bộ nhớ KV-cache và chi phí \(O(L^2)\) của Attention đã làm sống dậy một thế hệ &lt;strong&gt;mô hình hồi quy tuyến tính hiện đại&lt;/strong&gt; — tiêu biểu là &lt;strong&gt;Mamba (SSM)&lt;/strong&gt; và &lt;strong&gt;RWKV&lt;/strong&gt; — kết hợp khả năng huấn luyện song song với tốc độ suy luận \(O(1)\) cho mỗi token.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-hướng-phát-triển-của-tư-duy-hồi-quy-giai-đoạn-20222026&quot;&gt;Kiến thức cần nhớ: Bốn hướng phát triển của Tư duy Hồi quy giai đoạn 2022–2026&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Vì sao hồi quy hồi sinh — Bài toán KV-Cache và Suy luận \(O(1)\)&lt;/strong&gt;:
Transformer phải giữ toàn bộ lịch sử khóa/giá trị trong bộ nhớ GPU (tăng tuyến tính theo độ dài chuỗi), trong khi mô hình hồi quy hiện đại chỉ cần duy trì một trạng thái kích thước &lt;strong&gt;cố định&lt;/strong&gt; bất kể chuỗi dài bao nhiêu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình Không gian Trạng thái có cấu trúc (SSM) và Mamba&lt;/strong&gt;:
Xuất phát từ phương trình vi phân tuyến tính \(h&apos;(t) = A h(t) + B x(t)\) được rời rạc hóa, Mamba (2023–2024) bổ sung cơ chế &lt;strong&gt;chọn lọc theo đầu vào&lt;/strong&gt; (\(B_t, C_t, \Delta_t\) phụ thuộc \(x_t\)) và thuật toán quét song song trên SRAM GPU.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;RWKV (Receptance Weighted Key Value)&lt;/strong&gt;:
Viết lại attention thành dạng hồi quy tuyến tính cho phép “chế độ Transformer” (song song) khi huấn luyện và “chế độ RNN” (bộ nhớ hằng số) khi suy luận.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc lai (Hybrid SSM–Attention) và thiết bị biên&lt;/strong&gt;:
Các mô hình thực tiễn như Jamba, Zamba hay Nemotron-H xen kẽ các tầng Mamba (rẻ, dài) với một ít tầng Attention (truy xuất chính xác), đồng thời RNN nhỏ vẫn giữ vị thế trong xử lý âm thanh streaming độ trễ thấp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-bằng-số-độ-phức-tạp-suy-luận-ở-độ-dài-ngữ-cảnh-l--100000-token&quot;&gt;Giải thích: So sánh bằng số độ phức tạp suy luận ở độ dài ngữ cảnh \(L = 100{,}000\) token&lt;/h3&gt;

&lt;p&gt;Giả sử một mô hình 32 tầng với kích thước trạng thái/ẩn \(d = 4{,}096\) sinh ra &lt;strong&gt;1 token mới&lt;/strong&gt; khi ngữ cảnh đã đạt \(L = 100{,}000\) token (dùng FP16 = 2 byte/số):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Kiến trúc&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Bộ nhớ trạng thái cần đọc cho 1 token mới&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Số phép tính để sinh thêm 1 token&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Tính chất mở rộng khi \(L\) tăng gấp 10 lần&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Transformer chuẩn (KV-Cache)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(32 \times 2 \times L \times d \times 2 \approx \mathbf{52{,}4\text{ GB}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Tỷ lệ với \(O(L \cdot d)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bộ nhớ và độ trễ &lt;strong&gt;tăng gấp 10 lần&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Mô hình hồi quy hiện đại (Mamba / RWKV)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Trạng thái cố định \(32 \times (N_{\text{state}} \cdot d) \times 2 \approx \mathbf{4\text{–}32\text{ MB}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Cố định \(O(N_{\text{state}} \cdot d)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bộ nhớ và độ trễ &lt;strong&gt;không đổi (\(O(1)\))&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Con số 52 GB so với vài chục MB giải thích rõ ràng vì sao nguyên lý trạng thái ẩn hồi quy của Chương 05 không hề lỗi thời, mà đang tái sinh mạnh mẽ trong các mô hình ngữ cảnh siêu dài.&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-mô-hình-chuỗi-hồi-quy-sau-thời-đại-transformer&quot;&gt;Tùy chọn: Mô hình chuỗi hồi quy sau thời đại Transformer&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này mang tính &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết RNN gốc hay bài cài đặt mô hình ngôn ngữ cấp ký tự. Nội dung tập trung làm rõ những bối cảnh mà cơ chế hồi quy vẫn được sử dụng, cũng như các kiến trúc giai đoạn 2023–2025 đưa ý tưởng “quét theo thời gian” trở lại.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Phương trình của RNN gốc:&lt;/p&gt;

\[\mathbf{h}_t = \sigma(W_h \mathbf{h}_{t-1} + W_x \mathbf{x}_t + \mathbf{b}).\]

&lt;p&gt;Transformer loại bỏ vòng lặp từ trái sang phải trong quá trình &lt;em&gt;huấn luyện&lt;/em&gt;. Từ sau năm 2022, các &lt;strong&gt;mô hình không gian trạng thái (state-space models) và hồi quy tuyến tính&lt;/strong&gt; đưa cơ chế hồi quy trở lại dưới dạng &lt;em&gt;quét song song (parallel scan)&lt;/em&gt; với chi phí tính toán tuyến tính theo độ dài chuỗi.&lt;/p&gt;

&lt;h2 id=&quot;1-vì-sao-rnn-không-hoàn-toàn-biến-mất&quot;&gt;1. Vì sao RNN không hoàn toàn biến mất&lt;/h2&gt;

&lt;p&gt;Transformer tiêu tốn \(O(T^2)\) bộ nhớ và thời gian theo độ dài chuỗi \(T\) (khi chưa áp dụng các kỹ thuật xấp xỉ). Các bài toán như nhận dạng giọng nói trực tuyến (speech streaming), điều khiển thời gian thực và phân tích trình tự gen rất dài vẫn cần độ phức tạp \(O(T)\) cùng trạng thái bộ nhớ gọn nhẹ. Đó chính là động lực ban đầu của RNN, nay được cải tiến bằng cách tham số hóa hiệu quả hơn.&lt;/p&gt;

&lt;h2 id=&quot;2-các-ứng-dụng-và-kiến-trúc-tiêu-biểu&quot;&gt;2. Các ứng dụng và kiến trúc tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;mô-hình-không-gian-trạng-thái-có-cấu-trúc-ssm-và-mamba&quot;&gt;Mô hình không gian trạng thái có cấu trúc (SSM) và Mamba&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2312.00752&quot;&gt;Gu &amp;amp; Dao, 2023&lt;/a&gt; đề xuất Mamba sử dụng SSM có cơ chế chọn lọc, trong đó bước cập nhật trạng thái rời rạc có dạng hồi quy:&lt;/p&gt;

\[\mathbf{h}_t = \overline{A}_t \mathbf{h}_{t-1} + \overline{B}_t \mathbf{x}_t, \quad \mathbf{y}_t = C_t \mathbf{h}_t,\]

&lt;p&gt;với \(\overline{A}_t\) phụ thuộc trực tiếp vào đầu vào (cơ chế &lt;em&gt;selection&lt;/em&gt;). Quá trình huấn luyện được thực hiện bằng &lt;em&gt;parallel scan&lt;/em&gt; thay vì vòng lặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; tuần tự trong Python. Đây là một trong những câu trả lời nổi bật giai đoạn 2023–2025 cho câu hỏi liệu kiến trúc hồi quy có thể cạnh tranh với attention trong xử lý ngôn ngữ hay không.&lt;/p&gt;

&lt;h3 id=&quot;rwkv&quot;&gt;RWKV&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.13048&quot;&gt;Peng et al., 2023&lt;/a&gt; kết hợp khối trộn theo thời gian (&lt;em&gt;time-mix&lt;/em&gt;) theo kiểu linear attention với khối trộn theo kênh (&lt;em&gt;channel-mix&lt;/em&gt;). Nhờ đó, RWKV suy luận như một RNN với kích thước trạng thái cố định, trong khi vẫn huấn luyện song song được. Kiến trúc này được ứng dụng trong các mô hình hội thoại mã nguồn mở khi dung lượng bộ nhớ KV-cache trở thành nút thắt.&lt;/p&gt;

&lt;h3 id=&quot;phạm-vi-ứng-dụng-còn-lại-của-rnn-cổ-điển&quot;&gt;Phạm vi ứng dụng còn lại của RNN cổ điển&lt;/h3&gt;

&lt;p&gt;Nhận diện từ khóa trên thiết bị biên (on-device keyword spotting), một số mô hình dự báo chuỗi thời gian cơ sở và các bài toán nghiên cứu quy mô nhỏ vẫn sử dụng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt; hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.GRU&lt;/code&gt;. Trong khi đó, các hệ thống nhận dạng giọng nói (ASR) triển khai thực tế đã chuyển sang Conformer hoặc Whisper (Chương 08 và 19) thay vì dùng mạng Elman RNN gốc.&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-mã-nguồn-phổ-biến&quot;&gt;3. Thư viện và mã nguồn phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/state-spaces/mamba&quot;&gt;state-spaces/mamba&lt;/a&gt; — mã nguồn và kernel chính thức của Mamba.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/BlinkDL/RWKV-LM&quot;&gt;BlinkDL/RWKV-LM&lt;/a&gt; — mã nguồn huấn luyện và suy luận cho RWKV.&lt;/li&gt;
  &lt;li&gt;PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt; — API tiêu chuẩn cho các bài tập cốt lõi trong chương này.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2312.00752&quot;&gt;Mamba (Gu &amp;amp; Dao, 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.13048&quot;&gt;RWKV (Peng et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2111.00396&quot;&gt;S4 (Gu et al., 2022)&lt;/a&gt; — kiến trúc tiền thân của dòng SSM.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-vai-trò-bổ-trợ-cho-nội-dung-cốt-lõi&quot;&gt;5. Vai trò bổ trợ cho nội dung cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn nên hoàn thành phần cài đặt RNN gốc và bài về các bẫy thường gặp trước. Bài đọc thêm này chỉ nhằm đối chiếu &lt;strong&gt;hồi quy tuyến tính hiện đại&lt;/strong&gt; với Transformer, không thay thế phần phân tích trải mạng (unfolding) và thuật toán BPTT.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [MAMBA and State Space Models explained&lt;/td&gt;
          &lt;td&gt;SSM explained](https://www.youtube.com/watch?v=vrF3MtGwD0Y) — AI Coffee Break with Letitia (tiếng Anh). Giải thích mô hình không gian trạng thái — lý do cơ chế hồi quy quay trở lại trong giai đoạn 2023–2024.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Ôn lại khái niệm trạng thái ẩn mà các kiến trúc hồi quy mới vẫn kế thừa.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dqoEU9Ac3ek&quot;&gt;MIT 6.S191 (2024): Recurrent Neural Networks, Transformers, and Attention&lt;/a&gt; — Alexander Amini (tiếng Anh). Cho thấy cách các khóa học hiện đại đặt RNN cạnh attention trong cùng một khung phân tích.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-01 Mạng Neuron Hồi quy - Cơ bản</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_01_RNN_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_01_RNN_Fundamentals</id>
   <content type="html">&lt;p&gt;Để hiểu vì sao những mô hình ngôn ngữ khổng lồ ngày nay phải tốn hàng tỷ đô-la nghiên cứu kiến trúc chuỗi, bước đi đúng đắn nhất là bắt đầu từ chính phương trình hồi quy đơn giản nhất của RNN. Nắm vững cách trải phẳng (unrolling) theo thời gian và lan truyền ngược BPTT sẽ cho bạn nền tảng vững chắc để đọc hiểu mọi kiến trúc xử lý chuỗi về sau.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-học-phần-cơ-bản-về-rnn&quot;&gt;Kiến thức cần nhớ: Ba trụ cột học phần Cơ bản về RNN&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết và trực giác trải phẳng theo thời gian (Unrolling)&lt;/strong&gt;:
Biến một vòng lặp hồi tiếp thành một mạng sâu \(T\) tầng chia sẻ chung trọng số — nhờ đó quy tắc chuỗi (chain rule) quen thuộc áp dụng được ngay.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền ngược theo thời gian (BPTT) và phổ trị riêng của \(W_{hh}\)&lt;/strong&gt;:
Đạo hàm truyền lùi \(k\) bước chứa lũy thừa \((W_{hh}^T)^k\); nếu trị riêng lớn nhất \(|\lambda_{\max}| &amp;lt; 1\) gradient tắt lịm, còn \(|\lambda_{\max}| &amp;gt; 1\) gradient bùng nổ theo cấp số nhân.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Triển khai thực chiến và kỹ thuật ổn định huấn luyện&lt;/strong&gt;:
Tự lập trình RNN từ NumPy/PyTorch, xây dựng mô hình ngôn ngữ cấp ký tự, áp dụng gradient clipping và truncated BPTT để huấn luyện ổn định.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-tốc-độ-suy-giảm-và-bùng-nổ-của-lũy-thừa-trọng-số-sau-20-bước&quot;&gt;Giải thích: Tính tay tốc độ suy giảm và bùng nổ của lũy thừa trọng số sau 20 bước&lt;/h3&gt;

&lt;p&gt;Trong BPTT, đạo hàm từ bước \(T\) truyền ngược về bước \(T - k\) tỷ lệ với lũy thừa \(\lambda^k\) (với \(\lambda\) là độ lớn trọng số hồi tiếp hiệu dụng sau khi nhân đạo hàm \(\tanh&apos; \le 1\)):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Hệ số mỗi bước \(\lambda\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Sau \(k = 5\) bước&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Sau \(k = 10\) bước&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Sau \(k = 20\) bước&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hiện tượng xảy ra&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}03125\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(9{,}77 \times 10^{-4}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\mathbf{9{,}54 \times 10^{-7}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Vanishing Gradient&lt;/strong&gt; — mạng “quên” hoàn toàn đầu câu&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1{,}0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1{,}000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1{,}000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\mathbf{1{,}000}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Lý tưởng nhưng cực khó duy trì chính xác bằng tay&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1{,}5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(7{,}594\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(57{,}67\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\mathbf{3{,}325{,}26}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Exploding Gradient&lt;/strong&gt; — trọng số vọt lên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ cần nhìn cột \(k = 20\) (một câu tiếng Việt bình thường đã dài 20 từ!), bạn thấy ngay lý do toán học trần trụi khiến RNN thuần túy thất bại trên phụ thuộc tầm xa.&lt;/p&gt;

&lt;p&gt;Bài học này giới thiệu mạng neuron hồi quy cho dữ liệu tuần tự qua hai phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết và Trực giác RNN&lt;/strong&gt; — tổng quan khái niệm, nền tảng toán học và trực giác qua ví dụ cụ thể.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Triển khai RNN&lt;/strong&gt; — mã nguồn đầy đủ, các khái niệm liên quan, bài báo nền tảng, bẫy thường gặp và tóm tắt điểm chính.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Nên xem trước khi đọc các bài lý thuyết và cài đặt.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 10&lt;/td&gt;
          &lt;td&gt;Recurrent Neural Networks](https://www.youtube.com/watch?v=6niqTuYFZLQ) — Stanford University School of Engineering (tiếng Anh). Bài giảng hệ thống về phép hồi quy và thuật toán lan truyền ngược theo thời gian.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=L8HKweZIOmg&quot;&gt;Sequence-to-Sequence (seq2seq) Encoder-Decoder Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Giới thiệu kiến trúc chuỗi-sang-chuỗi (seq2seq) được đề cập trong phần tổng quan và phần cài đặt.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-01-02 Triển khai RNN</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_01_02_RNN_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_01_02_RNN_Implementation</id>
   <content type="html">&lt;p&gt;Giữa việc hiểu phương trình \(h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h)\) trên bảng và việc huấn luyện thành công một mô hình ngôn ngữ biết tự sinh văn bản là cả một khoảng cách kỹ thuật: cách tổ chức kích thước tensor 3D &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(batch, seq_len, input_size)&lt;/code&gt;, cách ngắt đồ thị tính toán (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;detach()&lt;/code&gt;) khi chạy chuỗi dài, và cách lấy mẫu phân phối đầu ra bằng nhiệt độ (&lt;em&gt;temperature&lt;/em&gt;).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-thực-hành-khi-lập-trình-rnn&quot;&gt;Kiến thức cần nhớ: Ba trụ cột thực hành khi lập trình RNN&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Quản lý hình dạng tensor 3D và cờ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_first&lt;/code&gt;&lt;/strong&gt;:
Trong PyTorch, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt; mặc định kỳ vọng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(seq_len, batch, input_size)&lt;/code&gt; trừ khi bạn truyền tường minh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_first=True&lt;/code&gt; để đổi thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(batch, seq_len, input_size)&lt;/code&gt; — nhầm thứ tự hai trục đầu là lỗi phổ biến nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vòng lặp BPTT và tách trạng thái ẩn (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h.detach()&lt;/code&gt;)&lt;/strong&gt;:
Khi huấn luyện trên văn bản dài hàng triệu ký tự, ta cắt thành các đoạn \(T\) bước và gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h = h.detach()&lt;/code&gt; giữa các đoạn để truyền bộ nhớ sang đoạn sau mà không lưu đồ thị đạo hàm phình to vô hạn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Suy luận tự hồi quy (Autoregressive Sampling) với Temperature&lt;/strong&gt;:
Chia logit cho nhiệt độ \(\tau\) trước khi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softmax&lt;/code&gt;: \(\tau &amp;lt; 1\) làm phân phối nhọn hơn (an toàn, lặp), còn \(\tau &amp;gt; 1\) làm phân phối phẳng hơn (sáng tạo nhưng dễ sai chính tả).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-số-tham-số-của-nnrnninput_size10-hidden_size32-num_layers1&quot;&gt;Giải thích: Tính tay số tham số của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN(input_size=10, hidden_size=32, num_layers=1)&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;Một tầng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt; trong PyTorch chứa hai ma trận trọng số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_ih&lt;/code&gt; (từ đầu vào \(x_t\)), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_hh&lt;/code&gt; (từ trạng thái ẩn \(h_{t-1}\)) và hai vector bias tương ứng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_ih&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_hh&lt;/code&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Thành phần tham số&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Kích thước ma trận/vector&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Số lượng phần tử&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_ih_l0&lt;/code&gt; (\(W_{xh}\))&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(32 \times 10\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;320&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_hh_l0&lt;/code&gt; (\(W_{hh}\))&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(32 \times 32\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;1,024&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_ih_l0&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_hh_l0&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(32 + 32\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;64&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Tổng cộng tầng RNN&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt; &lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;&lt;strong&gt;1,408&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Lưu ý chi tiết thực tế: công thức tổng quát của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt; trong PyTorch có &lt;strong&gt;hai&lt;/strong&gt; vector bias (\(2 \cdot d_h\)) để tương thích chuẩn cuDNN, nhiều hơn \(d_h\) tham số so với công thức sách giáo khoa chỉ viết 1 bias \(b_h\).&lt;/p&gt;

&lt;p&gt;Phần cài đặt RNN gồm hai nội dung chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Triển khai Cốt lõi&lt;/strong&gt; — cài đặt RNN từ đầu bằng NumPy, dự đoán chuỗi và đối chiếu với PyTorch.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình ngôn ngữ cấp ký tự, Papers và Bẫy thường gặp&lt;/strong&gt; — xây dựng mô hình ngôn ngữ, các khái niệm liên quan, bài báo nền tảng và lưu ý thực hành.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Lecture 10&lt;/td&gt;
          &lt;td&gt;Recurrent Neural Networks](https://www.youtube.com/watch?v=6niqTuYFZLQ) — Stanford University School of Engineering (tiếng Anh). Trình bày cấu trúc cài đặt của một ô RNN cùng hàm mất mát trên chuỗi.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Cài đặt trực tiếp mô hình ngôn ngữ cấp ký tự bằng mã nguồn, đúng với mục tiêu thực hành của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Tài liệu đối chiếu nhanh về kích thước các vectơ trạng thái ẩn h và đầu vào x khi đọc mã.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-01-02-02 Mô hình ngôn ngữ cấp ký tự, Papers và Bẫy thường gặp</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_01_02_02_RNN_Language_Model_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_01_02_02_RNN_Language_Model_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Năm 2015, bài blog nổi tiếng &lt;em&gt;“The Unreasonable Effectiveness of Recurrent Neural Networks”&lt;/em&gt; của Andrej Karpathy khiến cả cộng đồng lập trình sửng sốt: một mạng RNN cấp ký tự cực kỳ gọn nhẹ, chỉ học dự đoán &lt;strong&gt;ký tự tiếp theo&lt;/strong&gt;, mà sau vài giờ huấn luyện đã biết tự gõ kịch Shakespeare đúng thể thơ, tự viết code C có đóng mở ngoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{}&lt;/code&gt; khớp nhau, thậm chí tự sinh mã LaTeX gần như biên dịch được!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-mô-hình-ngôn-ngữ-cấp-ký-tự-char-rnn&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Mô hình Ngôn ngữ Cấp Ký tự (Char-RNN)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bài toán học tự giám sát (Next-Token Prediction)&lt;/strong&gt;:
Từ chuỗi văn bản thô &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;hello&quot;&lt;/code&gt;, ta không cần ai gán nhãn thủ công: đầu vào là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;hell&quot;&lt;/code&gt; và nhãn đích dịch phải 1 bước là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;ello&quot;&lt;/code&gt; — chính là nguyên lý tiền huấn luyện của mọi LLM hiện đại.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mã hóa ký tự (One-Hot vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Embedding&lt;/code&gt;)&lt;/strong&gt;:
Với bảng chữ cái nhỏ (khoảng 50–100 ký tự), vector one-hot đủ dùng để minh họa, nhưng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Embedding&lt;/code&gt; tương đương phép tra bảng nhanh hơn nhiều và học được không gian ngữ nghĩa dày đặc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chiến lược lấy mẫu (Greedy vs. Multinomial Temperature Sampling)&lt;/strong&gt;:
Luôn chọn ký tự xác suất cao nhất (greedy) dễ rơi vào vòng lặp vô tận; lấy mẫu xác suất với nhiệt độ \(\tau\) tạo sự cân bằng giữa độ mạch lạc và đa dạng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các cạm bẫy kinh điển khi huấn luyện RNN thực tế&lt;/strong&gt;:
Quên khởi tạo lại hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;detach&lt;/code&gt; trạng thái ẩn giữa các batch độc lập, không dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pack_padded_sequence&lt;/code&gt; khi chuỗi trong cùng batch có độ dài khác nhau (khiến &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;PAD&amp;gt;&lt;/code&gt; làm nhiễu trạng thái ẩn), và kỳ vọng RNN thuần nhớ được phụ thuộc xa hơn ~15–20 bước.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-ảnh-hưởng-của-nhiệt-độ-temperature-tau-lên-xác-suất-sinh-ký-tự-tiếp-theo&quot;&gt;Giải thích: Tính tay ảnh hưởng của Nhiệt độ (Temperature \(\tau\)) lên xác suất sinh ký tự tiếp theo&lt;/h3&gt;

&lt;p&gt;Giả sử ở bước dự đoán ký tự sau &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;hel&quot;&lt;/code&gt;, mạng đưa ra 3 logit cho các ký tự &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(&apos;l&apos;, &apos;p&apos;, &apos;o&apos;)&lt;/code&gt; lần lượt là \(\mathbf{z} = [2{,}0, \; 1{,}0, \; 0{,}0]\). Xác suất lấy mẫu là \(p_i = \frac{e^{z_i / \tau}}{\sum_j e^{z_j / \tau}}\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Nhiệt độ \(\tau\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Logit sau chia \(\mathbf{z}/\tau\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;\(P(\text{&apos;l&apos;})\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;\(P(\text{&apos;p&apos;})\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;\(P(\text{&apos;o&apos;})\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hành vi sinh văn bản&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(\tau = 0{,}5\)&lt;/strong&gt; (lạnh)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([4{,}0,\; 2{,}0,\; 0{,}0]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;86,7%&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;11,7%&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1,6%&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Rất tự tin, gần như luôn chọn &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;l&apos;&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(\tau = 1{,}0\)&lt;/strong&gt; (chuẩn)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([2{,}0,\; 1{,}0,\; 0{,}0]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;66,5%&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;24,5%&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;9,0%&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Cân bằng giữa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;l&apos;&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;hello&lt;/code&gt;) và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;p&apos;&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;help&lt;/code&gt;)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(\tau = 2{,}0\)&lt;/strong&gt; (nóng)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([1{,}0,\; 0{,}5,\; 0{,}0]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;50,6%&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;30,7%&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;18,6%&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Phẳng dần, dễ sinh ra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;o&apos;&lt;/code&gt; (sai chính tả nhưng đa dạng)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ bằng một tham số vô hướng \(\tau\) lúc suy luận (không cần huấn luyện lại mô hình!), bạn kiểm soát hoàn toàn độ “liều lĩnh” của bộ sinh văn bản.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Ví dụ mô hình ngôn ngữ cấp ký tự
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mô hình ngôn ngữ cấp ký tự với PyTorch RNN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo dataset văn bản đơn giản
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;hello world, deep learning is amazing! transformers are powerful.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;chars&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;char_to_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chars&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;idx_to_char&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chars&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chars&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vocabulary: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chars&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vocabulary size: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Chuẩn bị chuỗi: cho &quot;hell&quot; dự đoán &quot;ello&quot;
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tạo các chuỗi huấn luyện từ văn bản&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Chuyển thành chỉ số
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;seq_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;char_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;char_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Chuyển thành tensor và tạo mã hóa one-hot
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;to_onehot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Chuyển chuỗi chỉ số thành tensor one-hot&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;one_hot&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;seq_onehot&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;seq_onehot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;one_hot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_onehot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;one_hot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;to_onehot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;long&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dataset: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; sequences of length &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (num_sequences, seq_length, vocab_size)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Target shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (num_sequences, seq_length)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tạo model
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RNNSequenceModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                         &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Loss và optimizer
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CrossEntropyLoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện mô hình ngôn ngữ cấp ký tự...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch, seq_len, vocab_size)
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Reshape cho cross-entropy: (batch * seq_len, vocab_size)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs_flat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;targets_flat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tính loss
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Backward pass và tối ưu
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# BPTT diễn ra tự động ở đây!
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Gradient clipping (cốt yếu cho RNN!)
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Không có bước này, gradient có thể bùng nổ và huấn luyện phân kỳ
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip_grad_norm_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_norm&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh văn bản bằng cách lấy mẫu từ phân phối đã học
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sinh văn bản từ RNN đã học&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Sinh văn bản tự hồi quy (autoregressive) bằng RNN đã huấn luyện.
    
    Ta bắt đầu bằng seed text, dự đoán phân phối xác suất ký tự tiếp theo,
    lấy mẫu từ đó, nối vào chuỗi, và lặp lại.
    Đây là sinh tự hồi quy — mỗi dự đoán điều kiện trên
    tất cả các dự đoán trước đó.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Chuyển seed text thành chỉ số
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;current_seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;char_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;generated&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_text&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Trạng thái ẩn mang thông tin qua quá trình sinh
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Chuẩn bị đầu vào: seq_length ký tự cuối (hoặc pad nếu ngắn hơn)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;input_seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;current_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;current_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;current_seq&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Pad nếu cần
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;input_seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;char_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_seq&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Chuyển thành one-hot
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Dự đoán ký tự tiếp theo
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Lấy xác suất cho ký tự tiếp theo (bước thời gian cuối)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Lấy mẫu từ phân phối (thú vị hơn argmax)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;next_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;multinomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;next_char&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx_to_char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;generated&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_char&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;current_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;generated&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;deep &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;generated_text&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Seed: &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated: &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;generated_text&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mô hình đã học các mẫu cấp ký tự!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Với nhiều dữ liệu và huấn luyện hơn, RNN có thể sinh văn bản mạch lạc.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Đoạn mã dưới đây minh họa hiện tượng gradient biến mất bằng thực nghiệm:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Minh họa Gradient biến mất trong RNN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;analyze_gradient_flow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sequence_lengths&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Cho thấy gradient suy giảm thế nào theo độ dài chuỗi.
    
    Ta tạo chuỗi các độ dài khác nhau, tính gradient, và
    đo độ lớn của chúng. Điều này minh họa thực nghiệm vì sao RNN vanilla
    gặp khó với phụ thuộc tầm xa.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequence_lengths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Tạo RNN đơn giản
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;rnn_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;RNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Chuỗi đầu vào ngẫu nhiên
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rnn_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính loss từ đầu ra bước thời gian CUỐI CÙNG
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Gradient phải backprop qua seq_len-1 bước để tới đầu vào đầu tiên x[:, 0, :]
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Đo độ lớn gradient tại bước thời gian đầu tiên
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;grad_magnitude&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_magnitude&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sequence length &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Gradient magnitude = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad_magnitude&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Thường thấy suy giảm cấp số nhân của độ lớn gradient
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Quan sát: Gradient suy giảm cấp số nhân theo độ dài chuỗi!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đây là vấn đề gradient biến mất giới hạn RNN vanilla.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;gradient_analysis&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;analyze_gradient_flow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-các-khái-niệm-liên-quan&quot;&gt;5. Các khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;So sánh RNN với mạng truyền thẳng (feedforward) làm sáng tỏ các giả định nền tảng trong thiết kế kiến trúc mạng. Mạng feedforward coi các đầu vào là những mẫu độc lập và có phân phối đồng nhất — thứ tự đưa các hình ảnh vào khi huấn luyện không ảnh hưởng vì mỗi ảnh được xử lý tách biệt. Ngược lại, RNN mô hình hóa tường minh sự phụ thuộc giữa các phần tử liên tiếp thông qua trạng thái ẩn. Việc chọn RNN thay vì mạng feedforward thể hiện một thiên kiến quy nạp (inductive bias) rằng thứ tự thời gian hoặc thứ tự chuỗi mang thông tin quan trọng cho bài toán.&lt;/p&gt;

&lt;p&gt;Góc nhìn từ máy trạng thái hữu hạn và hệ thống động lực mang lại hiểu biết sâu hơn về mặt lý thuyết. Một RNN với trạng thái ẩn rời rạc và hàm kích hoạt ngưỡng cứng hoạt động như một máy trạng thái hữu hạn, chuyển đổi giữa các trạng thái dựa trên đầu vào. Với trạng thái ẩn liên tục và hàm kích hoạt trơn, RNN trở thành một hệ thống động lực rời rạc theo thời gian được mô tả bởi phương trình sai phân \(\mathbf{h}_{t+1} = f(\mathbf{W}_{hh}\mathbf{h}_t + \mathbf{W}_{xh}\mathbf{x}_t)\). Tính ổn định và năng lực biểu diễn của hệ thống này phụ thuộc vào phổ giá trị riêng của \(\mathbf{W}_{hh}\), qua đó quyết định hệ thống ổn định, hỗn loạn hay ở biên ổn định. Liên hệ này giải thích bản chất toán học của hiện tượng gradient biến mất/bùng nổ và lý do các kiến trúc như LSTM cần kiểm soát trực tiếp luồng thông tin bằng cơ chế cổng.&lt;/p&gt;

&lt;p&gt;Quá trình phát triển từ RNN đến LSTM rồi Transformer phản ánh nỗ lực giải quyết lần lượt từng giới hạn cốt lõi. RNN cơ bản khó học phụ thuộc tầm xa do gradient biến mất. LSTM đưa vào cơ chế cổng tạo đường truyền trực tiếp theo thời gian, giúp gradient lan truyền tốt hơn và bộ nhớ duy trì lâu hơn, nhưng vẫn phải xử lý tuần tự nên khó song song hóa. Transformer loại bỏ hoàn toàn hồi quy, dùng attention để kết nối trực tiếp mọi cặp vị trí trong chuỗi, cho phép song song hóa hoàn toàn dù phải đổi lấy độ phức tạp bậc hai theo độ dài chuỗi. Mỗi kiến trúc đại diện cho một sự đánh đổi khác nhau giữa khả năng biểu diễn, độ dễ huấn luyện và hiệu suất tính toán.&lt;/p&gt;

&lt;p&gt;So sánh RNN với mạng tích chập (CNN) cũng làm rõ sự đánh đổi này. Tích chập 1D theo thời gian nắm bắt được nhiều mẫu tuần tự và hỗ trợ song song hóa hoàn toàn, nhưng vùng tiếp nhận (receptive field) chỉ mở rộng tuyến tính theo chiều sâu: một mạng gồm \(L\) lớp với kích thước bộ lọc \(k\) có vùng tiếp nhận bằng \(1 + L(k-1)\). Trong khi đó, RNN về lý thuyết có vùng tiếp nhận không giới hạn vì trạng thái ẩn có thể lưu giữ thông tin từ bất kỳ thời điểm nào trước đó. Sự đánh đổi giữa khả năng song song hóa của tích chập và bộ nhớ lý thuyết vô hạn của RNN đã dẫn tới các kiến trúc kết hợp như WaveNet trong bài toán tổng hợp âm thanh.&lt;/p&gt;

&lt;p&gt;RNN hai chiều (Bidirectional RNN) mở rộng mô hình gốc bằng cách xử lý chuỗi theo cả chiều xuôi và chiều ngược, duy trì hai trạng thái ẩn \(\overrightarrow{\mathbf{h}}_t\) và \(\overleftarrow{\mathbf{h}}_t\). Đầu ra tại mỗi bước kết hợp cả hai chiều: \(\mathbf{y}_t = g(\mathbf{W}_{hy}[\overrightarrow{\mathbf{h}}_t; \overleftarrow{\mathbf{h}}_t] + \mathbf{b}_y)\). Cách thiết kế này hiệu quả với các tác vụ có sẵn toàn bộ chuỗi đầu vào (như dịch một câu hoàn chỉnh), nhưng không áp dụng được cho dự đoán thời gian thực khi mô hình phải ra quyết định trước khi thấy phần tương lai của chuỗi.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://doi.org/10.1207/s15516709cog1402_1&quot;&gt;“Finding Structure in Time” (1990)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Jeffrey L. Elman&lt;br /&gt;
Bài báo này giới thiệu Simple Recurrent Network (SRN), còn gọi là mạng Elman, và chứng minh kết nối hồi quy có thể học các mẫu theo thời gian. Elman cho thấy RNN có thể dự đoán từ tiếp theo trong các câu đơn giản và tự khám phá cấu trúc ngữ pháp mà không cần luật định nghĩa sẵn. Trạng thái ẩn tự hình thành biểu diễn nội bộ cho các từ loại (danh từ, động từ) và quan hệ tuần tự chỉ từ nhiệm vụ dự đoán. Công trình này đặt nền móng cho việc ứng dụng RNN trong mô hình hóa chuỗi, đồng thời cho thấy không gian trạng thái ẩn của mạng neuron có thể tự tổ chức thành những biểu diễn có thể diễn giải được.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://doi.org/10.1162/089976600300015015&quot;&gt;“Learning to Forget: Continual Prediction with LSTM” (2000)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Felix A. Gers, Jürgen Schmidhuber, Fred Cummins&lt;br /&gt;
Dù LSTM ra đời năm 1997, bài báo này bổ sung một thành phần then chốt giúp kiến trúc này vận hành hiệu quả trong thực tế: cổng quên (&lt;em&gt;forget gate&lt;/em&gt;). Phiên bản LSTM ban đầu chỉ tích lũy thông tin trong trạng thái tế bào (&lt;em&gt;cell state&lt;/em&gt;) mà thiếu cơ chế loại bỏ thông tin cũ không còn phù hợp, dễ dẫn đến bão hòa trên chuỗi dài. Cổng quên \(\mathbf{f}_t = \sigma(\mathbf{W}_f[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_f)\) cho phép mạng chủ động xóa bộ nhớ khi cần. Bổ sung nhỏ này cải thiện rõ rệt hiệu năng của LSTM trên chuỗi dài và trở thành thành phần tiêu chuẩn trong mọi cài đặt LSTM về sau.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1211.5063&quot;&gt;“On the difficulty of training Recurrent Neural Networks” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Razvan Pascanu, Tomas Mikolov, Yoshua Bengio&lt;br /&gt;
Bài báo cung cấp phân tích toán học chặt chẽ về hiện tượng gradient biến mất và bùng nổ trong RNN, vượt xa các quan sát thực nghiệm trước đó. Các tác giả chỉ ra rằng khi lan truyền ngược qua \(t\) bước thời gian, gradient phụ thuộc vào tích của \(t\) ma trận Jacobian; nếu trị riêng lớn nhất nhỏ hơn 1 thì gradient suy giảm theo hàm mũ, còn nếu lớn hơn 1 thì bùng nổ theo hàm mũ. Họ khẳng định đây là đặc tính nội tại của động lực hồi quy chứ không chỉ là vấn đề kỹ thuật huấn luyện. Công trình này đề xuất kỹ thuật cắt ngưỡng gradient (&lt;em&gt;gradient clipping&lt;/em&gt;) để kiểm soát hiện tượng bùng nổ và lý giải cách cơ chế cổng trong LSTM cải thiện luồng gradient.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1412.3555&quot;&gt;“Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Junyoung Chung, Caglar Gulcehre, KyungHyun Cho, Yoshua Bengio&lt;br /&gt;
Bài báo so sánh có hệ thống giữa LSTM và GRU (Gated Recurrent Unit) trên nhiều tác vụ mô hình hóa chuỗi nhằm đánh giá ưu thế của từng kiến trúc. GRU, do Cho và cộng sự đề xuất năm 2014, tinh giản LSTM xuống còn hai cổng và bỏ trạng thái tế bào riêng biệt, giảm khoảng 25% số lượng tham số. Kết quả thực nghiệm cho thấy GRU thường đạt hiệu năng tương đương LSTM nhưng huấn luyện nhanh hơn nhờ ít tham số hơn, đồng thời khẳng định các kiến trúc có cơ chế cổng luôn vượt trội RNN cơ bản trên chuỗi dài.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1506.02078&quot;&gt;“Visualizing and Understanding Recurrent Networks” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Andrej Karpathy, Justin Johnson, Li Fei-Fei&lt;br /&gt;
Bài báo khảo sát cách hoạt động bên trong của RNN thông qua phân tích trạng thái ẩn trên mô hình ngôn ngữ cấp ký tự. Khi quan sát các đơn vị ẩn kích hoạt theo mẫu đầu vào, nhóm tác giả phát hiện một số neuron đảm nhận vai trò rất cụ thể như theo dõi dấu ngoặc kép, kiểm tra cân bằng dấu ngoặc đơn hay mức thụt lề mã nguồn. Điều này chứng minh RNN thực sự học được cấu trúc có nghĩa thay vì chỉ ghi nhớ máy móc. Công trình cũng giới thiệu các kỹ thuật trực quan hóa góp phần thúc đẩy hướng nghiên cứu về khả năng diễn giải mô hình trong học sâu.&lt;/p&gt;

&lt;h2 id=&quot;các-bẫy-phổ-biến-và-thủ-thuật-thực-hành&quot;&gt;Các bẫy phổ biến và thủ thuật thực hành&lt;/h2&gt;

&lt;p&gt;Lỗi thường gặp nhất khi huấn luyện RNN là hiện tượng gradient bùng nổ. Dấu hiệu dễ nhận biết là giá trị mất mát đột ngột thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;, tham số tiến tới vô cực hoặc hàm mất mát dao động mạnh thay vì giảm dần. Nguyên nhân đến từ việc tích các gradient qua nhiều bước thời gian tăng theo hàm mũ. Giải pháp tiêu chuẩn là cắt ngưỡng gradient (&lt;em&gt;gradient clipping&lt;/em&gt;): tính chuẩn gradient toàn cục trên toàn bộ tham số \(\|\nabla_\theta \mathcal{L}\|_2 = \sqrt{\sum_\theta (\frac{\partial \mathcal{L}}{\partial \theta})^2}\), và nếu vượt ngưỡng (thường chọn từ 5 đến 10), nhân toàn bộ gradient với hệ số \(\frac{\text{threshold}}{\|\nabla_\theta \mathcal{L}\|_2}\). Cách làm này giữ nguyên hướng của vectơ gradient đồng thời ngăn bước cập nhật quá lớn. Cần áp dụng cắt theo chuẩn toàn cục thay vì cắt riêng từng phần tử để bảo toàn tỷ lệ tương đối giữa gradient của các tham số.&lt;/p&gt;

&lt;p&gt;Hiện tượng gradient biến mất khó phát hiện hơn vì quá trình huấn luyện vẫn diễn ra bình thường mà không báo lỗi, nhưng mô hình không học được các phụ thuộc tầm xa. Triệu chứng thường thấy là mô hình chỉ dựa vào ngữ cảnh rất gần (chẳng hạn chỉ xét vài từ cuối trong mô hình ngôn ngữ) hoặc thất bại ở các bài toán đòi hỏi nhớ thông tin từ đầu chuỗi dài. Để chẩn đoán, cần vẽ đồ thị độ lớn gradient theo số bước lan truyền ngược hoặc kiểm thử trên tác vụ bộ nhớ dài hạn. Các biện pháp khắc phục gồm chuyển sang LSTM/GRU, rút ngắn độ dài chuỗi lan truyền ngược (Truncated BPTT), hoặc bổ sung hàm mất mát phụ ở các bước trung gian để rút ngắn đường truyền gradient.&lt;/p&gt;

&lt;p&gt;Khởi tạo trọng số hồi quy ảnh hưởng trực tiếp tới sự ổn định của luồng gradient. Khởi tạo ngẫu nhiên nhỏ kiểu \(\mathbf{W}_{hh} \sim \mathcal{N}(0, 0.01^2)\) thường gây gradient biến mất ngay từ đầu. Giải pháp tốt hơn là khởi tạo trực giao: gán \(\mathbf{W}_{hh}\) bằng một ma trận trực giao ngẫu nhiên (thường thu được qua phân rã QR). Ma trận trực giao bảo toàn chuẩn vectơ qua phép nhân, giúp gradient không bị co nhỏ hay khuếch đại quá mức trong giai đoạn đầu huấn luyện (dù tính trực giao sẽ dần mất đi khi trọng số được cập nhật). Một lựa chọn khác là khởi tạo gần ma trận đơn vị: \(\mathbf{W}_{hh} = I + \mathcal{N}(0, 0.001^2)\), giúp trạng thái ẩn thay đổi chậm và hỗ trợ luồng gradient.&lt;/p&gt;

&lt;p&gt;Khi huấn luyện theo batch với các chuỗi có độ dài khác nhau, một số chuỗi sẽ kết thúc sớm hơn chuỗi dài nhất trong batch. Cách xử lý chuẩn là đệm (&lt;em&gt;padding&lt;/em&gt;) các chuỗi ngắn bằng token đặc biệt để đồng nhất độ dài, sau đó che (&lt;em&gt;masking&lt;/em&gt;) các vị trí đệm khi tính hàm mất mát để tránh sinh gradient nhiễu. Trong PyTorch, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PackedSequence&lt;/code&gt; giúp xử lý gọn vấn đề này bằng cách bỏ qua hoàn toàn phép tính trên các phần tử đệm.&lt;/p&gt;

&lt;p&gt;Việc chọn số chiều trạng thái ẩn \(d_h\) đòi hỏi cân nhắc kỹ lưỡng. Số chiều lớn tăng khả năng ghi nhớ các mẫu phức tạp và ngữ cảnh dài, nhưng làm số tham số của \(\mathbf{W}_{hh}\) tăng theo bình phương (\(d_h^2\)), kéo theo chi phí tính toán \(O(d_h^2)\) ở mỗi bước và tăng nguy cơ quá khớp trên tập dữ liệu nhỏ. Mức khởi điểm phổ biến là 128–256 cho mô hình cấp ký tự, hoặc 512–1024 cho mô hình ngôn ngữ cấp từ với bộ từ vựng lớn. Luôn cần kiểm chứng trên tập validation để phát hiện sớm hiện tượng quá khớp.&lt;/p&gt;

&lt;p&gt;Trong các mô hình chuỗi-sang-chuỗi, việc dùng &lt;em&gt;teacher forcing&lt;/em&gt; lúc huấn luyện nhưng sinh tự hồi quy lúc suy luận tạo ra độ lệch giữa hai giai đoạn. Khi huấn luyện với &lt;em&gt;teacher forcing&lt;/em&gt;, decoder luôn nhận token đúng của bước trước nên ít gặp tình huống đầu vào sai; nhưng khi suy luận, nó phải dùng chính dự đoán của mình, khiến sai số dễ tích lũy dần. Để giảm độ lệch này, có thể áp dụng &lt;em&gt;scheduled sampling&lt;/em&gt; (thay dần token đúng bằng token dự đoán trong quá trình huấn luyện với xác suất tăng dần) hoặc dùng hàm mất mát phụ nhằm tăng khả năng chống nhiễu đầu vào.&lt;/p&gt;

&lt;h2 id=&quot;điểm-chính&quot;&gt;Điểm chính&lt;/h2&gt;

&lt;p&gt;Mạng Neuron Hồi quy đưa khái niệm bộ nhớ vào mạng neuron thông qua trạng thái ẩn được duy trì theo thời gian, giúp mô hình hóa hiệu quả các dữ liệu tuần tự mà thứ tự và ngữ cảnh đóng vai trò quyết định. Cơ chế chia sẻ tham số qua các bước thời gian cho phép RNN tổng quát hóa sang nhiều độ dài chuỗi khác nhau. Tuy nhiên, cấu trúc hồi quy cũng kéo theo ba hạn chế lớn: xử lý tuần tự khó song song hóa trên GPU, tích các ma trận Jacobian gây gradient biến mất hoặc bùng nổ khiến khó học phụ thuộc tầm xa, và trạng thái ẩn kích thước cố định tạo nút thắt thông tin trên chuỗi dài. Dù vậy, các nguyên lý mà RNN thiết lập — duy trì trạng thái theo thời gian và mô hình hóa tường minh cấu trúc chuỗi — vẫn là nền tảng cho các kiến trúc kế tiếp như LSTM và Transformer.&lt;/p&gt;

&lt;p&gt;Bước chuyển từ mạng feedforward sang RNN đánh dấu sự mở rộng quan trọng của học sâu: từ xử lý các đầu vào tĩnh độc lập sang mô hình hóa các quá trình động có bộ nhớ và cấu trúc thời gian, mở đường cho nhiều hướng nghiên cứu kiến trúc mô hình chuỗi hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Hướng dẫn chi tiết mô hình ngôn ngữ cấp ký tự và hàm mất mát huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=L8HKweZIOmg&quot;&gt;Sequence-to-Sequence (seq2seq) Encoder-Decoder Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Giải thích mô hình encoder-decoder chuỗi-sang-chuỗi, kiến trúc liên quan trực tiếp đến phần khái niệm và bẫy thường gặp trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qhXZsFVxGKo&quot;&gt;Vanishing/Exploding Gradients (C2W1L10)&lt;/a&gt; — DeepLearningAI (tiếng Anh). Phân tích hiện tượng gradient biến mất và bùng nổ qua tích nhiều bước trong lan truyền ngược theo thời gian.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-01-02-01 Triển khai Cốt lõi RNN</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_01_02_01_RNN_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_01_02_01_RNN_Core_Code</id>
   <content type="html">&lt;p&gt;Tự viết một ô RNN bằng NumPy và tự tính lan truyền ngược BPTT bằng tay là bài tập “nhập môn vàng” giúp bạn nhìn thấy rõ ràng từng ma trận gradient cộng dồn qua từng bước thời gian — và cũng là cách nhanh nhất để hiểu vì sao một lỗi nhỏ như quên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clip_grad_norm_&lt;/code&gt; có thể làm toàn bộ trọng số nổ tung thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; chỉ sau vài chục vòng lặp.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-thành-phần-cốt-lõi-trong-mã-nguồn-rnn&quot;&gt;Kiến thức cần nhớ: Bốn thành phần cốt lõi trong mã nguồn RNN&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bộ nhớ đệm trạng thái (Forward Cache)&lt;/strong&gt;:
Trong lượt truyền xuôi, ta bắt buộc phải lưu lại toàn bộ danh sách \(h_0, h_1, \dots, h_T\) và \(x_1, \dots, x_T\) vì lượt BPTT cần chính các giá trị này để tính đạo hàm \((1 - h_t^2)\) và tích ngoài \(d z_t \cdot h_{t-1}^T\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đóng gói gradient truyền lùi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dh_next&lt;/code&gt;&lt;/strong&gt;:
Tại bước \(t\), tổng gradient đổ vào \(h_t\) gồm &lt;strong&gt;hai nhánh&lt;/strong&gt;: nhánh từ mất mát đầu ra \(\hat{y}_t\) tại chính thời điểm \(t\), cộng với nhánh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dh_next&lt;/code&gt; truyền ngược từ bước tương lai \(t+1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa cắt gradient (Global Norm Clipping)&lt;/strong&gt;:
Thay vì cắt rời rạc từng phần tử làm lệch hướng vector gradient, PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clip_grad_norm_&lt;/code&gt; co giãn đồng đều toàn bộ vector gradient nếu chuẩn \(L_2\) vượt ngưỡng \(\theta\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra chéo bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt; và tác vụ dự đoán chuỗi số&lt;/strong&gt;:
Thử nghiệm trên bài toán dự đoán bước kế tiếp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1, 2, 3] -&amp;gt; [2, 3, 4]&lt;/code&gt; giúp xác minh nhanh độ đúng của hình dạng tensor, hàm mất mát và luồng cập nhật trọng số trước khi mở rộng lên bài toán lớn.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-phép-cắt-gradient-theo-chuẩn-l_2-gradient-norm-clipping&quot;&gt;Giải thích: Tính tay phép Cắt Gradient theo Chuẩn \(L_2\) (Gradient Norm Clipping)&lt;/h3&gt;

&lt;p&gt;Giả sử sau một bước BPTT, vector gradient thu được là \(\mathbf{g} = [3{,}0, \; -4{,}0]\) và ta đặt ngưỡng cắt \(\theta = 2{,}0\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Tính chuẩn \(L_2\) của vector gradient&lt;/strong&gt;:
\(\|\mathbf{g}\|_2 = \sqrt{3{,}0^2 + (-4{,}0)^2} = \sqrt{9 + 16} = \mathbf{5{,}0}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — So sánh với ngưỡng \(\theta = 2{,}0\)&lt;/strong&gt;:
Vì \(5{,}0 &amp;gt; 2{,}0\), ta tính hệ số co tỷ lệ: \(\text{scale} = \frac{\theta}{\|\mathbf{g}\|_2} = \frac{2{,}0}{5{,}0} = \mathbf{0{,}4}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Nhân đồng đều để giữ nguyên hướng dốc&lt;/strong&gt;:
\(\mathbf{g}_{\text{clipped}} = 0{,}4 \times [3{,}0, \; -4{,}0] = \mathbf{[1{,}2, \; -1{,}6]}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng lại chuẩn mới&lt;/strong&gt;: \(\sqrt{1{,}2^2 + (-1{,}6)^2} = \sqrt{1{,}44 + 2{,}56} = \sqrt{4} = \mathbf{2{,}0}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Hướng bước nhảy vẫn giữ tỷ lệ \(3 : (-4)\) y nguyên, nhưng độ dài bước đã được thuần hóa an toàn về đúng ngưỡng \(2{,}0\)!&lt;/p&gt;

&lt;h2 id=&quot;4-đoạn-code&quot;&gt;4. Đoạn Code&lt;/h2&gt;

&lt;p&gt;Phần này trình bày cách cài đặt RNN từ đầu bằng NumPy để theo dõi rõ từng phép toán, sau đó đối chiếu với cách cài đặt chuẩn bằng PyTorch:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VanillaRNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Triển khai RNN vanilla từ đầu bằng NumPy.
    
    Bản triển khai này ưu tiên độ rõ ràng hơn hiệu năng. Ta sẽ thấy chính xác
    trạng thái ẩn tiến hóa ra sao theo thời gian, gradient chảy ngược thế nào,
    và gradient biến mất xuất phát từ đâu. Hiểu triển khai thủ công này
    rất quan trọng khi debug huấn luyện RNN và để đánh giá những gì framework
    hiện đại làm tự động.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Khởi tạo RNN với khởi tạo trọng số cẩn thận.
        
        Với RNN, khởi tạo còn quan trọng hơn mạng feedforward.
        Trọng số hồi quy Whh quyết định trị riêng của động lực trạng thái ẩn.
        Nếu trị riêng quá lớn (&amp;gt; 1), trạng thái ẩn bùng nổ. Quá nhỏ (&amp;lt; 1),
        chúng biến mất. Ta khởi tạo giá trị ngẫu nhiên nhỏ với hy vọng rơi vào
        chế độ ổn định, dù điều này thường thất bại với RNN vanilla.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Trọng số đầu vào sang ẩn: ánh xạ không gian đầu vào sang không gian ẩn
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Scale theo 1/√hidden_size để duy trì phương sai
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wxh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Trọng số ẩn sang ẩn: ma trận quan trọng nhất cho động lực thời gian
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Một số người khởi tạo identity + nhiễu để luồng gradient ban đầu tốt hơn
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Whh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Trọng số ẩn sang đầu ra
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Bias
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Forward pass qua toàn bộ chuỗi.
        
        inputs: list các vectơ đầu vào [x_1, x_2, ..., x_T], mỗi x_t là (input_size, 1)
        h_prev: trạng thái ẩn ban đầu (hidden_size, 1)
        
        Returns:
            outputs: list các vectơ đầu ra [y_1, y_2, ..., y_T]
            hidden_states: list các trạng thái ẩn [h_0, h_1, ..., h_T]
            
        Ta phải lưu TẤT CẢ trạng thái ẩn vì backpropagation through time
        cần chúng. Điều này tạo chi phí bộ nhớ tuyến tính theo độ dài chuỗi,
        trở nên quá tải với các chuỗi rất dài.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Xử lý chuỗi từng bước một
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Vòng lặp tuần tự này là không thể tránh trong RNN — ta không thể
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# song song hóa qua thời gian vì h_t phụ thuộc h_{t-1}
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật trạng thái ẩn: kết hợp trạng thái trước và đầu vào hiện tại
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# tanh giới hạn kích hoạt trong [-1, 1], ngăn bùng nổ
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# (dù gây bão hòa và gradient biến mất)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Whh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wxh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Tính đầu ra từ trạng thái ẩn
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Với phân loại chuỗi, ta chỉ dùng đầu ra cuối
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Với gán nhãn chuỗi, ta dùng tất cả đầu ra
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Backpropagation Through Time (BPTT).
        
        Đây là nơi RNN trở nên thách thức. Ta phải backpropagate gradient
        không chỉ qua các lớp (như mạng feedforward) mà còn ngược theo thời gian.
        Gradient của loss theo Whh bao gồm đóng góp từ mọi bước thời gian,
        tạo ra tích dài các Jacobian dẫn đến gradient biến mất/bùng nổ.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Khởi tạo bộ tích lũy gradient
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Chúng sẽ tích lũy gradient từ mọi bước thời gian
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wxh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Whh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient chảy ngược qua thời gian
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Ban đầu bằng zero, sẽ tích lũy khi ta backprop qua thời gian
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dh_next&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backpropagate through time (từ T xuống 1)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;reversed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Sai số đầu ra tại bước thời gian này
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Với MSE loss: dy = y_pred - y_true
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Gradient của tham số lớp đầu ra
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Backprop vào trạng thái ẩn
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Hai nguồn gradient: từ đầu ra tại bước này (dy)
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# và từ các bước tương lai (dh_next)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dh_next&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Backprop qua phi tuyến tanh
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# tanh&apos;(z) = 1 - tanh^2(z) = 1 - h^2
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Đạo hàm này tiến về 0 khi |h| tiến về 1 (bão hòa)
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# gây gradient biến mất
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dh&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Gradient của tham số lớp ẩn
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dz&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Truyền gradient sang bước thời gian trước
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Đây là nơi tích các Jacobian xảy ra
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# dh_next sẽ được dùng ở bước t-1
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dh_next&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Whh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dz&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Clip gradient để ngăn bùng nổ
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Đây là một &quot;hack&quot;, nhưng cần thiết cho RNN vanilla
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Ta đang xử lý triệu chứng (gradient lớn) chứ không phải nguyên nhân
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# (bất ổn định cơ bản của động lực hồi quy)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;update_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cập nhật gradient descent chuẩn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wxh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Whh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Minh họa trên tác vụ dự đoán chuỗi đơn giản
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vanilla RNN: Dự đoán số tiếp theo trong chuỗi&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tác vụ: Cho [1, 2, 3], dự đoán [2, 3, 4]
# Kiểm tra xem RNN có học được mẫu tuần tự đơn giản không
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_sequence_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_sequences&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Sinh dữ liệu huấn luyện: chuỗi các số tăng dần
    Đầu vào: [start, start+1, start+2, ...]
    Mục tiêu: [start+1, start+2, start+3, ...]
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sequences_in&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sequences_target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;sequences_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;sequences_target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequences_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequences_target&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo RNN
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VanillaRNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sinh dữ liệu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_sequence_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_sequences&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vòng huấn luyện
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huấn luyện RNN để dự đoán số tiếp theo...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính loss (MSE)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Cập nhật
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;update_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Average Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm thử trên chuỗi mới
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kiểm thử trên chuỗi mới: [10, 11, 12, 13, 14, 15, 16, 17]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;17&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;h_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dự đoán:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Sau khi thấy &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, dự đoán tiếp: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (đúng: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lưu ý: RNN vanilla gặp khó với tác vụ đơn giản này do gradient biến mất!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Điều này thúc đẩy kiến trúc LSTM/GRU sẽ được đề cập ở chương tiếp theo.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Tiếp theo là cách cài đặt RNN bằng PyTorch, nơi quá trình tính toán hồi quy và lan truyền ngược được xử lý tự động:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RNNSequenceModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    RNN hiện đại dùng layer RNN tích hợp của PyTorch.
    
    PyTorch xử lý tính toán hồi quy hiệu quả, unrolling vòng lặp
    trong C++ tối ưu và quản lý gradient tự động. Nhanh hơn nhiều so với
    triển khai NumPy của ta và xử lý batching một cách thanh lịch.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;RNNSequenceModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Module RNN của PyTorch xử lý tính toán hồi quy
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# num_layers &amp;gt; 1 tạo RNN xếp chồng (đầu ra của lớp này làm đầu vào lớp sau)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# batch_first=True nghĩa là shape đầu vào là (batch, seq_len, input_size)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;RNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                         &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nonlinearity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lớp đầu ra ánh xạ trạng thái ẩn sang dự đoán
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (batch, seq_len, input_size)
        hidden: trạng thái ẩn ban đầu tùy chọn (num_layers, batch, hidden_size)
        
        Returns:
            output: (batch, seq_len, output_size)
            hidden: trạng thái ẩn cuối
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Nếu không cung cấp trạng thái ẩn ban đầu, RNN khởi tạo về zero
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_cuda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cuda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# RNN trả về:
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# - rnn_out: trạng thái ẩn ở mọi bước thời gian (batch, seq_len, hidden_size)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# - hidden: trạng thái ẩn cuối (num_layers, batch, hidden_size)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;rnn_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Áp dụng lớp đầu ra cho mỗi bước thời gian
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Reshape thành (batch * seq_len, hidden_size) để tính toán hiệu quả
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rnn_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;rnn_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rnn_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnn_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy (tiếng Anh). Cài đặt mô hình ngôn ngữ cấp ký tự từ đầu trong notebook, khớp với vòng lặp huấn luyện cốt lõi của bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 10&lt;/td&gt;
          &lt;td&gt;Recurrent Neural Networks](https://www.youtube.com/watch?v=6niqTuYFZLQ) — Stanford University School of Engineering (tiếng Anh). Trình bày các phương trình toán học tương ứng với phần mã nguồn trên.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Tóm tắt trực quan một bước tính toán RNN, hữu ích để xem nhanh trước khi đọc mã nguồn đầy đủ.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-01-01 Lý thuyết và Trực giác RNN</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_01_01_RNN_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_01_01_RNN_Theory</id>
   <content type="html">&lt;p&gt;Vào năm 1994, Yoshua Bengio và cộng sự công bố một kết quả lý thuyết gây chấn động: nếu một hệ động lực rời rạc như RNN lưu trữ thông tin bền vững qua nhiều bước thời gian, thì về mặt toán học nó &lt;strong&gt;bắt buộc&lt;/strong&gt; phải đối mặt với sự suy giảm theo hàm mũ của gradient khi lan truyền ngược. Hiểu phương trình toán học của RNN và BPTT không chỉ là chuyện đạo hàm — đó là chìa khóa lý giải toàn bộ lịch sử tiến hóa của NLP hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-mảnh-ghép-lý-thuyết-của-rnn&quot;&gt;Kiến thức cần nhớ: Bốn mảnh ghép lý thuyết của RNN&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hệ phương trình trạng thái và đầu ra&lt;/strong&gt;:
\(h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h)\) và \(\hat{y}_t = \text{softmax}(W_{hy} h_t + b_y)\), trong đó \(h_t \in \mathbb{R}^{d_h}\) đóng vai trò tóm tắt toàn bộ tiền tố \((x_1, \dots, x_t)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đồ thị tính toán trải phẳng (Unrolled Computation Graph)&lt;/strong&gt;:
Mỗi bước thời gian dùng chung ma trận \(W_{hh}\), nên theo quy tắc đạo hàm toàn phần, tổng gradient \(\frac{\partial \mathcal{L}}{\partial W_{hh}}\) là &lt;strong&gt;tổng&lt;/strong&gt; đóng góp từ mọi bước \(t = 1 \dots T\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giải phẫu công thức BPTT&lt;/strong&gt;:
\(\frac{\partial h_t}{\partial h_k} = \prod_{j=k+1}^{t} \operatorname{diag}\!\big(1 - h_j^2\big) W_{hh}\) — tích của \((t - k)\) ma trận Jacobian giải thích trực tiếp hiện tượng triệt tiêu hoặc bùng nổ gradient.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cắt xén gradient (Gradient Clipping) và Truncated BPTT&lt;/strong&gt;:
Gradient clipping chặn chuẩn \(\|\mathbf{g}\|_2 \le \theta\) trị dứt điểm bùng nổ gradient, nhưng &lt;strong&gt;không&lt;/strong&gt; cứu được gradient biến mất; còn Truncated BPTT giới hạn cửa sổ truyền ngược \(K\) bước để tiết kiệm bộ nhớ.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-bước-bptt-qua-2-thời-điểm-để-thấy-tích-jacobian&quot;&gt;Giải thích: Tính tay một bước BPTT qua 2 thời điểm để thấy tích Jacobian&lt;/h3&gt;

&lt;p&gt;Giả sử RNN vô hướng có \(W_{hh} = 0{,}8\), không có đầu vào mới ở bước 2, với trạng thái đã tính ở forward là \(h_1 = 0{,}5\) và \(h_2 = \tanh(0{,}8 \times 0{,}5) = \tanh(0{,}4) \approx 0{,}380\). Giả sử hàm mất mát chỉ đặt ở bước cuối \(\mathcal{L} = \frac{1}{2}(h_2 - 1)^2\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đạo hàm tại bước cuối \(t=2\)&lt;/strong&gt;:
\(\frac{\partial \mathcal{L}}{\partial h_2} = h_2 - 1 = 0{,}380 - 1 = \mathbf{-0{,}620}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đạo hàm hàm kích hoạt \(\tanh&apos;(z_2) = 1 - h_2^2\)&lt;/strong&gt;:
\(1 - (0{,}380)^2 = 1 - 0{,}1444 = \mathbf{0{,}8556}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Truyền ngược một bước về \(h_1\)&lt;/strong&gt;:
\(\frac{\partial \mathcal{L}}{\partial h_1} = \frac{\partial \mathcal{L}}{\partial h_2} \cdot (1 - h_2^2) \cdot W_{hh} = (-0{,}620) \times 0{,}8556 \times 0{,}8 \approx \mathbf{-0{,}4244}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient đối với \(W_{hh}\) tại bước 2&lt;/strong&gt;:
\(\left.\frac{\partial \mathcal{L}}{\partial W_{hh}}\right|_{t=2} = \frac{\partial \mathcal{L}}{\partial h_2} \cdot (1 - h_2^2) \cdot h_1 = (-0{,}620) \times 0{,}8556 \times 0{,}5 \approx \mathbf{-0{,}2652}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mỗi lần lùi thêm 1 bước thời gian, tín hiệu lỗi bị nhân thêm một thừa số \((1 - h_j^2) W_{hh} \approx 0{,}684 &amp;lt; 1\) — chỉ sau 15 bước, tín hiệu này co lại chỉ còn \(0{,}684^{15} \approx 0{,}0033\) (chưa tới 0,4% độ lớn ban đầu!).&lt;/p&gt;

&lt;h1 id=&quot;mạng-neuron-hồi-quy-xử-lý-dữ-liệu-tuần-tự&quot;&gt;Mạng Neuron Hồi quy: Xử lý Dữ liệu Tuần tự&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter05/rnn_unrolled_architecture.png&quot; alt=&quot;RNN Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc RNN và quá trình trải mạng theo thời gian. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Mạng Neuron Hồi quy (RNN) tiếp cận dữ liệu theo cách khác biệt căn bản so với mạng truyền thẳng (feedforward). Trong khi mạng feedforward xử lý mỗi đầu vào một cách độc lập, coi từng hình ảnh hay vectơ đặc trưng là một mẫu riêng rẽ, RNN được thiết kế chuyên biệt cho dữ liệu tuần tự — nơi thứ tự các phần tử quyết định ý nghĩa và ngữ cảnh trước đó ảnh hưởng trực tiếp đến cách diễn giải phần tử hiện tại. Việc bổ sung bộ nhớ cho mạng neuron cho phép mô hình xử lý nhiều bài toán mà mạng feedforward không đáp ứng tốt: ngôn ngữ tự nhiên (thứ tự từ quyết định ngữ nghĩa), giọng nói (các âm vị nối tiếp theo thời gian), chuỗi thời gian tài chính (xu hướng quá khứ hỗ trợ dự báo tương lai) và video (chuỗi khung hình liên kết thành diễn biến).&lt;/p&gt;

&lt;p&gt;Ý tưởng cốt lõi của RNN là duy trì một trạng thái ẩn đóng vai trò bộ nhớ. Tại mỗi bước thời gian, mạng tiếp nhận đầu vào mới cùng trạng thái ẩn từ bước trước, xử lý cả hai bằng cùng một tập trọng số để tạo ra trạng thái ẩn mới và đầu ra tương ứng. Cơ chế hồi quy này — dùng chung tham số qua mọi bước thời gian trong khi trạng thái ẩn liên tục được cập nhật — cho phép mạng xử lý chuỗi có độ dài bất kỳ. Tương tự cách mạng tích chập (CNN) chia sẻ trọng số trong không gian để phát hiện đặc trưng ở mọi vị trí trên ảnh, RNN chia sẻ trọng số theo thời gian để nhận diện các mẫu tuần tự bất kể chúng xuất hiện ở đâu trong chuỗi.&lt;/p&gt;

&lt;p&gt;Lý do ra đời của RNN gắn liền với đặc thù độ dài biến thiên của dữ liệu tuần tự: một câu có thể gồm 5 từ hoặc 50 từ, một đoạn âm thanh có thể dài 3 giây hoặc 3 phút. Nếu thiết kế tham số riêng cho từng bước thời gian, mô hình sẽ phình to số lượng tham số và không thể tổng quát hóa sang những chuỗi dài hơn dữ liệu huấn luyện. Bằng cách áp dụng lặp lại cùng một phép biến đổi ở mọi bước và dùng trạng thái ẩn mang thông tin từ quá khứ, RNN vừa tiết kiệm tham số vừa có khả năng xử lý chuỗi dài tùy ý về mặt lý thuyết.&lt;/p&gt;

&lt;p&gt;Tuy vậy, RNN cũng có những hạn chế đáng kể. Chính tính tuần tự khiến mô hình chậm khi tính toán: bước \(t\) chỉ có thể thực hiện sau khi hoàn tất bước \(t-1\), làm hạn chế khả năng song song hóa trên GPU. Khi lan truyền ngược qua nhiều bước thời gian, gradient dễ bị biến mất hoặc bùng nổ, gây khó khăn cho việc học phụ thuộc tầm xa. Bên cạnh đó, trạng thái ẩn có kích thước cố định tạo nên nút thắt thông tin, khiến việc nén toàn bộ lịch sử của chuỗi dài ngày càng khó khăn. Những giới hạn này đã thúc đẩy sự ra đời của LSTM, GRU và sau đó là cơ chế attention cùng kiến trúc Transformer.&lt;/p&gt;

&lt;p&gt;Dù vậy, RNN vẫn giữ vai trò quan trọng trong học sâu. Kiến trúc này đặt nền tảng cho khái niệm bộ nhớ trong mạng neuron, minh họa rõ ưu nhược điểm của xử lý tuần tự và làm sáng tỏ các vấn đề về luồng gradient trong mạng sâu. Ngoài ra, trong một số ứng dụng xử lý trực tuyến (streaming) hoặc môi trường ưu tiên hiệu suất trên CPU thay vì thông lượng GPU, RNN và các biến thể của nó vẫn là lựa chọn phù hợp.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Công thức toán học của RNN thể hiện rõ cả sự gọn nhẹ lẫn nguồn gốc của các thách thức huấn luyện. Tại mỗi bước thời gian \(t\), RNN duy trì trạng thái ẩn \(\mathbf{h}_t\) nhằm tóm lược thông tin chuỗi tính đến bước đó. Khi nhận đầu vào mới \(\mathbf{x}_t\), trạng thái ẩn được cập nhật theo phương trình:&lt;/p&gt;

\[\mathbf{h}_t = f(\mathbf{W}_{hh}\mathbf{h}_{t-1} + \mathbf{W}_{xh}\mathbf{x}_t + \mathbf{b}_h)\]

&lt;p&gt;trong đó \(f\) là hàm kích hoạt phi tuyến (thường là \(\tanh\) ở RNN cơ bản), \(\mathbf{W}_{hh}\) điều khiển mức độ ảnh hưởng của trạng thái trước lên trạng thái hiện tại (trọng số hồi quy), \(\mathbf{W}_{xh}\) ánh xạ đầu vào hiện tại và \(\mathbf{b}_h\) là vectơ độ lệch (bias).&lt;/p&gt;

&lt;p&gt;Phương trình này hàm chứa hai đặc điểm thiết kế quan trọng. Thứ nhất, các ma trận trọng số \(\mathbf{W}_{hh}\) và \(\mathbf{W}_{xh}\) được dùng chung ở tất cả các bước thời gian. Nhờ cơ chế chia sẻ tham số này, RNN có thể tổng quát hóa trên nhiều độ dài chuỗi khác nhau và phát hiện các mẫu thời gian không phụ thuộc vào vị trí tuyệt đối, tương tự cách bộ lọc tích chập phát hiện cạnh ở bất kỳ vị trí nào trên ảnh.&lt;/p&gt;

&lt;p&gt;Thứ hai, trạng thái ẩn \(\mathbf{h}_t\) vừa đóng vai trò bộ nhớ (lưu trữ thông tin từ các đầu vào trước), vừa làm đầu vào cho bước kế tiếp. Điều này tạo ra một vòng phản hồi đệ quy: trạng thái hiện tại phụ thuộc vào trạng thái trước đó, và tiếp tục truy ngược về tận đầu chuỗi. Khi khai triển phép đệ quy này, ta có:&lt;/p&gt;

\[\mathbf{h}_t = f(\mathbf{W}_{hh}f(\mathbf{W}_{hh}\mathbf{h}_{t-2} + \mathbf{W}_{xh}\mathbf{x}_{t-1} + \mathbf{b}_h) + \mathbf{W}_{xh}\mathbf{x}_t + \mathbf{b}_h)\]

&lt;p&gt;Biểu thức trên cho thấy \(\mathbf{h}_t\) phụ thuộc vào \(\mathbf{x}_t\), \(\mathbf{x}_{t-1}\) và lần ngược về toàn bộ các đầu vào cho tới \(\mathbf{x}_1\). Chuỗi hàm hợp lồng nhau này giúp RNN mô hình hóa được các phụ thuộc thời gian phức tạp, nhưng cũng khiến việc huấn luyện trở nên khó khăn vì gradient phải lan truyền ngược qua toàn bộ chuỗi hàm hợp đó.&lt;/p&gt;

&lt;p&gt;Đầu ra tại mỗi bước thời gian được tính từ trạng thái ẩn:&lt;/p&gt;

\[\mathbf{y}_t = g(\mathbf{W}_{hy}\mathbf{h}_t + \mathbf{b}_y)\]

&lt;p&gt;trong đó \(g\) là hàm kích hoạt phù hợp với bài toán (softmax cho phân loại đa lớp, tuyến tính cho hồi quy, sigmoid cho phân loại nhị phân hoặc đa nhãn). Ma trận \(\mathbf{W}_{hy}\) cũng được chia sẻ qua mọi bước thời gian, tức là mạng dùng chung một bộ giải mã để đọc trạng thái ẩn ở mọi thời điểm, buộc trạng thái ẩn duy trì một cách biểu diễn nhất quán xuyên suốt chuỗi.&lt;/p&gt;

&lt;p&gt;Kích thước của các ma trận trọng số quyết định chi phí tính toán và năng lực biểu diễn. Với chiều đầu vào \(d_x\), chiều trạng thái ẩn \(d_h\) và chiều đầu ra \(d_y\), ta có:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{W}_{xh} \in \mathbb{R}^{d_h \times d_x}\): Chiếu đầu vào sang không gian ẩn.&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}_{hh} \in \mathbb{R}^{d_h \times d_h}\): Kết nối hồi quy (đóng vai trò quyết định).&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}_{hy} \in \mathbb{R}^{d_y \times d_h}\): Chiếu trạng thái ẩn sang không gian đầu ra.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ma trận hồi quy \(\mathbf{W}_{hh}\) đặc biệt quan trọng vì nó quyết định cách thông tin tồn tại theo thời gian. Nếu \(\mathbf{W}_{hh}\) gần ma trận không, trạng thái ẩn sẽ nhanh chóng quên các đầu vào cũ; nếu gần ma trận đơn vị, trạng thái ẩn thay đổi chậm hơn. Các trị riêng của \(\mathbf{W}_{hh}\) kiểm soát trực tiếp luồng gradient trong quá trình lan truyền ngược theo thời gian.&lt;/p&gt;

&lt;p&gt;Tùy vào yêu cầu bài toán, RNN được tổ chức theo nhiều dạng kiến trúc khác nhau. Với bài toán phân loại chuỗi (phân tích cảm xúc, phân loại video), mạng xử lý toàn bộ chuỗi và thường chỉ dùng trạng thái ẩn cuối cùng để dự đoán: \(\mathbf{y} = g(\mathbf{W}_{hy}\mathbf{h}_T + \mathbf{b}_y)\), buộc \(\mathbf{h}_T\) phải tóm lược cả chuỗi. Với bài toán gán nhãn chuỗi (gán nhãn từ loại, nhận diện thực thể), mạng sinh đầu ra tại từng bước: \(\mathbf{y}_t = g(\mathbf{W}_{hy}\mathbf{h}_t + \mathbf{b}_y)\) cho mọi \(t\). Với bài toán chuỗi-sang-chuỗi (dịch máy), một RNN đóng vai trò bộ mã hóa (encoder) nén chuỗi đầu vào thành trạng thái ẩn cuối cùng để khởi tạo RNN giải mã (decoder) sinh chuỗi đầu ra.&lt;/p&gt;

&lt;p&gt;Việc huấn luyện RNN sử dụng thuật toán Lan truyền ngược theo thời gian (Backpropagation Through Time — BPTT), thực chất là thuật toán lan truyền ngược áp dụng trên đồ thị tính toán đã trải của RNN. Hàm mất mát trên một chuỗi thường là tổng mất mát tại các bước thời gian:&lt;/p&gt;

\[\mathcal{L} = \sum_{t=1}^{T} \mathcal{L}_t(\mathbf{y}_t, \hat{\mathbf{y}}_t)\]

&lt;p&gt;Vì \(\mathbf{W}_{hh}\) tham gia tính toán ở mọi bước thời gian, gradient của hàm mất mát theo \(\mathbf{W}_{hh}\) là tổng đóng góp từ tất cả các bước:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}_{hh}} = \sum_{t=1}^{T} \frac{\partial \mathcal{L}_t}{\partial \mathbf{W}_{hh}}\]

&lt;p&gt;Mỗi số hạng \(\frac{\partial \mathcal{L}_t}{\partial \mathbf{W}_{hh}}\) đòi hỏi lan truyền ngược qua các bước từ \(1\) đến \(t\) theo quy tắc dây chuyền, bởi \(\mathbf{W}_{hh}\) tác động lên \(\mathbf{h}_1\), \(\mathbf{h}_1\) tác động lên \(\mathbf{h}_2\), cho tới \(\mathbf{h}_t\). Đồ thị tính toán vì thế phình to theo độ dài chuỗi, vừa tốn bộ nhớ (do phải lưu toàn bộ các trạng thái ẩn trung gian), vừa dẫn tới hiện tượng gradient biến mất hoặc bùng nổ.&lt;/p&gt;

&lt;p&gt;Phân tích luồng gradient cho thấy rõ nguyên nhân cốt lõi. Đạo hàm của \(\mathbf{h}_t\) theo \(\mathbf{h}_k\) (với \(k &amp;lt; t\)) là tích của các ma trận Jacobian:&lt;/p&gt;

\[\frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_k} = \prod_{i=k+1}^{t} \frac{\partial \mathbf{h}_i}{\partial \mathbf{h}_{i-1}}\]

&lt;p&gt;Mỗi ma trận Jacobian \(\frac{\partial \mathbf{h}_i}{\partial \mathbf{h}_{i-1}} = \text{diag}(f&apos;(\mathbf{z}_i)) \mathbf{W}_{hh}\) là tích của đạo hàm hàm kích hoạt (với \(\tanh\) thì bị chặn bởi 1) và ma trận trọng số hồi quy. Nếu giá trị kỳ dị lớn nhất của \(\mathbf{W}_{hh}\) nhỏ hơn 1, tích này giảm theo hàm mũ theo số bước thời gian, gây ra hiện tượng gradient biến mất; ngược lại, nếu lớn hơn 1, tích này tăng bùng nổ theo hàm mũ. Đây là thách thức căn bản khi huấn luyện RNN học các phụ thuộc tầm xa.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và Trực giác&lt;/h2&gt;

&lt;p&gt;Để hình dung cụ thể cách RNN xử lý chuỗi, hãy xét bài toán phân tích cảm xúc trên câu “Con mèo ngồi trên tấm thảm” bằng một RNN có trạng thái ẩn 3 chiều (kích thước nhỏ để dễ theo dõi) nhằm dự đoán sắc thái tích cực hoặc tiêu cực.&lt;/p&gt;

&lt;p&gt;Ban đầu, trước khi đọc từ nào, ta khởi tạo \(\mathbf{h}_0 = \mathbf{0}\) để biểu diễn trạng thái chưa có thông tin. Từ đầu tiên “Con” được đưa vào dưới dạng vectơ nhúng \(\mathbf{x}_1 = [0.2, -0.1, 0.5]\). Giả sử các ma trận trọng số được khởi tạo với các giá trị nhỏ:&lt;/p&gt;

\[\mathbf{W}_{hh} = \begin{bmatrix} 0.5 &amp;amp; 0.1 &amp;amp; -0.2 \\ -0.1 &amp;amp; 0.6 &amp;amp; 0.3 \\ 0.2 &amp;amp; -0.3 &amp;amp; 0.4 \end{bmatrix}, \quad \mathbf{W}_{xh} = \begin{bmatrix} 0.3 &amp;amp; 0.2 &amp;amp; -0.1 \\ 0.1 &amp;amp; -0.2 &amp;amp; 0.4 \\ -0.2 &amp;amp; 0.3 &amp;amp; 0.1 \end{bmatrix}\]

&lt;p&gt;Bước cập nhật trạng thái ẩn tính:&lt;/p&gt;

\[\mathbf{z}_1 = \mathbf{W}_{hh}\mathbf{h}_0 + \mathbf{W}_{xh}\mathbf{x}_1 + \mathbf{b}_h = \mathbf{0} + \mathbf{W}_{xh}\mathbf{x}_1 + \mathbf{b}_h\]

&lt;p&gt;Do \(\mathbf{h}_0 = \mathbf{0}\), trạng thái ẩn đầu tiên chỉ phụ thuộc vào từ thứ nhất:&lt;/p&gt;

\[\mathbf{h}_1 = \tanh(\mathbf{z}_1) = \tanh\begin{pmatrix}\begin{bmatrix} 0.3 &amp;amp; 0.2 &amp;amp; -0.1 \\ 0.1 &amp;amp; -0.2 &amp;amp; 0.4 \\ -0.2 &amp;amp; 0.3 &amp;amp; 0.1 \end{bmatrix} \begin{bmatrix} 0.2 \\ -0.1 \\ 0.5 \end{bmatrix} + \mathbf{b}_h\end{pmatrix}\]

&lt;p&gt;Giả sử sau khi qua \(\tanh\) ta thu được \(\mathbf{h}_1 = [0.1, 0.05, -0.15]\). Vectơ này mã hóa thông tin “đã thấy từ ‘Con’”. Tiếp theo, từ “mèo” đi vào với \(\mathbf{x}_2 = [0.8, 0.3, -0.2]\). Lúc này phép cập nhật có hai thành phần:&lt;/p&gt;

\[\mathbf{z}_2 = \mathbf{W}_{hh}\mathbf{h}_1 + \mathbf{W}_{xh}\mathbf{x}_2 + \mathbf{b}_h\]

&lt;p&gt;Thành phần \(\mathbf{W}_{hh}\mathbf{h}_1\) mang thông tin từ “Con”, còn \(\mathbf{W}_{xh}\mathbf{x}_2\) xử lý từ “mèo”. Hàm phi tuyến \(\tanh\) tổng hợp cả hai:&lt;/p&gt;

\[\mathbf{h}_2 = \tanh(\mathbf{z}_2)\]

&lt;p&gt;Trạng thái \(\mathbf{h}_2\) hiện mã hóa ngữ cảnh “đã thấy ‘Con mèo’”, trong đó ảnh hưởng của “Con” được truyền gián tiếp qua \(\mathbf{h}_1\) và ma trận \(\mathbf{W}_{hh}\).&lt;/p&gt;

&lt;p&gt;Khi tiếp tục đi qua các từ “ngồi”, “trên”, “tấm”, “thảm”, mỗi trạng thái ẩn mới lại tích hợp thêm ngữ cảnh. Đến cuối câu, \(\mathbf{h}_6\) về mặt lý thuyết đại diện cho ý nghĩa của cả câu và được dùng để dự đoán cảm xúc:&lt;/p&gt;

\[\text{cam_xuc} = \text{sigmoid}(\mathbf{W}_{hy}\mathbf{h}_6 + \mathbf{b}_y)\]

&lt;p&gt;Điểm mấu chốt là thông tin từ từ “Con” ở đầu câu phải đi qua chuỗi chuyển đổi \(\mathbf{h}_1 \to \mathbf{h}_2 \to \cdots \to \mathbf{h}_6\) mới tác động được tới dự đoán cuối cùng. Mỗi bước đều nhân với \(\mathbf{W}_{hh}\) rồi đi qua \(\tanh\). Nếu \(\mathbf{W}_{hh}\) liên tục làm suy giảm tín hiệu (trị riêng nhỏ hơn 1), thông tin yếu dần theo hàm mũ — gây gradient biến mất. Ngược lại, nếu \(\mathbf{W}_{hh}\) khuếch đại tín hiệu (trị riêng lớn hơn 1), tín hiệu tăng mạnh mất kiểm soát — gây gradient bùng nổ. Giữ cho luồng thông tin ổn định qua nhiều bước chính là bài toán khó nhất của RNN cơ bản.&lt;/p&gt;

&lt;p&gt;Trong quá trình lan truyền ngược, khi tính \(\frac{\partial \mathcal{L}}{\partial \mathbf{W}_{hh}}\), ta phải tính đến việc \(\mathbf{W}_{hh}\) xuất hiện ở mọi bước thời gian. Gradient chứa các tích như:&lt;/p&gt;

\[\frac{\partial \mathbf{h}_6}{\partial \mathbf{h}_1} = \frac{\partial \mathbf{h}_6}{\partial \mathbf{h}_5} \frac{\partial \mathbf{h}_5}{\partial \mathbf{h}_4} \cdots \frac{\partial \mathbf{h}_2}{\partial \mathbf{h}_1}\]

&lt;p&gt;Mỗi ma trận Jacobian \(\frac{\partial \mathbf{h}_{t+1}}{\partial \mathbf{h}_t} = \text{diag}(\tanh&apos;(\mathbf{z}_{t+1})) \mathbf{W}_{hh}\) phụ thuộc đồng thời vào \(\mathbf{W}_{hh}\) và đạo hàm của \(\tanh\).&lt;/p&gt;

&lt;p&gt;Vì đạo hàm của \(\tanh\) bị chặn bởi 1 và tiến gần về 0 khi giá trị kích hoạt bão hòa, chuẩn của mỗi ma trận Jacobian thường nhỏ hơn \(\|\mathbf{W}_{hh}\|\). Do đó, tích các Jacobian co lại theo hàm mũ trừ khi \(\|\mathbf{W}_{hh}\|\) được cân chỉnh rất sát. Trong thực tế, RNN cơ bản hiếm khi duy trì được sự cân bằng này, nên thường chỉ học hiệu quả các phụ thuộc trong khoảng 10–20 bước thời gian.&lt;/p&gt;

&lt;p&gt;Các cấu hình kiến trúc RNN khác nhau cũng phản ánh cách tận dụng trạng thái ẩn phù hợp từng bài toán. Kiến trúc nhiều-một (chuỗi → một đầu ra) tính \(\mathbf{h}_t\) cho mọi \(t\) nhưng chỉ dùng \(\mathbf{h}_T\) để dự đoán, thích hợp cho bài toán phân loại. Kiến trúc nhiều-nhiều cùng độ dài (chuỗi → chuỗi cùng độ dài) sinh \(\mathbf{y}_t = g(\mathbf{W}_{hy}\mathbf{h}_t + \mathbf{b}_y)\) tại mỗi bước, phù hợp với gán nhãn từng khung hình video hoặc từng từ. Kiến trúc nhiều-nhiều khác độ dài (chuỗi-sang-chuỗi) dùng mô hình encoder-decoder: RNN encoder xử lý chuỗi đầu vào để lấy trạng thái ẩn cuối \(\mathbf{h}_T^{enc}\) rồi dùng nó khởi tạo trạng thái ban đầu cho RNN decoder (\(\mathbf{h}_0^{dec} = \mathbf{h}_T^{enc}\)). Sau đó decoder sinh đầu ra theo kiểu tự hồi quy, đưa đầu ra của bước trước làm đầu vào cho bước tiếp theo cho đến khi gặp token kết thúc chuỗi.&lt;/p&gt;

&lt;p&gt;Về độ phức tạp tính toán, RNN có chi phí tuyến tính theo độ dài chuỗi: \(O(T \cdot d_h^2)\), trong đó \(T\) là độ dài chuỗi và \(d_h\) là số chiều trạng thái ẩn (chủ yếu do phép nhân \(\mathbf{W}_{hh}\mathbf{h}_{t-1}\) ở mỗi bước). Tuy độ phức tạp lý thuyết thấp, sự phụ thuộc tuần tự khiến ta không thể song song hóa qua các bước thời gian: một chuỗi dài 100 bước bắt buộc phải thực hiện tuần tự 100 phép nhân ma trận ngay cả trên GPU mạnh. Ngược lại, Transformer có độ phức tạp bậc hai \(O(T^2 d)\) nhưng xử lý song song tất cả các vị trí cùng lúc, nhờ đó nhanh hơn đáng kể trên phần cứng hiện đại khi \(T\) không quá lớn.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Minh họa trực quan phương trình cập nhật trạng thái ẩn h_t = f(h_{t-1}, x_t) trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 10&lt;/td&gt;
          &lt;td&gt;Recurrent Neural Networks](https://www.youtube.com/watch?v=6niqTuYFZLQ) — Stanford University School of Engineering (tiếng Anh). Khai triển phương trình hồi quy theo thời gian và phân tích đường đi của gradient.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=t0EoeTYU-fc&quot;&gt;Mô hình ngôn ngữ và mạng nơ ron hồi quy (Language Model and Recurrent Neural Network)&lt;/a&gt; — ProtonX (tiếng Việt). Bài giảng tiếng Việt xây dựng mô hình ngôn ngữ dựa trên cùng phép tính hồi quy này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05 Giới thiệu về Mạng Neuron Hồi quy</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter05/05_00_Introduction</id>
   <content type="html">&lt;p&gt;Đọc hai câu &lt;em&gt;“Chó cắn người”&lt;/em&gt; và &lt;em&gt;“Người cắn chó”&lt;/em&gt;: tập từ vựng giống hệt nhau 100%, nhưng chỉ đảo vị trí hai danh từ là toàn bộ ý nghĩa đảo ngược hoàn toàn. Một mạng truyền thẳng (MLP) hay CNN thông thường xử lý từng đầu vào độc lập với kích thước cố định, không hề có khái niệm “trước–sau” hay “trí nhớ” về những gì vừa đi qua. &lt;strong&gt;Mạng Neuron Hồi quy (RNN)&lt;/strong&gt; ra đời chính để trao cho mạng thần kinh một &lt;strong&gt;trạng thái ẩn&lt;/strong&gt; — chiếc sổ tay ghi nhớ bối cảnh theo từng bước thời gian.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trục-tư-duy-của-mạng-neuron-hồi-quy&quot;&gt;Kiến thức cần nhớ: Bốn trục tư duy của Mạng Neuron Hồi quy&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Dữ liệu tuần tự và biến thiên độ dài&lt;/strong&gt;:
Ngôn ngữ, giọng nói, nhịp tim ECG hay giá cổ phiếu đều là chuỗi \((x_1, x_2, \dots, x_T)\) có độ dài \(T\) thay đổi và mang phụ thuộc thứ tự chặt chẽ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trạng thái ẩn \(h_t\) như bộ nhớ nén có chia sẻ trọng số&lt;/strong&gt;:
Tại mỗi bước \(t\), RNN cập nhật \(h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h)\) bằng &lt;strong&gt;cùng một bộ trọng số&lt;/strong&gt; \((W_{hh}, W_{xh})\) ở mọi thời điểm — tương tự cách CNN chia sẻ bộ lọc trong không gian, RNN chia sẻ trọng số dọc theo thời gian.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bốn mô hình ánh xạ chuỗi (Sequence Topologies)&lt;/strong&gt;:
Một-nhiều (sinh chú thích ảnh), nhiều-một (phân tích cảm xúc), nhiều-nhiều đồng bộ (gán nhãn từ loại POS), và nhiều-nhiều trễ kiểu encoder–decoder (dịch máy).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ba thách thức kinh điển định hình cả lĩnh vực&lt;/strong&gt;:
Gradient biến mất/bùng nổ qua chuỗi dài, không thể song song hóa theo trục thời gian, và nút thắt nén toàn bộ lịch sử vào một vector \(h_t\) cố định — trực tiếp dẫn tới LSTM, Attention và Transformer.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-2-bước-thời-gian-của-một-rnn-siêu-nhỏ&quot;&gt;Giải thích: Tính tay 2 bước thời gian của một RNN siêu nhỏ&lt;/h3&gt;

&lt;p&gt;Xét một RNN 1 chiều (\(h_t \in \mathbb{R}, x_t \in \mathbb{R}\)) với trọng số \(W_{hh} = 0{,}5, \; W_{xh} = 1{,}0, \; b_h = 0\), trạng thái ban đầu \(h_0 = 0\), và chuỗi đầu vào \(x = [1{,}0, \; -0{,}5]\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Bước \(t\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Đầu vào \(x_t\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Trạng thái trước \(h_{t-1}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Tổ hợp tuyến tính \(z_t = 0{,}5 h_{t-1} + 1{,}0 x_t\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Trạng thái mới \(h_t = \tanh(z_t)\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(t=1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1{,}0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0{,}5(0) + 1{,}0(1{,}0) = 1{,}0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\tanh(1{,}0) \approx \mathbf{0{,}7616}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(t=2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(-0{,}5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0{,}7616\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(0{,}5(0{,}7616) + 1{,}0(-0{,}5) = -0{,}1192\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\tanh(-0{,}1192) \approx \mathbf{-0{,}1186}\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Hãy nhìn ở \(t=2\): dù đầu vào mới là \(-0{,}5\), trạng thái \(h_2 \approx -0{,}1186\) vẫn mang “dư âm” dương của \(x_1 = 1{,}0\) truyền qua \(0{,}5 h_1 = +0{,}3808\). Nếu không có vòng hồi tiếp \(W_{hh} h_{t-1}\), kết quả ở bước 2 đã tụt xuống \(\tanh(-0{,}5) \approx -0{,}4621\).&lt;/p&gt;

&lt;h1 id=&quot;giới-thiệu-về-mạng-neuron-hồi-quy&quot;&gt;Giới thiệu về Mạng Neuron Hồi quy&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter05/rnn_unrolled_architecture.png&quot; alt=&quot;RNN Unrolled Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc RNN ở dạng gập (trái) và dạng trải theo thời gian (phải). Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Mạng Neuron Hồi quy (Recurrent Neural Networks — RNNs) đánh dấu một bước chuyển cơ bản trong thiết kế mạng neuron nhờ bổ sung yếu tố &lt;strong&gt;bộ nhớ&lt;/strong&gt;. Trong khi mạng truyền thẳng (feedforward) và CNN xử lý từng đầu vào một cách độc lập, coi mỗi điểm dữ liệu là một mẫu tách biệt, thì RNN duy trì một trạng thái nội bộ thay đổi dần khi đi qua dữ liệu tuần tự. Việc cho phép thông tin được lưu giữ theo thời gian mở ra khả năng xử lý nhiều bài toán mới như ngôn ngữ tự nhiên, giọng nói, âm nhạc, video, dự báo chuỗi thời gian và mọi tác vụ mà &lt;strong&gt;thứ tự dữ liệu mang ý nghĩa&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Một ưu điểm quan trọng khác của RNN là khả năng làm việc với các đầu vào có &lt;strong&gt;độ dài thay đổi&lt;/strong&gt;. Một câu có thể gồm 3 từ hoặc 30 từ; một video có thể có 10 khung hình hoặc 10.000 khung hình; một đoạn âm thanh có thể kéo dài 1 giây hoặc 1 giờ. Các mạng neuron truyền thống đòi hỏi đầu vào có kích thước cố định, buộc ta phải cắt bớt hoặc đệm thêm để đồng nhất độ dài, dễ gây mất mát thông tin. RNN khắc phục hạn chế này bằng cách xử lý từng phần tử theo trình tự thời gian, áp dụng cùng một phép biến đổi ở mỗi bước và dùng trạng thái ẩn để truyền thông tin về phía trước. Về mặt lý thuyết, thiết kế này cho phép RNN xử lý các chuỗi có độ dài tùy ý với số lượng tham số cố định.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;tại-sao-dữ-liệu-tuần-tự-cần-một-kiến-trúc-khác&quot;&gt;Tại sao dữ liệu tuần tự cần một kiến trúc khác&lt;/h2&gt;

&lt;p&gt;Hãy xét các ví dụ sau, nơi thứ tự các từ quyết định trực tiếp ý nghĩa của câu:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Ví dụ&lt;/th&gt;
      &lt;th&gt;Khi thay đổi thứ tự / cấu trúc&lt;/th&gt;
      &lt;th&gt;Sự thay đổi ý nghĩa&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;“Con &lt;strong&gt;chó&lt;/strong&gt; cắn người đàn ông”&lt;/td&gt;
      &lt;td&gt;“Người đàn ông cắn con &lt;strong&gt;chó&lt;/strong&gt;”&lt;/td&gt;
      &lt;td&gt;Chủ ngữ và tân ngữ đảo ngược nhau&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;“Món ăn &lt;strong&gt;không&lt;/strong&gt; tệ”&lt;/td&gt;
      &lt;td&gt;“Món ăn tệ”&lt;/td&gt;
      &lt;td&gt;Sắc thái cảm xúc đảo ngược hoàn toàn&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;“Cô ấy chỉ có mắt dành cho anh ấy”&lt;/td&gt;
      &lt;td&gt;“Cô ấy chỉ có mắt nhìn anh ấy”&lt;/td&gt;
      &lt;td&gt;Ý nghĩa chuyển từ thành ngữ sang nghĩa khác&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Tính chất phụ thuộc vào thứ tự không chỉ xuất hiện trong ngôn ngữ mà có mặt ở hầu hết các lĩnh vực dữ liệu tuần tự:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Giá cổ phiếu&lt;/strong&gt;: Giá đóng cửa hôm qua là mốc tham chiếu cho hôm nay, còn xu hướng tuần trước ảnh hưởng đến dự báo tuần này. Cuộc khủng hoảng tài chính năm 2008 không xảy ra trong một ngày mà hình thành từ các diễn biến kéo dài nhiều tháng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhận dạng giọng nói&lt;/strong&gt;: Việc phân biệt các cụm âm tương tự nhau (như “nhận ra lời nói” và “tắm biển đẹp” — vốn bắt nguồn từ cặp cụm từ đồng âm trong tiếng Anh) đòi hỏi ngữ cảnh kéo dài qua nhiều âm vị (phoneme), không thể chỉ dựa vào từng âm đơn lẻ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiểu video&lt;/strong&gt;: Quỹ đạo của một quả bóng chỉ có thể xác định dựa trên chuỗi khung hình liên tiếp. Nếu thiếu ngữ cảnh thời gian, ta không thể phân biệt quả bóng đang được ném đi hay đang được bắt lại.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gập protein&lt;/strong&gt;: Cấu trúc không gian ba chiều của protein phụ thuộc vào quá trình gập theo trình tự, không chỉ riêng tập hợp các amino acid.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sáng tác âm nhạc&lt;/strong&gt;: Hiệu ứng cảm xúc của một hợp âm phụ thuộc vào chuỗi hợp âm đi trước đó; cùng một hợp âm có thể nghe thuận tai hoặc nghịch tai tùy ngữ cảnh.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Thách thức cốt lõi&lt;/strong&gt;: Các mạng feedforward xử lý từng đầu vào độc lập nên không có cơ chế ghi nhận từ thứ 5 đứng sau từ thứ 4. Với chúng, “Con chó cắn người đàn ông” và “Người đàn ông cắn con chó” chỉ là cùng một tập hợp từ. CNN nhận diện tốt các mẫu không gian nhưng không có bộ nhớ theo thời gian. RNN giải quyết vấn đề này bằng cách &lt;strong&gt;truyền thông tin từ bước thời gian này sang bước tiếp theo&lt;/strong&gt; thông qua trạng thái ẩn đóng vai trò bộ nhớ.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ý-tưởng-cốt-lõi-trạng-thái-ẩn-như-bộ-nhớ&quot;&gt;Ý tưởng cốt lõi: Trạng thái ẩn như bộ nhớ&lt;/h2&gt;

&lt;p&gt;Ở mỗi bước thời gian \(t\), RNN thực hiện một quy trình đơn giản:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nhận&lt;/strong&gt; đầu vào mới \(\mathbf{x}_t\) (chẳng hạn từ tiếp theo, khung hình hoặc điểm dữ liệu mới).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kết hợp&lt;/strong&gt; đầu vào đó với trạng thái ẩn trước đó \(\mathbf{h}_{t-1}\) — phần bộ nhớ tóm lược những gì mạng đã xử lý.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính toán&lt;/strong&gt; trạng thái ẩn mới \(\mathbf{h}_t\) — trạng thái bộ nhớ đã cập nhật thêm thông tin mới.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tạo đầu ra&lt;/strong&gt; \(\mathbf{y}_t\) (tùy chọn) — dự đoán dựa trên trạng thái hiện tại.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Công thức toán học cốt lõi của RNN rất gọn:&lt;/p&gt;

\[\mathbf{h}_t = \tanh(\mathbf{W}_{hh}\mathbf{h}_{t-1} + \mathbf{W}_{xh}\mathbf{x}_t + \mathbf{b}_h)\]

&lt;p&gt;trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{x}_t \in \mathbb{R}^{d_x}\) là vectơ đầu vào tại bước thời gian \(t\)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{h}_{t-1} \in \mathbb{R}^{d_h}\) là trạng thái ẩn ở bước trước (bộ nhớ)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}_{xh} \in \mathbb{R}^{d_h \times d_x}\) là ma trận trọng số chiếu đầu vào sang không gian ẩn&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}_{hh} \in \mathbb{R}^{d_h \times d_h}\) là ma trận trọng số hồi quy (ẩn-sang-ẩn)&lt;/li&gt;
  &lt;li&gt;\(\tanh\) đưa giá trị kích hoạt về khoảng \([-1, 1]\), tạo tính phi tuyến và hạn chế giá trị tăng quá lớn&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter05/rnn_unrolled.png&quot; alt=&quot;RNN Unrolled&quot; /&gt;
&lt;em&gt;Hình ảnh: RNN được trải qua các bước thời gian, minh họa trạng thái ẩn truyền từ bước này sang bước tiếp theo.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;ba-đặc-điểm-cốt-lõi&quot;&gt;Ba đặc điểm cốt lõi&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Chia sẻ tham số qua thời gian&lt;/strong&gt;: Cùng các ma trận trọng số \(\mathbf{W}_{xh}\) và \(\mathbf{W}_{hh}\) được dùng ở mọi bước thời gian, tương tự cách CNN chia sẻ trọng số qua các vị trí không gian. Khi mạng học được mẫu “động từ theo sau chủ ngữ”, nó chỉ cần học một lần thay vì học riêng cho từng vị trí trong câu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Trạng thái ẩn là biểu diễn ngữ cảnh nén&lt;/strong&gt;: Trạng thái ẩn \(\mathbf{h}_t\) là một vectơ có kích thước cố định (chẳng hạn 256 hoặc 512 chiều) phải mã hóa toàn bộ thông tin của chuỗi tính đến thời điểm \(t\). Quá trình nén này có mất mát, buộc mạng phải học cách giữ lại thông tin quan trọng và bỏ qua chi tiết ít liên quan.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Cấu trúc đệ quy&lt;/strong&gt;: Vì \(\mathbf{h}_t\) phụ thuộc vào \(\mathbf{h}_{t-1}\), \(\mathbf{h}_{t-1}\) lại phụ thuộc vào \(\mathbf{h}_{t-2}\) và cứ tiếp diễn như vậy, trạng thái ẩn tại bước \(t\) về mặt lý thuyết chứa thông tin từ toàn bộ các đầu vào trước đó. Tuy nhiên trong thực tế, hiện tượng suy giảm gradient làm giới hạn phạm vi ghi nhớ hiệu quả này.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bối-cảnh-lịch-sử-vì-sao-rnn-vẫn-quan-trọng&quot;&gt;Bối cảnh lịch sử: Vì sao RNN vẫn quan trọng&lt;/h2&gt;

&lt;p&gt;Nghiên cứu RNN không chỉ để tìm hiểu một kỹ thuật cũ mà còn để nắm rõ mạch phát triển của các mô hình chuỗi:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;1990&lt;/strong&gt;: Elman giới thiệu Simple Recurrent Network (SRN), chứng minh kết nối hồi quy có thể học các mẫu theo thời gian.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;1997&lt;/strong&gt;: Hochreiter &amp;amp; Schmidhuber đề xuất LSTM, khắc phục vấn đề gradient biến mất bằng cơ chế cổng (&lt;em&gt;gate&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2014&lt;/strong&gt;: Cho và cộng sự giới thiệu GRU, đơn giản hóa cấu trúc LSTM nhưng vẫn duy trì hiệu năng tương đương.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2015&lt;/strong&gt;: Bahdanau và cộng sự giới thiệu cơ chế attention, cho phép truy cập trực tiếp tới mọi trạng thái quá khứ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2017&lt;/strong&gt;: Vaswani và cộng sự đề xuất kiến trúc Transformer, loại bỏ hoàn toàn phép hồi quy để tính toán song song bằng attention.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mỗi cải tiến ra đời nhằm giải quyết trực tiếp hạn chế của bước trước đó đồng thời kế thừa các nguyên lý nền tảng. Hiểu rõ RNN giúp ta nhận diện lý do xuất hiện của các kiến trúc kế tiếp và biết khi nào nên chọn mô hình nào.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;lộ-trình-phát-triển-tiếp-theo&quot;&gt;Lộ trình phát triển tiếp theo&lt;/h2&gt;

&lt;p&gt;RNN đặt nền móng cho mô hình hóa chuỗi nhưng tồn tại ba hạn chế cốt lõi:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Hạn chế&lt;/th&gt;
      &lt;th&gt;Tác động&lt;/th&gt;
      &lt;th&gt;Giải pháp hiện đại&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Xử lý tuần tự&lt;/td&gt;
      &lt;td&gt;Không thể song song hóa qua các bước thời gian&lt;/td&gt;
      &lt;td&gt;Transformer (attention)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Gradient biến mất&lt;/td&gt;
      &lt;td&gt;Khó học các phụ thuộc tầm xa&lt;/td&gt;
      &lt;td&gt;LSTM/GRU (cơ chế cổng)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Nghẽn thông tin&lt;/td&gt;
      &lt;td&gt;Bộ nhớ kích thước cố định dễ làm mất chi tiết cũ&lt;/td&gt;
      &lt;td&gt;Attention (truy cập trực tiếp)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chính những hạn chế này đã thúc đẩy sự ra đời của các kiến trúc trong các chương sau:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;LSTM và GRU&lt;/strong&gt; (Chương 6): Dùng cơ chế cổng để tạo kết nối bỏ qua (&lt;em&gt;skip connection&lt;/em&gt;) theo chiều thời gian.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế attention&lt;/strong&gt; (Chương 7): Cho phép liên kết trực tiếp tới mọi trạng thái trước đó mà không phải nén toàn bộ qua một vectơ duy nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Transformer&lt;/strong&gt; (Chương 8): Loại bỏ hồi quy để khai thác tối đa khả năng tính toán song song.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hiểu thấu đáo cả ưu điểm lẫn hạn chế của RNN là cơ sở để nắm bắt cách các kiến trúc mô hình chuỗi hiện đại hình thành và tiến hóa.&lt;/p&gt;

&lt;h2 id=&quot;các-loại-kiến-trúc-rnn&quot;&gt;Các loại kiến trúc RNN&lt;/h2&gt;

&lt;p&gt;Tùy theo bài toán, RNN có thể được cấu hình theo nhiều dạng vào–ra khác nhau:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Kiến trúc&lt;/th&gt;
      &lt;th&gt;Đầu vào&lt;/th&gt;
      &lt;th&gt;Đầu ra&lt;/th&gt;
      &lt;th&gt;Ví dụ tác vụ&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Nhiều-Một&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Chuỗi&lt;/td&gt;
      &lt;td&gt;Một giá trị&lt;/td&gt;
      &lt;td&gt;Phân loại cảm xúc, phát hiện ý định&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Một-Nhiều&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Một giá trị&lt;/td&gt;
      &lt;td&gt;Chuỗi&lt;/td&gt;
      &lt;td&gt;Tạo nhạc, sinh chú thích ảnh&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Nhiều-Nhiều (Cùng độ dài)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Chuỗi&lt;/td&gt;
      &lt;td&gt;Chuỗi (cùng độ dài)&lt;/td&gt;
      &lt;td&gt;Gán nhãn từ loại (POS), phân loại khung hình&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Nhiều-Nhiều (Khác độ dài)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Chuỗi&lt;/td&gt;
      &lt;td&gt;Chuỗi (độ dài khác)&lt;/td&gt;
      &lt;td&gt;Dịch máy, tóm tắt văn bản&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter05/rnn_types_architecture.png&quot; alt=&quot;RNN Types&quot; /&gt;
&lt;em&gt;Hình ảnh: Các kiểu kiến trúc RNN — Nhiều-Một, Một-Nhiều, Nhiều-Nhiều. Đỏ: Đầu vào (Input), Xanh lục: Trạng thái ẩn (Hidden), Xanh lam: Đầu ra (Output). Nguồn: CS231n&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ba-thách-thức-cơ-bản&quot;&gt;Ba thách thức cơ bản&lt;/h2&gt;

&lt;p&gt;Dù có cấu trúc gọn gàng, RNN cơ bản (vanilla RNN) gặp phải ba thách thức lớn:&lt;/p&gt;

&lt;h3 id=&quot;1-xử-lý-tuần-tự-khó-song-song-hóa&quot;&gt;1. Xử lý tuần tự (khó song song hóa)&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter05/rnn_blackbox.png&quot; alt=&quot;RNN Black Box&quot; /&gt;
&lt;em&gt;Hình ảnh: RNN dưới góc nhìn hộp đen với vòng phản hồi — trạng thái ẩn được đưa ngược lại làm đầu vào cho bước tiếp theo.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Khác với mạng feedforward xử lý độc lập từng mẫu, RNN bắt buộc phải tính \(\mathbf{h}_t\) trước khi tính \(\mathbf{h}_{t+1}\). Sự phụ thuộc tuần tự này dẫn đến:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Khó tận dụng khả năng tính toán song song của GPU.&lt;/li&gt;
  &lt;li&gt;Thời gian xử lý tăng tuyến tính theo độ dài chuỗi.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giải pháp hiện đại&lt;/strong&gt;: Transformer sử dụng attention để xử lý đồng thời mọi vị trí trong chuỗi.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-gradient-biến-mất-khó-học-phụ-thuộc-tầm-xa&quot;&gt;2. Gradient biến mất (khó học phụ thuộc tầm xa)&lt;/h3&gt;
&lt;p&gt;Khi lan truyền ngược qua thời gian, gradient được nhân dồn qua nhiều bước. Nếu mỗi bước làm giảm độ lớn gradient đi một hệ số nhỏ hơn 1, gradient sẽ suy giảm theo hàm mũ:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{h}_1} = \frac{\partial \mathcal{L}}{\partial \mathbf{h}_T} \cdot \prod_{t=2}^{T} \frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-1}}\]

&lt;p&gt;Chẳng hạn, với chuỗi 50 bước có trị riêng Jacobian bằng 0.99, gradient bị nhân với \(0.99^{49} \approx 0.61\) (đã giảm gần 40% giá trị); khi trị riêng nhỏ hơn nữa hoặc chuỗi kéo dài hàng trăm bước, tích này nhanh chóng suy giảm gần về 0.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Giải pháp hiện đại&lt;/strong&gt;: LSTM và GRU sử dụng cơ chế cổng để tạo đường truyền trực tiếp giúp gradient lan truyền ổn định hơn.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-nghẽn-thông-tin-bộ-nhớ-kích-thước-cố-định&quot;&gt;3. Nghẽn thông tin (bộ nhớ kích thước cố định)&lt;/h3&gt;
&lt;p&gt;Trạng thái ẩn \(\mathbf{h}_t\) phải chứa toàn bộ lịch sử chuỗi trong một vectơ có số chiều cố định. Khi chuỗi dài dần:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Thông tin buộc phải bị nén liên tục.&lt;/li&gt;
  &lt;li&gt;Các chi tiết ở phần đầu chuỗi dễ bị ghi đè hoặc thất thoát.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giải pháp hiện đại&lt;/strong&gt;: Cơ chế attention cho phép truy cập trực tiếp bất kỳ vị trí quá khứ nào mà không cần nén toàn bộ lịch sử vào một vectơ duy nhất.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chính ba giới hạn này đã định hướng quá trình phát triển của các mô hình chuỗi từ RNN đến LSTM, Attention và Transformer.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-tiên-quyết&quot;&gt;Kiến thức tiên quyết&lt;/h2&gt;

&lt;p&gt;Trước khi học chương này, bạn nên nắm vững:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mạng feedforward&lt;/strong&gt; và thuật toán lan truyền ngược (Chương 2–3).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phép nhân ma trận&lt;/strong&gt; — thao tác nền tảng trong mọi mạng neuron.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy tắc dây chuyền&lt;/strong&gt; — cơ sở để tính gradient qua nhiều lớp lồng nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ảnh hưởng của độ lớn gradient&lt;/strong&gt; — lý do gradient quá lớn hoặc quá nhỏ gây mất ổn định khi huấn luyện.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;nội-dung-chính-của-chương&quot;&gt;Nội dung chính của chương&lt;/h2&gt;

&lt;p&gt;Chương này trình bày hệ thống kiến thức về RNN từ lý thuyết đến cài đặt:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nền tảng toán học&lt;/strong&gt; — Các phương trình mô tả phép tính hồi quy khi trải theo thời gian cùng kích thước cụ thể của từng ma trận.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền ngược theo thời gian (BPTT)&lt;/strong&gt; — Cách gradient truyền ngược qua đồ thị tính toán và nguyên nhân gây ra hiện tượng gradient biến mất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ví dụ trực quan&lt;/strong&gt; — Theo dõi từng bước xử lý trên chuỗi cụ thể để thấy cách thông tin di chuyển qua trạng thái ẩn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt thực hành&lt;/strong&gt; — Xây dựng RNN từ đầu bằng NumPy để quan sát rõ từng phép toán, sau đó chuyển sang cài đặt chuẩn bằng PyTorch.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình ngôn ngữ cấp ký tự&lt;/strong&gt; — Ví dụ hoàn chỉnh minh họa RNN học cách sinh văn bản từng ký tự.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hạn chế và hướng khắc phục&lt;/strong&gt; — Phân tích những điểm yếu của RNN cơ bản để chuẩn bị nền tảng cho LSTM, GRU và Transformer.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Hãy bắt đầu từ phần lý thuyết toán học và cách cài đặt của RNN cơ bản.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau khi nắm vững RNN gốc, bạn có thể đọc thêm &lt;strong&gt;05-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về Mamba, RWKV và các trường hợp hồi quy tuyến tính cạnh tranh với Transformer. Phần đối chiếu trên hub LLM (trạng thái RNN so với KV-cache tăng dần, kèm một mục về SSM) nằm ở bài &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer (tiếng Anh). Giải thích trực quan vai trò trạng thái ẩn như bộ nhớ của RNN.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dqoEU9Ac3ek&quot;&gt;MIT 6.S191 (2024): Recurrent Neural Networks, Transformers, and Attention&lt;/a&gt; — Alexander Amini (tiếng Anh). Bài giảng MIT 2024 đặt cơ chế bộ nhớ của RNN cạnh attention theo đúng lộ trình học.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 10&lt;/td&gt;
          &lt;td&gt;Recurrent Neural Networks](https://www.youtube.com/watch?v=6niqTuYFZLQ) — Stanford University School of Engineering (tiếng Anh). Trình bày chi tiết về RNN cùng ba hạn chế cốt lõi đã nêu trong phần giới thiệu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Khi Vision Transformer (ViT) xuất hiện năm 2020, từng có dự đoán rằng mạng tích chập (CNN) sẽ sớm trở thành “đồ cổ” trong thị giác máy tính. Thế nhưng thực tế giai đoạn 2022–2026 lại kể một câu chuyện thú vị hơn nhiều: khi được cập nhật đúng quy trình huấn luyện hiện đại và thiết kế khối tối ưu như &lt;strong&gt;ConvNeXt&lt;/strong&gt;, CNN không những bắt kịp ViT về độ chính xác mà còn tiếp tục thống trị thị giác thời gian thực, ảnh y khoa và thiết bị biên (edge AI).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-xu-hướng-hiện-đại-của-cnn-20222026&quot;&gt;Kiến thức cần nhớ: Bốn xu hướng hiện đại của CNN (2022–2026)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;ConvNeXt — Hiện đại hóa ResNet bằng công thức của Transformer&lt;/strong&gt;:
Áp dụng nhân depthwise lớn \(7 \times 7\), khối cổ chai đảo ngược (inverted bottleneck), LayerNorm thay cho BatchNorm, GELU thay cho ReLU và công thức huấn luyện AdamW + Mixup + Stochastic Depth.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc lai (Hybrid CNN–Transformer)&lt;/strong&gt;:
Kết hợp tầng tích chập ở các giai đoạn đầu (khai thác thiên kiến cục bộ và hạ độ phân giải nhanh) với tầng Self-Attention ở giai đoạn sâu (mô hình hóa ngữ cảnh toàn cục), như trong CoAtNet hay FasterViT.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vai trò cốt lõi trong Mô hình Nền tảng và Phát hiện Vật thể&lt;/strong&gt;:
Dù SAM hay DINOv2 dùng encoder ViT, các bộ phát hiện thời gian thực (họ YOLO v8–v11) và decoder phân đoạn ảnh y khoa (U-Net hiện đại) vẫn đặt nền móng trên tích chập.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh đổi Độ phức tạp: \(O(N)\) của CNN vs. \(O(N^2)\) của Attention&lt;/strong&gt;:
Với ảnh độ phân giải cực cao (ảnh vệ tinh, ảnh giải phẫu bệnh học), chi phí bậc hai theo số patch của Self-Attention tăng vọt, khiến CNN tuyến tính theo số pixel vẫn giữ ưu thế áp đảo về độ trễ và năng lượng.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-sự-chênh-lệch-chi-phí-giữa-depthwise-conv-7-times-7-và-self-attention-trên-ảnh-độ-phân-giải-cao&quot;&gt;Giải thích: Tính tay sự chênh lệch chi phí giữa Depthwise Conv \(7 \times 7\) và Self-Attention trên ảnh độ phân giải cao&lt;/h3&gt;

&lt;p&gt;Xét một bản đồ đặc trưng kích thước \(56 \times 56\) (tổng cộng \(N = 56 \times 56 = 3{,}136\) vị trí không gian) với số kênh \(C = 96\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Self-Attention toàn cục&lt;/strong&gt; (chi phí tương tác giữa mọi cặp vị trí \(N \times N \times C\)):
Số phép nhân-cộng riêng cho tích ma trận \(Q K^T\) và \(A V\) là:
\(2 \times N^2 \times C = 2 \times (3{,}136)^2 \times 96 \approx \mathbf{1{,}888 \text{ triệu MACs}}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Depthwise Convolution \(7 \times 7\) trong ConvNeXt&lt;/strong&gt; (mỗi vị trí chỉ nhân với \(7 \times 7 = 49\) láng giềng trên từng kênh):
\(N \times k^2 \times C = 3{,}136 \times 49 \times 96 \approx \mathbf{14{,}75 \text{ triệu MACs}}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Ở độ phân giải \(56 \times 56\), phép lọc không gian của ConvNeXt rẻ hơn Self-Attention toàn cục tới &lt;strong&gt;128 lần&lt;/strong&gt; — đó là lý do cốt lõi khiến CNN hiện đại vẫn là lựa chọn hàng đầu cho suy luận độ trễ thấp trên điện thoại, camera và NPU biên.&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-convnet-sau-convnext-và-mô-hình-nền-tảng-thị-giác&quot;&gt;Tùy chọn: ConvNet sau ConvNeXt và Mô hình Nền tảng Thị giác&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; trình bày lại toán tích chập, tầng gộp hay lịch sử LeNet–ResNet. Nội dung tập trung cập nhật những kiến trúc và cách triển khai phổ biến trong thị giác máy tính từ sau năm 2022.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Phép tính cốt lõi của tích chập \((\mathbf{x} * \mathbf{k})_{i} = \sum_{u} x_{i+u}\,k_{u}\) không thay đổi. Điều thay đổi nằm ở &lt;strong&gt;thiết kế kiến trúc tổng thể&lt;/strong&gt; (như ConvNeXt) và &lt;strong&gt;cách sử dụng&lt;/strong&gt; (dùng các mạng xương sống tích chập hoặc lai, thường được đóng băng trọng số, trong các mô hình nền tảng thị giác).&lt;/p&gt;

&lt;h2 id=&quot;1-convnext-hiện-đại-hóa-convnet-bằng-quy-trình-huấn-luyện-transformer&quot;&gt;1. ConvNeXt: Hiện đại hóa ConvNet bằng Quy trình Huấn luyện Transformer&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2201.03545&quot;&gt;Liu et al., 2022&lt;/a&gt; (&lt;em&gt;“A ConvNet for the 2020s”&lt;/em&gt;) cho thấy một kiến trúc thuần tích chập xuất phát từ ResNet, khi được hiện đại hóa thiết kế khối và huấn luyện bằng quy trình của ViT (AdamW, Mixup, stochastic depth, kích thước nhân lớn hơn), có thể đạt hiệu năng ngang bằng các Transformer phân cấp trên ImageNet. Tiếp đó, &lt;a href=&quot;https://arxiv.org/abs/2301.00808&quot;&gt;ConvNeXt V2&lt;/a&gt; (2023) bổ sung lớp chuẩn hóa phản hồi toàn cục (&lt;em&gt;Global Response Normalization&lt;/em&gt; — GRN) cùng giai đoạn tiền huấn luyện autoencoder che khuất (&lt;em&gt;masked autoencoder&lt;/em&gt;) thuần tích chập.&lt;/p&gt;

&lt;p&gt;Thông điệp chính cho chương này: &lt;strong&gt;tích chập tách theo chiều sâu (&lt;em&gt;depthwise convolution&lt;/em&gt;) kết hợp cổ chai đảo ngược (&lt;em&gt;inverted bottleneck&lt;/em&gt;)&lt;/strong&gt; vẫn là một thiên kiến quy nạp hiệu quả; khoảng cách từng thấy giữa CNN và ViT đầu thập niên 2020 chủ yếu đến từ công thức huấn luyện và quy mô dữ liệu, chứ không có nghĩa tích chập đã lỗi thời.&lt;/p&gt;

&lt;h2 id=&quot;2-ứng-dụng-thực-tế&quot;&gt;2. Ứng dụng Thực tế&lt;/h2&gt;

&lt;h3 id=&quot;mô-hình-nền-tảng-thị-giác-vẫn-giữ-thành-phần-tích-chập&quot;&gt;Mô hình nền tảng thị giác vẫn giữ thành phần tích chập&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;DINOv2&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2304.07193&quot;&gt;Oquab et al., 2023&lt;/a&gt;) — học đặc trưng tự giám sát với ViT làm xương sống cho truy xuất ảnh, ước lượng độ sâu và phân đoạn; các biến thể ConvNeXt cũng thường được so sánh trực tiếp trên cùng bộ chuẩn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SAM&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2304.02643&quot;&gt;Kirillov et al., 2023&lt;/a&gt;) và &lt;strong&gt;SAM 2&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2408.00714&quot;&gt;Ravi et al., 2024&lt;/a&gt;) — mô hình phân đoạn theo gợi ý (&lt;em&gt;prompt&lt;/em&gt;) dùng encoder ảnh kiểu ViT, nhưng các hệ thống triển khai thực tế vẫn thường ghép kèm bộ phát hiện đối tượng tích chập và phần cổ (&lt;em&gt;neck&lt;/em&gt;) CNN gọn nhẹ.&lt;/li&gt;
  &lt;li&gt;Các bài toán ảnh y khoa và viễn thám vẫn ưu tiên &lt;strong&gt;decoder tích chập&lt;/strong&gt; kiểu U-Net đặt trên các encoder hiện đại.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;khi-nào-cnn-vẫn-là-lựa-chọn-phù-hợp&quot;&gt;Khi nào CNN vẫn là lựa chọn phù hợp&lt;/h3&gt;

&lt;p&gt;Các bài toán dự đoán dày đặc ở độ phân giải cao, yêu cầu độ trễ thấp trên NPU thiết bị di động hoặc tập dữ liệu quy mô nhỏ thường tiếp tục sử dụng EfficientNetV2, ConvNeXt-Tiny hay phần cổ (&lt;em&gt;neck&lt;/em&gt;) của họ YOLO. Trong khi đó, Transformer phát huy thế mạnh rõ rệt khi có thể tiền huấn luyện ở quy mô dữ liệu rất lớn.&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-phần-mềm-phổ-biến&quot;&gt;3. Thư viện và Phần mềm Phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/pytorch-image-models&quot;&gt;timm&lt;/a&gt; — cung cấp ConvNeXt, EfficientNetV2 cùng nhiều mô hình tiền huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ultralytics/ultralytics&quot;&gt;Ultralytics YOLO&lt;/a&gt; — bộ phát hiện đối tượng dựa trên tích chập (YOLOv8/v11) phổ biến trong công nghiệp.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/dinov2&quot;&gt;facebookresearch/dinov2&lt;/a&gt; và &lt;a href=&quot;https://github.com/facebookresearch/sam2&quot;&gt;facebookresearch/sam2&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2201.03545&quot;&gt;A ConvNet for the 2020s (Liu et al., 2022)&lt;/a&gt; — giới thiệu ConvNeXt.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2301.00808&quot;&gt;ConvNeXt V2 (Woo et al., 2023)&lt;/a&gt; — bổ sung GRN và tiền huấn luyện FCMAE.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.07193&quot;&gt;DINOv2 (Oquab et al., 2023)&lt;/a&gt; — đặc trưng thị giác tự giám sát quy mô lớn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.02643&quot;&gt;Segment Anything (Kirillov et al., 2023)&lt;/a&gt; — mô hình nền tảng cho bài toán phân đoạn theo gợi ý.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-mối-liên-hệ-với-các-bài-học-cốt-lõi&quot;&gt;5. Mối liên hệ với các Bài học Cốt lõi&lt;/h2&gt;

&lt;p&gt;Các bài tập tính kích thước và phép tính tích chập ở phần cốt lõi vẫn giữ nguyên giá trị. Bài này chỉ bổ sung góc nhìn thực tiễn về các kiến trúc thay thế VGG/ResNet sau năm 2022 — gồm ConvNet hiện đại và mô hình nền tảng thị giác — chứ không thay đổi định nghĩa của phép lọc tích chập.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=QqejV0LNDHA&quot;&gt;ConvNeXt: A ConvNet for the 2020s – Paper Explained (with animations)&lt;/a&gt; — AI Coffee Break with Letitia, tiếng Anh. Giải thích chi tiết cách ConvNeXt kế thừa công thức huấn luyện và thiết kế từ Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, tiếng Anh. Tổng quan kiến trúc CNN hiện đại làm nền cho các cải tiến trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=w1UsKanMatM&quot;&gt;Residual Networks (ResNet) [Physics Informed Machine Learning]&lt;/a&gt; — Steve Brunton, tiếng Anh. Ôn lại cấu trúc khối dư mà ConvNeXt vẫn tiếp tục giữ lại.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-98 Luyện phỏng vấn (CNN và đặc trưng sớm)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Trong các vòng phỏng vấn kỹ sư Machine Learning / Computer Vision tại các công ty công nghệ lớn, người phỏng vấn hiếm khi hỏi bạn thuộc lòng API PyTorch. Thay vào đó, họ thường đưa ra một tờ giấy trắng và yêu cầu bạn &lt;strong&gt;tính nhẩm số tham số, kích thước tensor, trường tiếp nhận&lt;/strong&gt; và giải thích bản chất toán học của từng lựa chọn kiến trúc trong vòng 2 phút.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nhóm-câu-hỏi-phỏng-vấn-cốt-lõi-về-cnn&quot;&gt;Kiến thức cần nhớ: Bốn nhóm câu hỏi phỏng vấn cốt lõi về CNN&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính nhanh kích thước và ngân sách tham số&lt;/strong&gt;:
Thành thạo hai công thức \(H&apos; = \lfloor (H + 2p - k)/s \rfloor + 1\) và \(\text{Params} = (k_h k_w C_{\text{in}} + 1) C_{\text{out}}\), đồng thời nhớ nói rõ có bias hay không (khi đứng trước BatchNorm thường tắt bias).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh đổi kiến trúc (Architectural Trade-offs)&lt;/strong&gt;:
Biết chứng minh bằng số vì sao chuỗi \(3 \times 3\) tốt hơn \(5 \times 5\) hay \(7 \times 7\), và khi nào cần tích chập \(1 \times 1\) hoặc depthwise separable.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân biệt sắc bén Đồng biến (Equivariance) và Bất biến (Invariance)&lt;/strong&gt;:
Tích chập thuần túy có tính &lt;em&gt;đồng biến tịnh tiến&lt;/em&gt; (\(f(T(x)) = T(f(x))\): ảnh dịch thì feature map dịch theo); chỉ khi kết hợp với Pooling/GAP thì biểu diễn mới tiến dần tới &lt;em&gt;bất biến tịnh tiến&lt;/em&gt; (\(f(T(x)) \approx f(x)\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế hoạt động của Kết nối tắt và lan truyền ngược&lt;/strong&gt;:
Giải thích được bằng đạo hàm chuỗi lý do kết nối tắt \(y = F(x) + x\) cứu gradient và giải quyết bài toán suy thoái chiều sâu.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-kiểm-chứng-bằng-số-câu-hỏi-phỏng-vấn-kinh-điển--hai-tầng-3-times-3-vs-một-tầng-5-times-5&quot;&gt;Giải thích: Kiểm chứng bằng số câu hỏi phỏng vấn kinh điển — “Hai tầng \(3 \times 3\) vs. một tầng \(5 \times 5\)”&lt;/h3&gt;

&lt;p&gt;Giả sử \(C_{\text{in}} = C_{\text{out}} = 64\) và ta xét trên một bản đồ đặc trưng \(32 \times 32\) (bỏ qua bias):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Tiêu chí so sánh&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Một tầng Conv \(5 \times 5\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hai tầng Conv \(3 \times 3\) liên tiếp&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Chênh lệch&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Trường tiếp nhận&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(5 \times 5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(3 + (3-1)\cdot 1 = 5 \times 5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Bằng nhau&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Số tham số&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(25 \times 64^2 = \mathbf{102{,}400}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(2 \times 9 \times 64^2 = \mathbf{73{,}728}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Giảm &lt;strong&gt;28%&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Số tầng phi tuyến (ReLU)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;2&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Biểu diễn phong phú hơn&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Bộ nhớ kích hoạt trung gian&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Chỉ lưu 1 tensor đầu ra&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Cần lưu thêm 1 tensor trung gian \(32\times 32\times 64\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Tốn thêm RAM khi train&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Khi trả lời phỏng vấn, nêu được cả 3 ưu điểm đầu &lt;strong&gt;lẫn&lt;/strong&gt; đánh đổi về bộ nhớ kích hoạt ở dòng cuối sẽ cho thấy bạn có kinh nghiệm triển khai thực tế chứ không chỉ học thuộc lý thuyết.&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-luyện-phỏng-vấn--cnn-và-đặc-trưng-sớm&quot;&gt;Tùy chọn: Luyện phỏng vấn — CNN và Đặc trưng Sớm&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; lặp lại phần toán tích chập, tầng gộp hay lịch sử LeNet–ResNet. Sau khi học các bài chính trong chương, bạn có thể luyện tập với bộ câu hỏi dưới đây rồi mở &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) để tham khảo thêm các câu hỏi kèm lời giải đầy đủ về tích chập, kiến trúc CNN và trích xuất đặc trưng ban đầu.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Chủ đề tham khảo trong sách cho chương này (đọc trực tiếp trong bản PDF):&lt;/strong&gt; hình học tích chập, kiến trúc CNN và phần đầu của chủ đề trích xuất đặc trưng. Phần luyện về học chuyển giao tiếp tục ở &lt;strong&gt;15-98&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Trang tổng hợp: &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;câu-hỏi-luyện-tập&quot;&gt;Câu hỏi luyện tập&lt;/h2&gt;

&lt;h3 id=&quot;q1-so-sánh-số-tham-số-tầng-tích-chập-và-tầng-liên-kết-đầy-đủ&quot;&gt;Q1. So sánh số tham số: tầng tích chập và tầng liên kết đầy đủ&lt;/h3&gt;

&lt;p&gt;Một tầng ánh xạ tensor kích thước \(32\times32\times3\) thành bản đồ đặc trưng \(32\times32\times16\). Hãy so sánh số tham số giữa (a) một tầng liên kết đầy đủ (&lt;em&gt;dense&lt;/em&gt;) nhận đầu vào đã làm phẳng và (b) một tầng tích chập \(3\times3\) với 16 kênh đầu ra, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;same&lt;/code&gt; padding, có bias. Trong buổi phỏng vấn, bạn nên nêu điểm nào trước?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Công thức số tham số của tầng tích chập là \(k_h k_w c_{\mathrm{in}} c_{\mathrm{out}} + c_{\mathrm{out}}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Với tầng liên kết đầy đủ: đầu vào có \(32\cdot32\cdot3=3072\) phần tử, đầu ra có \(32\cdot32\cdot16=16384\) phần tử, nên tổng tham số là \(3072\cdot16384+16384\) (hơn 50 triệu). Với tầng tích chập: chỉ cần \(3\cdot3\cdot3\cdot16+16=448\) tham số. Khi trả lời phỏng vấn, nên nêu trực tiếp con số của tầng tích chập cùng công thức, sau đó giải thích &lt;em&gt;lý do&lt;/em&gt; (kết nối cục bộ và chia sẻ trọng số) thay vì chỉ nói chung chung rằng CNN ít tham số hơn.&lt;/p&gt;

&lt;h3 id=&quot;q2-tính-tay-kích-thước-đầu-ra&quot;&gt;Q2. Tính tay kích thước đầu ra&lt;/h3&gt;

&lt;p&gt;Cho đầu vào kích thước \(H\times W=28\times28\), nhân \(5\times5\), bước nhảy \(s=1\), đệm \(p=0\), và \(c_{\mathrm{out}}=8\). Kích thước tensor đầu ra là bao nhiêu? Kết quả thay đổi thế nào nếu \(s=2\) và \(p=2\)?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Áp dụng công thức \(H&apos;=\bigl\lfloor(H+2p-k)/s\bigr\rfloor+1\) (tương tự cho \(W&apos;\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Trường hợp thứ nhất: \(H&apos;=28-5+1=24\), kích thước đầu ra là \(24\times24\times8\). Trường hợp thứ hai: \(H&apos;=\lfloor(28+4-5)/2\rfloor+1=\lfloor 27/2\rfloor+1=14\), kích thước đầu ra là \(14\times14\times8\). Khi trả lời, luôn ghi rõ quy ước sắp xếp chiều (&lt;em&gt;channels-last&lt;/em&gt; hay &lt;em&gt;channels-first&lt;/em&gt;) vì các framework dùng quy ước khác nhau.&lt;/p&gt;

&lt;h3 id=&quot;q3-hai-tầng-3times3-so-với-một-tầng-5times5&quot;&gt;Q3. Hai tầng \(3\times3\) so với một tầng \(5\times5\)&lt;/h3&gt;

&lt;p&gt;Hai tầng tích chập \(3\times3\) xếp chồng (không pooling, stride 1, padding giữ kích thước) và một tầng tích chập \(5\times5\) có cùng trường tiếp nhận lý thuyết trên đầu vào. Giả sử số kênh luôn là \(c\), hãy nêu một lý do về số tham số và một lý do về năng lực biểu diễn để chọn cấu trúc xếp chồng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Khi stride bằng 1, mỗi tầng cộng thêm \((k-1)\) vào trường tiếp nhận.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Một tầng \(5\times5\) cần \(25c^2\) trọng số, trong khi hai tầng \(3\times3\) chỉ cần \(2 \times 9c^2 = 18c^2\) trọng số và bổ sung thêm một hàm kích hoạt phi tuyến ở giữa, khiến phép biến đổi hợp thành không còn là một bộ lọc tuyến tính đơn thuần. Thiết kế của VGG dựa đúng trên lập luận này. (Nếu người phỏng vấn hỏi mở rộng sang depthwise-separable hay bottleneck \(1\times1\), đó là câu hỏi nâng cao ngoài trọng tâm cơ bản của chương.)&lt;/p&gt;

&lt;h3 id=&quot;q4-đồng-biến-tịnh-tiến-equivariance-và-bất-biến-tịnh-tiến-invariance&quot;&gt;Q4. Đồng biến tịnh tiến (&lt;em&gt;equivariance&lt;/em&gt;) và bất biến tịnh tiến (&lt;em&gt;invariance&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Áp dụng một bộ lọc dò cạnh đứng lên ảnh, sau đó dịch ảnh sang phải 2 pixel rồi lọc lại. Bản đồ đặc trưng đầu ra sẽ thay đổi thế nào nếu phép toán là tích chập đúng nghĩa? Cần thêm phép toán gì nếu muốn &lt;em&gt;bộ phân loại&lt;/em&gt; không bị ảnh hưởng bởi độ dịch đó?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Tích chập giao hoán với phép tịnh tiến; gộp toàn cục (&lt;em&gt;global pooling&lt;/em&gt;) loại bỏ thông tin vị trí không gian.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Bản đồ đặc trưng đầu ra cũng sẽ dịch sang phải đúng 2 pixel — đây là tính &lt;em&gt;đồng biến tịnh tiến&lt;/em&gt; (&lt;em&gt;translation equivariance&lt;/em&gt;). Khi bổ sung tầng global average/max pooling (hoặc giảm mẫu đủ mạnh) ở cuối mạng, vector đặc trưng đưa vào lớp phân loại trở nên gần &lt;em&gt;bất biến tịnh tiến&lt;/em&gt; (&lt;em&gt;translation invariance&lt;/em&gt;) hơn. Nhầm lẫn giữa hai thuật ngữ này là lỗi rất phổ biến khi phỏng vấn.&lt;/p&gt;

&lt;h3 id=&quot;q5-vai-trò-của-kết-nối-tắt-đồng-nhất&quot;&gt;Q5. Vai trò của kết nối tắt đồng nhất&lt;/h3&gt;

&lt;p&gt;Trong một khối dư \(\mathbf{y} = \mathbf{x} + \mathcal{F}(\mathbf{x})\), hãy viết dạng tổng quát của đạo hàm \(\partial\mathbf{y}/\partial\mathbf{x}\). Vì sao điều này giúp huấn luyện CNN 50 tầng hiệu quả hơn so với chỉ dùng ReLU?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Chú ý hạng tử ma trận đơn vị \(I\) từ nhánh tắt; \(\mathcal{F}\) có thể nhỏ khi mới khởi tạo.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Ta có \(\frac{\partial\mathbf{y}}{\partial\mathbf{x}} = I + \frac{\partial\mathcal{F}}{\partial\mathbf{x}}\). Thành phần đơn vị \(I\) duy trì một đường truyền không bị suy giảm cho gradient ngay cả khi \(\partial\mathcal{F}/\partial\mathbf{x}\) nhỏ, nhờ đó tín hiệu đạo hàm đi qua được nhiều khối liên tiếp. Ngược lại, mạng thuần không có kết nối tắt (dù dùng ReLU) vẫn phải nhân liên tiếp nhiều ma trận Jacobian có thể làm gradient co nhỏ. Đây là lý do về mặt tối ưu kiến trúc, không phải khẳng định tuyệt đối rằng ResNet luôn cho độ chính xác cao nhất trong mọi bài toán.&lt;/p&gt;

&lt;h2 id=&quot;ghi-công&quot;&gt;Ghi công&lt;/h2&gt;

&lt;p&gt;Kashani, S., và Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Bạn có thể tải bản PDF từ arXiv để tham khảo đầy đủ bộ câu hỏi và lời giải. Trang này là bộ bài luyện gốc của khóa học, không phải bản sao chép từ sách.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Nên xem trước khi làm các câu hỏi tính toán về tích chập.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, tiếng Anh. Ôn lại công thức tính kích thước đầu ra dùng cho câu Q2.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Hữu ích khi cần giải thích trực quan bộ lọc đang phát hiện đặc trưng gì.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-02 Tầng Gộp và Kiến trúc CNN</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_02_Pooling_and_Architectures/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_02_Pooling_and_Architectures</id>
   <content type="html">&lt;p&gt;Nếu tầng tích chập là đôi mắt tinh tường phát hiện từng chi tiết nhỏ, thì &lt;strong&gt;tầng gộp (pooling)&lt;/strong&gt; và &lt;strong&gt;kiến trúc tổng thể&lt;/strong&gt; chính là cách bộ não chắt lọc thông tin: bỏ qua những xê dịch nhỏ không đáng kể, nén dần không gian để tập trung vào ngữ nghĩa, và tổ chức hàng chục đến hàng trăm tầng sao cho tín hiệu học không bao giờ bị nghẽn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-của-tầng-gộp-và-thiết-kế-kiến-trúc-cnn&quot;&gt;Kiến thức cần nhớ: Ba trụ cột của Tầng Gộp và Thiết kế Kiến trúc CNN&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tầng Gộp (Max, Average, Global Average Pooling)&lt;/strong&gt;:
Đóng vai trò giảm độ phân giải không gian, tiết kiệm bộ nhớ/FLOPs, tăng trường tiếp nhận và mang lại tính bất biến cục bộ trước các dịch chuyển nhỏ vài pixel.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thay thế tầng Dense khổng lồ bằng Global Average Pooling (GAP)&lt;/strong&gt;:
Thay vì duỗi phẳng (flatten) bản đồ đặc trưng rồi nối vào tầng FC hàng chục triệu tham số dễ overfitting, GAP lấy trung bình toàn bộ mỗi kênh thành đúng 1 con số duy nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy luật tiến hóa của các kiến trúc CNN kinh điển&lt;/strong&gt;:
Đi từ những khối xếp chồng tuần tự (LeNet, AlexNet, VGG) sang các thiết kế đa nhánh (Inception) và đường cao tốc gradient bằng kết nối tắt (ResNet).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-lượng-tham-số-tiết-kiệm-khi-thay-flatten--fc-bằng-global-average-pooling&quot;&gt;Giải thích: Tính tay lượng tham số tiết kiệm khi thay Flatten + FC bằng Global Average Pooling&lt;/h3&gt;

&lt;p&gt;Giả sử trước bộ phân loại 1.000 lớp (ImageNet), bản đồ đặc trưng cuối cùng có kích thước \(7 \times 7 \times 512\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Kiểu cổ điển (VGG — Flatten + tầng FC 4096 ẩn)&lt;/strong&gt;:
Số phần tử sau khi duỗi phẳng: \(7 \times 7 \times 512 = 25{,}088\).
Riêng tầng FC đầu tiên ánh xạ \(25{,}088 \to 4{,}096\) đã tốn:
\(25{,}088 \times 4{,}096 + 4{,}096 = \mathbf{102{,}764{,}544}\) tham số (hơn 102 triệu!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểu hiện đại (ResNet — GAP + 1 tầng Linear 1000)&lt;/strong&gt;:
GAP nén mỗi mặt phẳng \(7 \times 7\) thành 1 số trung bình \(\Rightarrow\) vector chỉ còn &lt;strong&gt;512&lt;/strong&gt; chiều (0 tham số học).
Tầng phân loại cuối ánh xạ \(512 \to 1{,}000\) chỉ tốn:
\(512 \times 1{,}000 + 1{,}000 = \mathbf{513{,}000}\) tham số.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chiến lược GAP cắt giảm hơn &lt;strong&gt;200 lần&lt;/strong&gt; số tham số ở phần đầu ra, đồng thời giúp mạng chấp nhận ảnh đầu vào với nhiều độ phân giải khác nhau.&lt;/p&gt;

&lt;p&gt;Phần này hoàn thiện các thành phần cốt lõi của CNN: &lt;strong&gt;tầng gộp&lt;/strong&gt; (&lt;em&gt;pooling&lt;/em&gt;) dùng để giảm kích thước không gian và &lt;strong&gt;các kiến trúc kinh điển&lt;/strong&gt; minh họa cách kết hợp tầng tích chập cùng tầng gộp trong thực tế.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tầng Gộp&lt;/strong&gt; — max pooling, average pooling, global average pooling, nền tảng toán học và cài đặt&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc CNN Kinh điển&lt;/strong&gt; — LeNet, AlexNet, VGG, ResNet, các bài báo nền tảng và tổng kết&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bạn nên đọc bài về tầng gộp trước rồi chuyển sang phần khảo sát các kiến trúc.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=ZjM_XQa5s6s&quot;&gt;Max Pooling in Convolutional Neural Networks explained&lt;/a&gt; — deeplizard, tiếng Anh. Trình bày max pooling — thành phần giảm mẫu cốt lõi của phần đầu.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 9&lt;/td&gt;
          &lt;td&gt;CNN Architectures](https://www.youtube.com/watch?v=DAOcjicFr1Y) — Stanford University School of Engineering, tiếng Anh. Tổng quan các kiến trúc kinh điển từ LeNet đến ResNet.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=w1UsKanMatM&quot;&gt;Residual Networks (ResNet) [Physics Informed Machine Learning]&lt;/a&gt; — Steve Brunton, tiếng Anh. Phân tích kết nối tắt trong ResNet — kiến trúc trọng tâm ở cuối phần này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-02-02 Kiến trúc CNN Kinh điển</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_02_02_Classic_CNN_Architectures/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_02_02_Classic_CNN_Architectures</id>
   <content type="html">&lt;p&gt;Năm 2012, tại cuộc thi thị giác máy tính danh giá ImageNet, một mô hình CNN mang tên AlexNet bất ngờ đánh bại toàn bộ các phương pháp thị giác cổ điển với khoảng cách sai số hơn 10 điểm phần trăm — một cú địa chấn làm thay đổi hoàn toàn lịch sử trí tuệ nhân tạo. Từ cột mốc đó đến năm 2015, các kiến trúc kinh điển nối tiếp nhau ra đời, mỗi kiến trúc đều giải quyết một nút thắt kỹ thuật quan trọng của thế hệ trước.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-mốc-tiến-hóa-của-kiến-trúc-cnn-kinh-điển&quot;&gt;Kiến thức cần nhớ: Bốn mốc tiến hóa của Kiến trúc CNN Kinh điển&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;LeNet-5 (1998) — Bản thiết kế sơ khai hoàn chỉnh&lt;/strong&gt;:
Yann LeCun chứng minh chuỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv -&amp;gt; Pool -&amp;gt; Conv -&amp;gt; Pool -&amp;gt; FC&lt;/code&gt; có thể đọc chữ số viết tay trên hàng triệu tờ séc ngân hàng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;AlexNet (2012) — Mở khóa quy mô bằng GPU, ReLU và Dropout&lt;/strong&gt;:
Thay &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tanh/sigmoid&lt;/code&gt; bằng ReLU giúp huấn luyện nhanh gấp 6 lần, kết hợp tăng cường dữ liệu (data augmentation) và Dropout để chống overfitting trên 1,2 triệu ảnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;VGGNet (2014) — Triết lý đồng nhất bằng bộ lọc \(3 \times 3\)&lt;/strong&gt;:
Chứng minh rằng xếp chồng nhiều bộ lọc nhỏ \(3 \times 3\) tốt hơn hẳn việc dùng bộ lọc lớn \(7 \times 7\) hay \(11 \times 11\): ít tham số hơn nhưng có nhiều tầng phi tuyến hơn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ResNet (2015) — Phá vỡ trần chiều sâu bằng kết nối tắt&lt;/strong&gt;:
Giải quyết nghịch lý suy thoái (mạng sâu hơn lại có sai số huấn luyện cao hơn) bằng cách học phần dư \(F(x) = H(x) - x\) thay vì học trực tiếp ánh xạ \(H(x)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-bảng-đối-chiếu-quy-mô-và-bước-nhảy-vọt-hiệu-năng-trên-imagenet&quot;&gt;Giải thích: Bảng đối chiếu quy mô và bước nhảy vọt hiệu năng trên ImageNet&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Kiến trúc&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Năm&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Độ sâu có trọng số&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Top-5 Error (ImageNet)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Đột phá cốt lõi&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;LeNet-5&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1998&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;5 tầng&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;— (MNIST ~0,95%)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Kết hợp Conv + Pooling + Backprop đầu tiên&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;AlexNet&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2012&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;8 tầng&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;16,4%&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;ReLU, Dropout, huấn luyện trên 2 GPU&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;VGG-16&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2014&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;16 tầng&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;7,3%&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Chuẩn hóa hoàn toàn bằng nhân nhỏ \(3 \times 3\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;ResNet-152&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2015&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;152 tầng&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;3,57%&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Kết nối tắt \(y = F(x) + x\), vượt chuẩn người (~5%)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ trong 3 năm (2012–2015), sai số Top-5 giảm gần &lt;strong&gt;5 lần&lt;/strong&gt; trong khi độ sâu tăng gần &lt;strong&gt;20 lần&lt;/strong&gt; — tất cả xoay quanh hai câu hỏi cốt lõi: &lt;em&gt;dùng bộ lọc cỡ nào&lt;/em&gt; và &lt;em&gt;giữ gradient sống sót ra sao&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Phần này giới thiệu các kiến trúc CNN kinh điển theo tiến trình phát triển:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;LeNet và AlexNet&lt;/strong&gt; — hai cột mốc mở đầu của thị giác máy tính dùng học sâu&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;VGG, ResNet và Tiến hóa Kiến trúc&lt;/strong&gt; — mở rộng độ sâu, kết nối tắt (&lt;em&gt;skip connections&lt;/em&gt;), các bài báo nền tảng và tổng kết điểm chính&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Lecture 9&lt;/td&gt;
          &lt;td&gt;CNN Architectures](https://www.youtube.com/watch?v=DAOcjicFr1Y) — Stanford University School of Engineering, tiếng Anh. Bài giảng trình bày liên mạch các kiến trúc LeNet, AlexNet, VGG và ResNet.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 1&lt;/td&gt;
          &lt;td&gt;Introduction to Convolutional Neural Networks for Visual Recognition](https://www.youtube.com/watch?v=vT1JzLTH4G4) — Stanford University School of Engineering, tiếng Anh. Bối cảnh lịch sử lý giải vì sao bài toán ImageNet thúc đẩy sự đổi mới kiến trúc.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=w1UsKanMatM&quot;&gt;Residual Networks (ResNet) [Physics Informed Machine Learning]&lt;/a&gt; — Steve Brunton, tiếng Anh. Phân tích cơ chế kết nối dư khép lại chuỗi kiến trúc kinh điển này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-02-02-02 VGG, ResNet và Tiến hóa Kiến trúc</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_02_02_02_VGG_ResNet_and_Evolution/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_02_02_02_VGG_ResNet_and_Evolution</id>
   <content type="html">&lt;p&gt;Năm 2015, nhóm nghiên cứu của Kaiming He tại Microsoft Research chứng kiến một hiện tượng hết sức trớ trêu: khi họ xếp chồng một mạng CNN thường lên 56 tầng thay vì 20 tầng trên tập CIFAR-10, &lt;strong&gt;ngay cả sai số huấn luyện (training error)&lt;/strong&gt; của mạng 56 tầng cũng tệ hơn mạng 20 tầng! Đó không phải overfitting — mà là &lt;strong&gt;vấn đề suy thoái (degradation problem)&lt;/strong&gt;. Và giải pháp của họ lại đơn giản đến mức ai cũng phải thốt lên: chỉ cần cộng thêm đầu vào \(x\) vào đầu ra của khối tích chập, tạo nên &lt;strong&gt;ResNet&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nguyên-lý-thiết-kế-từ-vgg-đến-resnet&quot;&gt;Kiến thức cần nhớ: Bốn nguyên lý thiết kế từ VGG đến ResNet&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nguyên lý VGG — Phân rã nhân lớn thành chuỗi nhân \(3 \times 3\)&lt;/strong&gt;:
Hai tầng \(3 \times 3\) liên tiếp có cùng trường tiếp nhận với một tầng \(5 \times 5\), và ba tầng \(3 \times 3\) tương đương một tầng \(7 \times 7\), nhưng ít tham số hơn nhiều và có thêm nhiều lớp ReLU phi tuyến ở giữa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nghịch lý suy thoái (Degradation) vs. Overfitting&lt;/strong&gt;:
Về lý thuyết, một mạng sâu hơn ít nhất phải tốt bằng mạng nông nếu các tầng thêm vào học ánh xạ đồng nhất \(H(x) = x\). Thực tế, bộ tối ưu cực kỳ khó ép một chuỗi tầng phi tuyến học chính xác hàm đồng nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học phần dư (Residual Learning) \(H(x) = F(x) + x\)&lt;/strong&gt;:
Khi viết lại đầu ra khối là \(F(x) + x\), muốn học ánh xạ đồng nhất, mạng chỉ cần đẩy các trọng số của nhánh \(F(x)\) về \(0\) — điều mà khởi tạo nhỏ và weight decay làm cực kỳ dễ dàng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đường cao tốc Gradient (Gradient Highway)&lt;/strong&gt;:
Khi đạo hàm ngược qua \(y = F(x) + x\), ta có \(\frac{\partial \mathcal{L}}{\partial x} = \frac{\partial \mathcal{L}}{\partial y}\left(\frac{\partial F(x)}{\partial x} + I\right)\). Số hạng đơn vị \(+I\) đảm bảo gradient luôn chảy thẳng về các tầng đầu mà không bị triệt tiêu kể cả khi mạng sâu hơn 100 tầng.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-so-sánh-3-tầng-3-times-3-vgg-với-1-tầng-7-times-7-và-dòng-gradient-trong-resnet&quot;&gt;Giải thích: Tính tay so sánh 3 tầng \(3 \times 3\) (VGG) với 1 tầng \(7 \times 7\) và dòng gradient trong ResNet&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Tại sao VGG chọn 3 tầng \(3 \times 3\) thay vì 1 tầng \(7 \times 7\)&lt;/strong&gt; (với \(C_{\text{in}} = C_{\text{out}} = C\) kênh):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Trường tiếp nhận&lt;/strong&gt;: Tầng 1 nhìn \(3\times 3\) \(\to\) Tầng 2 nhìn \(5\times 5\) \(\to\) Tầng 3 nhìn &lt;strong&gt;\(7\times 7\)&lt;/strong&gt; (y hệt 1 tầng \(7\times 7\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Số tham số&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;1 tầng \(7 \times 7\): \(7 \times 7 \times C^2 = \mathbf{49 C^2}\).&lt;/li&gt;
      &lt;li&gt;3 tầng \(3 \times 3\): \(3 \times (3 \times 3 \times C^2) = \mathbf{27 C^2}\) (tiết kiệm &lt;strong&gt;45%&lt;/strong&gt; tham số!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ phi tuyến&lt;/strong&gt;: 3 lần ReLU thay vì chỉ 1 lần ReLU.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Kiểm chứng đường cao tốc gradient của ResNet&lt;/strong&gt;:
Giả sử một khối phi tuyến có đạo hàm rất nhỏ \(\frac{\partial F}{\partial x} = 0{,}1\) và ta xếp chồng \(L = 20\) khối:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mạng thường (không skip)&lt;/strong&gt;: Gradient thu nhỏ theo \(0{,}1^{20} = \mathbf{10^{-20}}\) (tắt lịm hoàn toàn!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mạng ResNet (có skip \(+x\))&lt;/strong&gt;: Đạo hàm mỗi khối là \(1 + 0{,}1 = 1{,}1\), gradient không những không tắt mà còn truyền nguyên vẹn từ tầng 20 về tầng 1 nhờ số hạng \(1\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;vggnet-2014--đơn-giản-và-chiều-sâu&quot;&gt;VGGNet (2014) — Đơn giản và Chiều sâu&lt;/h3&gt;

&lt;p&gt;VGG của Simonyan và Zisserman cho thấy việc &lt;strong&gt;tăng chiều sâu&lt;/strong&gt; với một cấu trúc &lt;strong&gt;đồng nhất, đơn giản&lt;/strong&gt; mang lại cải thiện rõ rệt về độ chính xác.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ý tưởng chính:&lt;/strong&gt; Chỉ sử dụng các tầng tích chập 3×3 xếp chồng liên tiếp.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiến trúc VGG-16:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (224×224×3)

Block 1: Conv3-64, Conv3-64, MaxPool → 112×112×64
Block 2: Conv3-128, Conv3-128, MaxPool → 56×56×128
Block 3: Conv3-256, Conv3-256, Conv3-256, MaxPool → 28×28×256
Block 4: Conv3-512, Conv3-512, Conv3-512, MaxPool → 14×14×512
Block 5: Conv3-512, Conv3-512, Conv3-512, MaxPool → 7×7×512

Flatten → FC 4096 → FC 4096 → FC 1000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Vì sao chọn nhân 3×3:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Hai tầng 3×3 nối tiếp cho cùng trường tiếp nhận 5×5 như một tầng 5×5, nhưng:
    &lt;ul&gt;
      &lt;li&gt;Ít tham số hơn: \(2 \times (3 \times 3) = 18\) so với \(5 \times 5 = 25\) (trên mỗi cặp kênh)&lt;/li&gt;
      &lt;li&gt;Nhiều lớp phi tuyến hơn: 2 lớp ReLU so với 1&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Ba tầng 3×3 nối tiếp cho trường tiếp nhận tương đương 7×7&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Tổng số tham số vào khoảng &lt;strong&gt;138 triệu&lt;/strong&gt; (phần lớn tập trung ở các tầng liên kết đầy đủ cuối mạng).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VGG16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kiến trúc VGG-16&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Khối 1
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Khối 2
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Khối 3
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Khối 4
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Khối 5
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;resnet-2015--bước-tiến-từ-kết-nối-tắt&quot;&gt;ResNet (2015) — Bước tiến từ Kết nối Tắt&lt;/h3&gt;

&lt;p&gt;ResNet của Kaiming He và cộng sự giải quyết &lt;strong&gt;bài toán suy giảm&lt;/strong&gt; (&lt;em&gt;degradation problem&lt;/em&gt;): khi tăng chiều sâu vượt một ngưỡng nhất định, mạng sâu hơn lại có sai số &lt;em&gt;huấn luyện&lt;/em&gt; cao hơn mạng nông, dù về lý thuyết có dung lượng lớn hơn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nguyên nhân:&lt;/strong&gt; Trong các mạng quá sâu (trên khoảng 20 tầng), dù đã khởi tạo cẩn thận và dùng chuẩn hóa batch, việc tối ưu trực tiếp một chuỗi dài các biến đổi phi tuyến vẫn gặp khó khăn do gradient suy giảm hoặc khó học ánh xạ đồng nhất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Giải pháp:&lt;/strong&gt; &lt;strong&gt;Kết nối dư&lt;/strong&gt; (&lt;em&gt;residual connections&lt;/em&gt; hay &lt;em&gt;skip connections&lt;/em&gt;). Thay vì học trực tiếp ánh xạ mong muốn \(H(\mathbf{x})\), khối mạng học phần dư \(F(\mathbf{x}) = H(\mathbf{x}) - \mathbf{x}\) rồi cộng đầu vào:&lt;/p&gt;

\[\mathbf{y} = F(\mathbf{x}) + \mathbf{x}\]

&lt;p&gt;&lt;strong&gt;Vì sao cơ chế này hiệu quả:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Dễ học ánh xạ đồng nhất:&lt;/strong&gt; Nếu một tầng chưa cần biến đổi đầu vào, mạng chỉ cần đẩy trọng số của \(F(\mathbf{x})\) về gần 0.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đường truyền trực tiếp cho gradient:&lt;/strong&gt; Nhánh cộng đồng nhất giúp gradient truyền ngược ổn định qua hàng chục đến hàng trăm tầng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu ứng tổ hợp (&lt;em&gt;ensemble&lt;/em&gt;):&lt;/strong&gt; Mạng có kết nối tắt hoạt động tương tự sự kết hợp của nhiều đường dẫn có độ sâu khác nhau.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Khối Dư Cơ bản:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;         ┌────────────────────────────────────┐
         │               Identity             │
         │                                    │
    x ───┼──→ Conv 3×3 → BN → ReLU           │
         │        ↓                           │
         │   Conv 3×3 → BN                    │
         │        ↓                           │
         └───────⊕───→ ReLU → output
              (add)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Khối Cổ chai&lt;/strong&gt; (&lt;em&gt;Bottleneck&lt;/em&gt;, dùng cho mạng sâu như ResNet-50 trở lên):&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;         ┌──────────────────────────────────┐
         │             Identity             │
         │                                  │
    x ───┼──→ Conv 1×1 → BN → ReLU (giảm)  │
         │        ↓                         │
         │   Conv 3×3 → BN → ReLU           │
         │        ↓                         │
         │   Conv 1×1 → BN (mở rộng)        │
         │        ↓                         │
         └───────⊕───→ ReLU → output
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BasicBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Khối dư cơ bản cho ResNet-18/34&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                               &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Để khớp kích thước
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Xử lý lệch kích thước
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;downsample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Then chốt: kết nối bỏ qua!
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Bottleneck&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Khối nút thắt cho ResNet-50/101/152&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# 1×1 giảm
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# 3×3 conv
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# 1×1 mở rộng
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;downsample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cài đặt ResNet&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tầng conv ban đầu
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                               &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;maxpool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Các tầng dư
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_make_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_make_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_make_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_make_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Global average pooling + bộ phân loại
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avgpool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AdaptiveAvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_make_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blocks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;or&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                         &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blocks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maxpool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;layer1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;layer2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;layer3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;layer4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;avgpool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Tạo các biến thể ResNet chuẩn
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;BasicBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Bottleneck&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet101&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Bottleneck&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;23&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== SO SÁNH MÔ HÌNH ==============
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;So sánh Kiến trúc CNN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;models&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;LeNet-5&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LeNet5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;VGG-16&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VGG16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ResNet-18&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ResNet-50&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; parameters&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;tóm-tắt-tiến-hóa-kiến-trúc&quot;&gt;Tóm tắt Tiến hóa Kiến trúc&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Mô hình&lt;/th&gt;
      &lt;th&gt;Năm&lt;/th&gt;
      &lt;th&gt;Độ sâu&lt;/th&gt;
      &lt;th&gt;Tham số&lt;/th&gt;
      &lt;th&gt;Lỗi Top-5&lt;/th&gt;
      &lt;th&gt;Đổi mới chính&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;LeNet-5&lt;/td&gt;
      &lt;td&gt;1998&lt;/td&gt;
      &lt;td&gt;5&lt;/td&gt;
      &lt;td&gt;60K&lt;/td&gt;
      &lt;td&gt;-&lt;/td&gt;
      &lt;td&gt;CNN ứng dụng thành công sớm nhất&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;AlexNet&lt;/td&gt;
      &lt;td&gt;2012&lt;/td&gt;
      &lt;td&gt;8&lt;/td&gt;
      &lt;td&gt;60M&lt;/td&gt;
      &lt;td&gt;15,3%&lt;/td&gt;
      &lt;td&gt;ReLU, Dropout, huấn luyện GPU&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;VGG-16&lt;/td&gt;
      &lt;td&gt;2014&lt;/td&gt;
      &lt;td&gt;16&lt;/td&gt;
      &lt;td&gt;138M&lt;/td&gt;
      &lt;td&gt;7,3%&lt;/td&gt;
      &lt;td&gt;Chỉ dùng nhân 3×3, tăng chiều sâu&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;GoogLeNet&lt;/td&gt;
      &lt;td&gt;2014&lt;/td&gt;
      &lt;td&gt;22&lt;/td&gt;
      &lt;td&gt;6,8M&lt;/td&gt;
      &lt;td&gt;6,7%&lt;/td&gt;
      &lt;td&gt;Mô-đun Inception&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ResNet-50&lt;/td&gt;
      &lt;td&gt;2015&lt;/td&gt;
      &lt;td&gt;50&lt;/td&gt;
      &lt;td&gt;25M&lt;/td&gt;
      &lt;td&gt;3,6%&lt;/td&gt;
      &lt;td&gt;Kết nối tắt (&lt;em&gt;skip connections&lt;/em&gt;)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ResNet-152&lt;/td&gt;
      &lt;td&gt;2015&lt;/td&gt;
      &lt;td&gt;152&lt;/td&gt;
      &lt;td&gt;60M&lt;/td&gt;
      &lt;td&gt;3,0%&lt;/td&gt;
      &lt;td&gt;Mạng rất sâu&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;DenseNet&lt;/td&gt;
      &lt;td&gt;2017&lt;/td&gt;
      &lt;td&gt;121&lt;/td&gt;
      &lt;td&gt;8M&lt;/td&gt;
      &lt;td&gt;4,2%&lt;/td&gt;
      &lt;td&gt;Kết nối dày đặc giữa các tầng&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;EfficientNet&lt;/td&gt;
      &lt;td&gt;2019&lt;/td&gt;
      &lt;td&gt;-&lt;/td&gt;
      &lt;td&gt;5,3M&lt;/td&gt;
      &lt;td&gt;2,9%&lt;/td&gt;
      &lt;td&gt;Tìm kiếm kiến trúc và compound scaling&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-các-bài-báo-nền-tảng&quot;&gt;5. Các Bài báo Nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf&quot;&gt;“Gradient-Based Learning Applied to Document Recognition” (1998)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Yann LeCun, Léon Bottou, Yoshua Bengio, Patrick Haffner&lt;br /&gt;
Giới thiệu LeNet-5 và thiết lập khuôn mẫu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv → pool → conv → pool&lt;/code&gt; cho CNN, chứng minh khả năng học đầu–cuối bằng gradient trực tiếp từ điểm ảnh thô thay cho các đặc trưng thủ công.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.4400&quot;&gt;“Network In Network” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Min Lin, Qiang Chen, Shuicheng Yan&lt;br /&gt;
Đề xuất tích chập 1×1 để kết hợp thông tin xuyên kênh và Global Average Pooling (GAP) thay thế các tầng liên kết đầy đủ cỡ lớn, giúp giảm mạnh số tham số và trở thành chuẩn trong các kiến trúc về sau.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.1556&quot;&gt;“Very Deep Convolutional Networks for Large-Scale Image Recognition” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Karen Simonyan, Andrew Zisserman&lt;br /&gt;
Chứng minh rằng mạng sâu sử dụng bộ lọc 3×3 nhỏ vượt trội mạng nông dùng bộ lọc lớn. Kiến trúc đơn giản, đồng nhất của VGGNet trở thành một mốc tham chiếu quen thuộc cho học chuyển giao (&lt;em&gt;transfer learning&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.03385&quot;&gt;“Deep Residual Learning for Image Recognition” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun&lt;br /&gt;
Đề xuất kết nối tắt giúp khắc phục hiện tượng suy giảm ở mạng sâu và huấn luyện thành công mạng hơn 100 tầng, đạt lỗi top-5 là 3,57% trên ImageNet 2015. Nguyên lý học phần dư sau đó được áp dụng rộng rãi trong Transformer, mô hình khuếch tán và hầu hết các kiến trúc sâu khác.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1608.06993&quot;&gt;“Densely Connected Convolutional Networks” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Gao Huang, Zhuang Liu, Laurens van der Maaten, Kilian Q. Weinberger&lt;br /&gt;
DenseNet nối đầu ra của mỗi tầng tới tất cả các tầng sau trong cùng khối, khuyến khích tái sử dụng đặc trưng và tăng cường luồng gradient với số lượng tham số gọn nhẹ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1905.11946&quot;&gt;“EfficientNet: Rethinking Model Scaling” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Mingxing Tan, Quoc V. Le&lt;br /&gt;
Sử dụng tìm kiếm kiến trúc neuron để xây dựng mạng cơ sở hiệu quả, sau đó đề xuất mở rộng đồng thời cả độ sâu, độ rộng và độ phân giải (&lt;em&gt;compound scaling&lt;/em&gt;) để đạt độ chính xác cao với ít tham số và FLOPs hơn.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-điểm-then-chốt&quot;&gt;6. Điểm Then chốt&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tầng gộp&lt;/strong&gt; giảm kích thước không gian trong khi giữ lại thông tin đặc trưng chính; max pooling thường ưu tiên cho phân loại, còn average pooling phù hợp hơn cho các tác vụ cần bảo toàn thông tin nền hoặc ở dạng global pooling.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Global Average Pooling&lt;/strong&gt; thay thế các tầng liên kết đầy đủ nặng tham số, giảm khoảng 40 lần tham số ở phần đầu ra và hỗ trợ khái quát hóa tốt hơn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lộ trình tiến hóa kiến trúc:&lt;/strong&gt; LeNet (đơn giản) → AlexNet (quy mô và GPU) → VGG (độ sâu đồng nhất) → ResNet (kết nối tắt) → EfficientNet (tối ưu hiệu quả).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xếp chồng tích chập 3×3&lt;/strong&gt; thường hiệu quả hơn dùng nhân kích thước lớn về cả số tham số lẫn số lớp phi tuyến.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kết nối tắt&lt;/strong&gt; là thành phần nền tảng để huấn luyện mạng sâu, xuất hiện trong ResNet, DenseNet, U-Net, Transformer và mô hình khuếch tán.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các mẫu thiết kế phổ biến:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Khối &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv → BatchNorm → ReLU&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Kết nối tắt sau mỗi 2–3 tầng&lt;/li&gt;
      &lt;li&gt;Global Average Pooling thay cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Flatten + FC&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Tích chập có stride để giảm mẫu học được&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình tiền huấn luyện&lt;/strong&gt; (&lt;em&gt;transfer learning&lt;/em&gt;) là điểm khởi đầu thực tế cho hầu hết bài toán thị giác, vì đặc trưng học từ ImageNet chuyển giao tốt sang nhiều miền dữ liệu khác.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Chương tiếp theo:&lt;/strong&gt; Mạng Neuron Hồi quy (RNN) cho dữ liệu tuần tự.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=w1UsKanMatM&quot;&gt;Residual Networks (ResNet) [Physics Informed Machine Learning]&lt;/a&gt; — Steve Brunton, tiếng Anh. Diễn giải trực quan khối dư như sự kết hợp giữa các tầng tích chập kiểu VGG và đường nối tắt.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=RYth6EbBUqM&quot;&gt;C4W2L04 Why ResNets Work&lt;/a&gt; — DeepLearningAI, tiếng Anh. Giải thích rõ vì sao đường nối tắt giúp tăng độ sâu mà không làm suy giảm quá trình huấn luyện.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 9&lt;/td&gt;
          &lt;td&gt;CNN Architectures](https://www.youtube.com/watch?v=DAOcjicFr1Y) — Stanford University School of Engineering, tiếng Anh. Tổng hợp mạch tiến hóa từ VGG đến ResNet theo dòng thời gian.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-02-02-01 LeNet và AlexNet</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_02_02_01_LeNet_AlexNet/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_02_02_01_LeNet_AlexNet</id>
   <content type="html">&lt;p&gt;Trong suốt thập niên 1990, hệ thống đọc mã bưu chính và séc ngân hàng của Yann LeCun (LeNet-5) đã xử lý hơn 10% tổng lượng séc tại Mỹ, nhưng mạng neuron sâu vẫn bị giới nghiên cứu lạnh nhạt suốt hơn một thập kỷ vì phần cứng quá yếu. Phải đến năm 2012, khi Alex Krizhevsky tận dụng hai chiếc card đồ họa chơi game NVIDIA GTX 580 để huấn luyện AlexNet trên 1,2 triệu ảnh ImageNet, kỷ nguyên Deep Learning hiện đại mới thực sự bùng nổ.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-điểm-khác-biệt-lịch-sử-giữa-lenet-5-và-alexnet&quot;&gt;Kiến thức cần nhớ: Bốn điểm khác biệt lịch sử giữa LeNet-5 và AlexNet&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hàm kích hoạt: từ Sigmoid/Tanh sang ReLU&lt;/strong&gt;:
LeNet-5 dùng hàm bão hòa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tanh&lt;/code&gt; khiến gradient suy giảm nhanh khi đi sâu; AlexNet chuyển sang ReLU (\(\max(0, x)\)), giúp tốc độ hội tụ nhanh gấp ~6 lần.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giảm mẫu: từ Average Pooling sang Overlapping Max Pooling&lt;/strong&gt;:
AlexNet dùng Max Pooling kích thước \(3 \times 3\) với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=2&lt;/code&gt; (các cửa sổ chồng lấp lên nhau), giúp giữ đặc trưng sắc nét hơn và giảm overfitting.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kích thước nhân lớn ở tầng đầu để hạ độ phân giải nhanh&lt;/strong&gt;:
Với ảnh \(227 \times 227\), AlexNet dùng nhân \(11 \times 11, s=4\) ở tầng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv1&lt;/code&gt; nhằm cắt ngay kích thước không gian xuống \(55 \times 55\) để vừa bộ nhớ 3 GB VRAM thời đó.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỹ thuật chống Overfitting quy mô lớn&lt;/strong&gt;:
AlexNet đặt chuẩn cho bộ đôi &lt;strong&gt;Data Augmentation&lt;/strong&gt; (cắt ngẫu nhiên, lật ngang, biến đổi màu PCA) và &lt;strong&gt;Dropout (p=0,5)&lt;/strong&gt; ở các tầng liên kết đầy đủ.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-dòng-chảy-kích-thước-qua-tầng-đầu-tiên-của-alexnet&quot;&gt;Giải thích: Tính tay dòng chảy kích thước qua tầng đầu tiên của AlexNet&lt;/h3&gt;

&lt;p&gt;Với ảnh đầu vào chuẩn hóa \(227 \times 227 \times 3\) đi qua &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv1(in=3, out=96, kernel=11, stride=4, padding=0)&lt;/code&gt; rồi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MaxPool1(kernel=3, stride=2)&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sau &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv1&lt;/code&gt;&lt;/strong&gt;:
\(H_1 = \left\lfloor \frac{227 + 0 - 11}{4} \right\rfloor + 1 = \frac{216}{4} + 1 = 55 \Rightarrow \text{tensor } \mathbf{55 \times 55 \times 96}\)
Số tham số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv1&lt;/code&gt;: \((11 \times 11 \times 3 + 1) \times 96 = 364 \times 96 = \mathbf{34{,}944}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sau &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MaxPool1&lt;/code&gt; chồng lấp (\(k=3, s=2\))&lt;/strong&gt;:
\(H_2 = \left\lfloor \frac{55 - 3}{2} \right\rfloor + 1 = 26 + 1 = 27 \Rightarrow \text{tensor } \mathbf{27 \times 27 \times 96}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chỉ sau một cặp Conv–Pool đầu tiên, diện tích không gian đã thu gọn từ \(227^2 = 51{,}529\) xuống còn \(27^2 = 729\) (giảm hơn &lt;strong&gt;70 lần&lt;/strong&gt;), giải thích vì sao AlexNet có thể chạy được trên GPU chỉ có 3 GB bộ nhớ năm 2012.&lt;/p&gt;

&lt;h2 id=&quot;4-các-kiến-trúc-cnn-kinh-điển&quot;&gt;4. Các Kiến trúc CNN Kinh điển&lt;/h2&gt;

&lt;p&gt;Quá trình phát triển của các kiến trúc CNN phản ánh hành trình mở rộng độ sâu, nâng cao hiệu quả tính toán và hoàn thiện các nguyên lý thiết kế mạng. Dưới đây là hai cột mốc mở đầu quan trọng: LeNet-5 và AlexNet.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv.jpg&quot; alt=&quot;CNN&quot; /&gt;
&lt;em&gt;Tổng quan kiến trúc Mạng Neuron Tích chập (CNN). Nguồn: AnalyticsVidhya&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv6.jpg&quot; alt=&quot;CNN&quot; /&gt;
&lt;em&gt;Tổng quan kiến trúc Mạng Neuron Tích chập (CNN). Nguồn: AnalyticsVidhya&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;lenet-5-1998--kiến-trúc-tiên-phong&quot;&gt;LeNet-5 (1998) — Kiến trúc Tiên phong&lt;/h3&gt;

&lt;p&gt;LeNet-5 do Yann LeCun và cộng sự đề xuất là một trong những mạng CNN ứng dụng thành công sớm nhất, ban đầu được thiết kế cho bài toán nhận diện chữ số viết tay.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiến trúc:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (32×32×1)
    ↓
Conv1: 6 filters, 5×5, stride 1 → 28×28×6
    ↓
AvgPool: 2×2, stride 2 → 14×14×6
    ↓
Conv2: 16 filters, 5×5, stride 1 → 10×10×16
    ↓
AvgPool: 2×2, stride 2 → 5×5×16
    ↓
Flatten → 400
    ↓
FC1: 400 → 120
    ↓
FC2: 120 → 84
    ↓
Output: 84 → 10
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Đặc điểm chính:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Khoảng 60.000 tham số.&lt;/li&gt;
  &lt;li&gt;Sử dụng hàm kích hoạt tanh/sigmoid (trước khi ReLU được dùng phổ biến trong CNN).&lt;/li&gt;
  &lt;li&gt;Sử dụng average pooling (trước khi max pooling trở thành lựa chọn chuẩn).&lt;/li&gt;
  &lt;li&gt;Được huấn luyện trên tập dữ liệu chữ số viết tay MNIST (10 lớp, ảnh 28×28 được đệm lên 32×32).&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LeNet5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kiến trúc LeNet-5 (hiện đại hóa với ReLU)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;       &lt;span class=&quot;c1&quot;&gt;# 32→28
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;                   &lt;span class=&quot;c1&quot;&gt;# 28→14
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;     &lt;span class=&quot;c1&quot;&gt;# 14→10
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;                   &lt;span class=&quot;c1&quot;&gt;# 10→5
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;120&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;120&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;84&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;84&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;alexnet-2012--bước-ngoặt-trên-imagenet&quot;&gt;AlexNet (2012) — Bước ngoặt trên ImageNet&lt;/h3&gt;

&lt;p&gt;AlexNet của Krizhevsky, Sutskever và Hinton giành chiến thắng tại cuộc thi ImageNet 2012 với mức giảm lỗi đáng kể, thúc đẩy mạnh mẽ việc ứng dụng học sâu trong thị giác máy tính.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiến trúc:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (227×227×3)
    ↓
Conv1: 96 filters, 11×11, stride 4 → 55×55×96
    ↓
MaxPool: 3×3, stride 2 → 27×27×96
    ↓
Conv2: 256 filters, 5×5, pad 2 → 27×27×256
    ↓
MaxPool: 3×3, stride 2 → 13×13×256
    ↓
Conv3: 384 filters, 3×3, pad 1 → 13×13×384
    ↓
Conv4: 384 filters, 3×3, pad 1 → 13×13×384
    ↓
Conv5: 256 filters, 3×3, pad 1 → 13×13×256
    ↓
MaxPool: 3×3, stride 2 → 6×6×256
    ↓
Flatten → 9216
    ↓
FC1: 9216 → 4096 (+ Dropout 0.5)
    ↓
FC2: 4096 → 4096 (+ Dropout 0.5)
    ↓
Output: 4096 → 1000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Các đóng góp chính:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hàm kích hoạt ReLU:&lt;/strong&gt; Giúp huấn luyện nhanh hơn đáng kể so với tanh hoặc sigmoid.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dropout:&lt;/strong&gt; Kỹ thuật chính quy hóa giảm quá khớp ở các tầng liên kết đầy đủ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tăng cường dữ liệu (&lt;em&gt;data augmentation&lt;/em&gt;):&lt;/strong&gt; Cắt ngẫu nhiên, lật ngang và biến đổi màu sắc để làm phong phú tập huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Huấn luyện trên GPU:&lt;/strong&gt; Chia mô hình chạy song song trên 2 GPU (mỗi GPU có 3 GB bộ nhớ vào năm 2012).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Local Response Normalization:&lt;/strong&gt; Cơ chế chuẩn hóa cục bộ (về sau phần lớn được thay bằng BatchNorm).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Tổng số tham số khoảng &lt;strong&gt;60 triệu&lt;/strong&gt; — quy mô rất lớn vào thời điểm công bố.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;AlexNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;AlexNet đơn giản hóa&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;96&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;96&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;384&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;384&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;384&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;384&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Lecture 9&lt;/td&gt;
          &lt;td&gt;CNN Architectures](https://www.youtube.com/watch?v=DAOcjicFr1Y) — Stanford University School of Engineering, tiếng Anh. Trình bày chi tiết cấu trúc LeNet và AlexNet theo trình tự tích chập xếp chồng, tầng gộp và bộ phân loại.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 1&lt;/td&gt;
          &lt;td&gt;Introduction to Convolutional Neural Networks for Visual Recognition](https://www.youtube.com/watch?v=vT1JzLTH4G4) — Stanford University School of Engineering, tiếng Anh. Đặt bước nhảy vọt về quy mô của AlexNet trong bối cảnh lịch sử phát triển thị giác máy tính.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa các loại tầng cơ bản tạo nên hai kiến trúc này trước khi xuất hiện cơ chế kết nối dư.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-02-01 Tầng Gộp</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_02_01_Pooling_Layers/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_02_01_Pooling_Layers</id>
   <content type="html">&lt;p&gt;Khi bạn nhìn một chiếc cốc trên bàn và dịch chuyển nó sang trái vài milimet, bạn vẫn nhận ra ngay đó là cùng một chiếc cốc — não bộ không đòi hỏi mọi tế bào võng mạc phải kích hoạt ở đúng tọa độ pixel cũ. Trong CNN, cơ chế tạo ra sự “khoan dung trước xê dịch nhỏ” ấy đồng thời cắt giảm 75% kích thước bản đồ đặc trưng sau mỗi giai đoạn chính là &lt;strong&gt;tầng gộp (Pooling Layer)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-khía-cạnh-toán-học-và-thực-tiễn-của-tầng-gộp&quot;&gt;Kiến thức cần nhớ: Bốn khía cạnh toán học và thực tiễn của Tầng Gộp&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Max Pooling — Giữ lại tín hiệu nổi bật nhất&lt;/strong&gt;:
Lấy giá trị lớn nhất trong mỗi cửa sổ \(k \times k\), cực kỳ hiệu quả trong việc phát hiện &lt;em&gt;sự hiện diện&lt;/em&gt; của một đặc trưng (ví dụ có góc nhọn hay cạnh sắc hay không) bất chấp vị trí lệch đi 1 pixel.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Average Pooling — Giữ lại mật độ trung bình nền&lt;/strong&gt;:
Lấy trung bình cộng trong cửa sổ, bảo toàn thông tin bối cảnh mượt mà hơn, thường dùng ở các tầng chuyển tiếp hoặc cuối mạng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền ngược qua tầng Gộp (Routing Gradient)&lt;/strong&gt;:
Dù không có tham số học được, tầng gộp vẫn định tuyến gradient rất khác nhau: Max Pooling chỉ dồn 100% gradient về đúng vị trí đạt cực đại (các vị trí khác nhận 0), còn Average Pooling chia đều gradient cho cả \(k^2\) ô.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xu hướng thay thế Pooling bằng Strided Convolution&lt;/strong&gt;:
Nhiều kiến trúc hiện đại (All-CNN, ResNet downsample) thay Max Pooling bằng tích chập có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=2&lt;/code&gt; để mạng tự học trọng số giảm mẫu thay vì áp cứng quy tắc lấy max.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-cả-lan-truyền-xuôi-và-lan-truyền-ngược-qua-max-pooling-2-times-2&quot;&gt;Giải thích: Tính tay cả Lan truyền Xuôi và Lan truyền Ngược qua Max Pooling \(2 \times 2\)&lt;/h3&gt;

&lt;p&gt;Xét một vùng đặc trưng \(2 \times 2\) đầu vào \(X\) và giả sử gradient từ tầng trên truyền xuống cho đầu ra gộp này là \(\frac{\partial \mathcal{L}}{\partial y} = 8{,}0\):&lt;/p&gt;

\[X = \begin{bmatrix} 1 &amp;amp; 6 \\ 3 &amp;amp; 2 \end{bmatrix}\]

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Phép gộp&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Giá trị xuôi \(y\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Ma trận gradient ngược \(\frac{\partial \mathcal{L}}{\partial X}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Diễn giải trực giác&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Max Pooling \(2 \times 2\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\max(1,6,3,2) = \mathbf{6}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\begin{bmatrix} 0 &amp;amp; \mathbf{8{,}0} \\ 0 &amp;amp; 0 \end{bmatrix}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Toàn bộ gradient 8,0 chảy ngược về duy nhất ô &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(0,1)&lt;/code&gt; giữ giá trị cực đại; 3 ô còn lại không bị thay đổi.&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Average Pooling \(2 \times 2\)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\frac{1+6+3+2}{4} = \mathbf{3{,}0}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\begin{bmatrix} \mathbf{2{,}0} &amp;amp; \mathbf{2{,}0} \\ \mathbf{2{,}0} &amp;amp; \mathbf{2{,}0} \end{bmatrix}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Gradient được chia đều \(8{,}0 / 4 = 2{,}0\) cho cả 4 ô vì mỗi ô đều đóng góp hệ số \(\frac{1}{4}\) vào trung bình.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Quan sát ma trận gradient ở trên giúp bạn hiểu ngay vì sao trong PyTorch, tầng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MaxPool2d&lt;/code&gt; phải lưu lại chỉ số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;indices&lt;/code&gt; (vị trí cực đại) trong quá trình forward pass để phục vụ cho bước backward!&lt;/p&gt;

&lt;h1 id=&quot;tầng-gộp-và-kiến-trúc-cnn&quot;&gt;Tầng Gộp và Kiến trúc CNN&lt;/h1&gt;

&lt;p&gt;Sau khi nắm vững tầng tích chập, ta cần thêm hai thành phần quan trọng để xây dựng một mạng CNN hoàn chỉnh: &lt;strong&gt;tầng gộp&lt;/strong&gt; (&lt;em&gt;pooling&lt;/em&gt;) để giảm kích thước không gian và &lt;strong&gt;các mẫu thiết kế kiến trúc&lt;/strong&gt; để kết hợp hiệu quả các tầng với nhau. Bài này đi sâu vào các phép gộp phổ biến và chuẩn bị cho phần phân tích các kiến trúc CNN kinh điển.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-tầng-gộp-tổng-quan-khái-niệm&quot;&gt;1. Tầng Gộp: Tổng quan Khái niệm&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Tầng gộp&lt;/strong&gt; (&lt;em&gt;pooling&lt;/em&gt;, còn gọi là giảm mẫu — &lt;em&gt;downsampling&lt;/em&gt;) thu nhỏ kích thước không gian của bản đồ đặc trưng trong khi giữ lại những thông tin quan trọng nhất. Phép toán này mang lại bốn lợi ích chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giảm số chiều:&lt;/strong&gt; Bản đồ đặc trưng nhỏ hơn giúp giảm đáng kể khối lượng tính toán và số tham số ở các tầng phía sau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tăng tính bất biến tịnh tiến:&lt;/strong&gt; Những dịch chuyển nhỏ của đối tượng trong ảnh ít làm thay đổi đầu ra sau khi gộp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giảm nhiễu cục bộ:&lt;/strong&gt; Lấy cực đại hoặc trung bình giúp giảm độ nhạy với các dao động nhỏ ở mức điểm ảnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mở rộng trường tiếp nhận:&lt;/strong&gt; Mỗi phần tử sau khi gộp đại diện cho một vùng rộng hơn trên ảnh đầu vào gốc.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Ý tưởng cốt lõi:&lt;/strong&gt; Gộp đóng vai trò như một bước tóm tắt thông tin không gian — để nhận diện một đối tượng, mô hình cần biết các đặc trưng quan trọng có xuất hiện trong vùng đó hay không, hơn là ghi nhớ tọa độ chính xác đến từng điểm ảnh.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv5.jpg&quot; alt=&quot;CNN&quot; /&gt;
&lt;em&gt;Tổng quan kiến trúc Mạng Neuron Tích chập (CNN). Nguồn: AnalyticsVidhya&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;h3 id=&quot;max-pooling&quot;&gt;Max Pooling&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Max pooling&lt;/strong&gt; chọn giá trị lớn nhất trong mỗi cửa sổ gộp:&lt;/p&gt;

\[\text{MaxPool}(X)_{i,j} = \max_{m,n \in R_{i,j}} X_{m,n}\]

&lt;p&gt;Trong đó \(R_{i,j}\) là vùng gộp (thường 2×2) ứng với vị trí đầu ra \((i,j)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ trực quan với cửa sổ 2×2, stride 2:&lt;/strong&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Đầu vào (4×4):              Đầu ra (2×2):

┌─────┬─────┬─────┬─────┐
│  1  │  3  │  2  │  4  │     ┌─────┬─────┐
├─────┼─────┼─────┼─────┤     │  6  │  8  │
│  5  │  6  │  7  │  8  │ →   ├─────┼─────┤
├─────┼─────┼─────┼─────┤     │  3  │  4  │
│  0  │  2  │  1  │  3  │     └─────┴─────┘
├─────┼─────┼─────┼─────┤
│  1  │  3  │  2  │  4  │
└─────┴─────┴─────┴─────┘

Vùng [0:2, 0:2] = [[1,3],[5,6]] → max = 6
Vùng [0:2, 2:4] = [[2,4],[7,8]] → max = 8
Vùng [2:4, 0:2] = [[0,2],[1,3]] → max = 3
Vùng [2:4, 2:4] = [[1,3],[2,4]] → max = 4
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Tính chất của max pooling:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Giữ lại các kích hoạt mạnh nhất (đặc trưng nổi bật nhất trong vùng).&lt;/li&gt;
  &lt;li&gt;Mang lại tính bất biến trước các dịch chuyển nhỏ.&lt;/li&gt;
  &lt;li&gt;Đưa vào một dạng phép biến đổi phi tuyến.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không có tham số học được.&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;average-pooling&quot;&gt;Average Pooling&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Average pooling&lt;/strong&gt; lấy giá trị trung bình của tất cả các phần tử trong cửa sổ gộp:&lt;/p&gt;

\[\text{AvgPool}(X)_{i,j} = \frac{1}{|R_{i,j}|} \sum_{m,n \in R_{i,j}} X_{m,n}\]

&lt;p&gt;&lt;strong&gt;Ví dụ trực quan:&lt;/strong&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Đầu vào (4×4):              Đầu ra (2×2):

┌─────┬─────┬─────┬─────┐
│  1  │  3  │  2  │  4  │     ┌───────┬───────┐
├─────┼─────┼─────┼─────┤     │ 3.75  │ 5.25  │
│  5  │  6  │  7  │  8  │ →   ├───────┼───────┤
├─────┼─────┼─────┼─────┤     │ 1.50  │ 2.50  │
│  0  │  2  │  1  │  3  │     └───────┴───────┘
├─────┼─────┼─────┼─────┤
│  1  │  3  │  2  │  4  │
└─────┴─────┴─────┴─────┘

Vùng [0:2, 0:2] = [[1,3],[5,6]] → mean = 15/4 = 3.75
Vùng [0:2, 2:4] = [[2,4],[7,8]] → mean = 21/4 = 5.25
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Tính chất của average pooling:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tính đến mọi phần tử trong vùng gộp thay vì chỉ giữ một điểm.&lt;/li&gt;
  &lt;li&gt;Tạo dòng gradient mượt và phân bố đều hơn khi lan truyền ngược.&lt;/li&gt;
  &lt;li&gt;Bảo toàn tốt thông tin nền tổng thể.&lt;/li&gt;
  &lt;li&gt;Ít dùng ở các tầng giữa của mạng phân loại hơn max pooling, nhưng hữu ích trong phân đoạn hoặc ở dạng global pooling.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;so-sánh-max-pooling-và-average-pooling&quot;&gt;So sánh Max Pooling và Average Pooling&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Khía cạnh&lt;/th&gt;
      &lt;th&gt;Max Pooling&lt;/th&gt;
      &lt;th&gt;Average Pooling&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Thông tin giữ lại&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Đặc trưng nổi bật nhất&lt;/td&gt;
      &lt;td&gt;Cường độ trung bình toàn vùng&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Luồng gradient&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Thưa (chỉ đi qua phần tử cực đại)&lt;/td&gt;
      &lt;td&gt;Dày (phân bổ đều cho mọi phần tử)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Tác vụ phù hợp&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Phân loại ảnh (tìm đặc trưng phân biệt mạnh)&lt;/td&gt;
      &lt;td&gt;Phân đoạn, ước lượng độ sâu&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Vị trí thường dùng&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Các tầng sớm và giữa&lt;/td&gt;
      &lt;td&gt;Global average pooling ở cuối mạng&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Trong thực nghiệm, max pooling thường cho kết quả tốt hơn ở các tầng trích xuất đặc trưng cho bài toán phân loại vì các kích hoạt cực đại phản ánh rõ nhất sự hiện diện của đặc trưng phân biệt.&lt;/p&gt;

&lt;h3 id=&quot;global-average-pooling-gap&quot;&gt;Global Average Pooling (GAP)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Global Average Pooling&lt;/strong&gt; lấy trung bình toàn bộ mỗi bản đồ đặc trưng \(H \times W\) thành đúng một giá trị vô hướng:&lt;/p&gt;

\[\text{GAP}(X)_c = \frac{1}{H \times W} \sum_{i=1}^{H} \sum_{j=1}^{W} X_{i,j,c}\]

&lt;p&gt;&lt;strong&gt;Ví dụ trực quan:&lt;/strong&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Đầu vào (7×7×512):                    Đầu ra (512,):

┌─────────────────────────────┐
│  Bản đồ Đặc trưng 1 (7×7)   │ →  [0.42]
├─────────────────────────────┤
│  Bản đồ Đặc trưng 2 (7×7)   │ →  [0.78]
├─────────────────────────────┤
│         ...                 │      ...
├─────────────────────────────┤
│  Bản đồ Đặc trưng 512 (7×7) │ →  [0.31]
└─────────────────────────────┘

Mỗi bản đồ 7×7 → một số (trung bình của nó)
Kết quả: vectơ 512 chiều
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm của GAP&lt;/strong&gt; (được giới thiệu từ &lt;em&gt;Network in Network&lt;/em&gt;, 2014):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Loại bỏ các tầng liên kết đầy đủ lớn:&lt;/strong&gt; Giảm mạnh số lượng tham số và nguy cơ quá khớp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khái quát hóa tốt hơn:&lt;/strong&gt; Đóng vai trò như một dạng chính quy hóa về mặt cấu trúc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dễ diễn giải hơn:&lt;/strong&gt; Mỗi kênh bản đồ đặc trưng liên kết trực tiếp với mức độ hiện diện của đặc trưng tương ứng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Linh hoạt kích thước ảnh đầu vào:&lt;/strong&gt; Mạng có thể xử lý ảnh ở nhiều độ phân giải khác nhau khi suy luận.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Trước khi dùng GAP&lt;/strong&gt; (như ở AlexNet, VGG):&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Tầng Conv → Flatten (4096 giá trị) → FC (4096→4096) → FC (4096→1000)
Tham số ở các tầng FC: 4096×4096 + 4096×1000 ≈ 20 triệu
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Khi dùng GAP&lt;/strong&gt; (như ở ResNet và các CNN hiện đại):&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Tầng Conv → GAP (512 giá trị) → FC (512→1000)
Tham số: 512×1000 = 512,000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Chỉ riêng thay đổi này đã giúp giảm &lt;strong&gt;gần 40 lần&lt;/strong&gt; số tham số ở phần đầu ra.&lt;/p&gt;

&lt;h3 id=&quot;công-thức-kích-thước-đầu-ra-cho-tầng-gộp&quot;&gt;Công thức Kích thước Đầu ra cho Tầng Gộp&lt;/h3&gt;

&lt;p&gt;Công thức tính kích thước hoàn toàn tương tự tầng tích chập:&lt;/p&gt;

\[H_{out} = \left\lfloor \frac{H_{in} + 2p - k}{s} \right\rfloor + 1\]

&lt;p&gt;Với max pooling 2×2 tiêu chuẩn và stride 2 (\(k = 2, s = 2, p = 0\)):&lt;/p&gt;

\[H_{out} = \left\lfloor \frac{H_{in} - 2}{2} \right\rfloor + 1 = \frac{H_{in}}{2}\]

&lt;p&gt;(khi \(H_{in}\) là số chẵn), tức kích thước không gian giảm đi một nửa theo mỗi chiều.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-cài-đặt-mã&quot;&gt;3. Cài đặt Mã&lt;/h2&gt;

&lt;h3 id=&quot;cài-đặt-bằng-numpy&quot;&gt;Cài đặt bằng NumPy&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Phép max pooling.
    
    Args:
        input_array: Đầu vào dạng (H, W) hoặc (H, W, C)
        pool_size: Kích thước cửa sổ gộp
        stride: Bước nhảy của phép gộp
    
    Returns:
        Đầu ra đã gộp
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Xử lý trường hợp một kênh
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ndim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newaxis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tính kích thước đầu ra
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Trích vùng gộp và lấy max
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;region&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;region&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;avg_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Phép average pooling.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ndim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newaxis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;region&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;region&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;global_avg_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Global average pooling: trung bình mỗi kênh thành một giá trị.
    
    Args:
        input_array: Dạng (H, W, C)
    
    Returns:
        Vectơ dạng (C,)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== DEMO ==============
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Demo các Phép Gộp&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo đầu vào mẫu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đầu vào (4×4):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_data&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Max pooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_pooled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Max pooling (2×2, stride 2):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_pooled&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Average pooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_pooled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;avg_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Average pooling (2×2, stride 2):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_pooled&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Global average pooling (đa kênh)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;multi_channel&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;gap_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;global_avg_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;multi_channel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Global average pooling:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Shape đầu vào: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;multi_channel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Shape đầu ra: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gap_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  5 giá trị đầu: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gap_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;cài-đặt-bằng-pytorch&quot;&gt;Cài đặt bằng PyTorch&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# ============== CÁC TẦNG GỘP CÓ SẴN ==============
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Max pooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Average pooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Global average pooling (adaptive - hoạt động với mọi kích thước đầu vào)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;global_avg_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AdaptiveAvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Kích thước đầu ra 1×1
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Global max pooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;global_max_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AdaptiveMaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== DEMO ==============
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Ví dụ Gộp PyTorch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo đầu vào mẫu: batch 2, 64 kênh, 32×32
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape đầu vào: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Áp dụng các phép gộp khác nhau
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;avg_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;avg_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;gap_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;global_avg_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sau MaxPool2d(2,2): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# (2, 64, 16, 16)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sau AvgPool2d(2,2): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# (2, 64, 16, 16)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sau GAP: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gap_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                 &lt;span class=&quot;c1&quot;&gt;# (2, 64, 1, 1)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sau GAP + squeeze: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gap_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 64)
&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# ============== GỘP KÈM CHỈ SỐ (cho unpooling) ==============
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# MaxPool có thể trả về chỉ số cho các phép unpooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_pool_with_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;return_indices&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pooled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool_with_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Max pooling kèm chỉ số:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Shape đã gộp: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pooled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Shape chỉ số: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Unpooling (hữu ích cho mạng phân đoạn như U-Net)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;unpool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxUnpool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;unpooled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;unpool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pooled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Shape unpooled: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;unpooled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== SO SÁNH: POOLING so với CONV STRIDE ==============
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pooling so với Tích chập Stride&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Truyền thống: Conv → Pool
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_then_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 32×32 → 32×32
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                              &lt;span class=&quot;c1&quot;&gt;# 32×32 → 16×16
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Hiện đại: Conv stride (giảm mẫu học được)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;strided_conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 32×32 → 16×16
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;out_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_then_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;out_strided&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;strided_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đầu vào: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Conv + MaxPool: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Conv Stride: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_strided&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# So sánh tham số
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;conv_then_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;strided_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;strided_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tham số - Conv+Pool: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Conv Stride: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;strided_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Cùng số tham số, nhưng conv stride học được phép giảm mẫu!)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=ZjM_XQa5s6s&quot;&gt;Max Pooling in Convolutional Neural Networks explained&lt;/a&gt; — deeplizard, tiếng Anh. Giải thích trực quan cách max pooling giữ lại kích hoạt mạnh nhất trong từng cửa sổ.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa pooling trong một lượt lan truyền xuôi đầy đủ để thấy sự thay đổi kích thước.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, tiếng Anh. So sánh pooling truyền thống với tích chập có stride để giảm kích thước không gian.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01 Tầng Tích chập</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_Convolutional_Layers/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_Convolutional_Layers</id>
   <content type="html">&lt;p&gt;Mọi hệ thống nhận diện khuôn mặt, xe tự lái hay chẩn đoán ảnh X-quang đều bắt đầu từ một phép toán tưởng chừng đơn giản: trượt một ma trận số nhỏ qua bức ảnh và tính tổng tích từng phần tử. Thế nhưng đằng sau thao tác trượt ấy là cả một hệ thống toán học chặt chẽ về kích thước tensor, đa kênh, bước nhảy và độ đệm — nơi chỉ cần sai một đơn vị là toàn bộ đường ống kiến trúc bị lệch chiều.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nhánh-kiến-thức-của-tầng-tích-chập&quot;&gt;Kiến thức cần nhớ: Bốn nhánh kiến thức của Tầng Tích chập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đại số tensor và hình học kích thước&lt;/strong&gt;:
Hiểu chính xác mối quan hệ giữa kích thước đầu vào \((H, W, C_{\text{in}})\), kích thước nhân \(k\), đệm \(p\), bước nhảy \(s\) và giãn cách \(d\) để dự đoán ngay đầu ra mà không phải “chạy thử rồi sửa lỗi shape”.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trực giác xử lý tín hiệu và trường tiếp nhận&lt;/strong&gt;:
Nhìn thấy một bộ lọc \(3 \times 3\) thực chất là một bộ phát hiện mẫu cục bộ, và khi xếp chồng nhiều tầng, vùng ảnh gốc mà một neuron sâu “nhìn thấy” (receptive field) mở rộng nhanh chóng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Từ công thức toán đến cài đặt NumPy và PyTorch&lt;/strong&gt;:
Tự viết vòng lặp tích chập bằng NumPy giúp hiểu từng phép nhân cộng bên trong, trước khi chuyển sang &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; tối ưu hóa trên GPU bằng thuật toán &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;im2col&lt;/code&gt;/Winograd.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biến thể hiện đại và cạm bẫy kỹ thuật&lt;/strong&gt;:
Phân biệt tích chập chuẩn với tích chập \(1\times 1\), depthwise separable và dilated convolution, đồng thời tránh các lỗi kinh điển như nhầm thứ tự chiều NCHW/NHWC hay quên bias khi dùng BatchNorm.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-nhanh-một-tầng-tích-chập-4-tham-số-trên-giấy&quot;&gt;Giải thích: Tính nhanh một tầng tích chập 4 tham số trên giấy&lt;/h3&gt;

&lt;p&gt;Cho ảnh đầu vào kích thước \(H = 32, W = 32, C_{\text{in}} = 3\) đi qua tầng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=2, padding=1)&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Tính chiều cao và rộng đầu ra&lt;/strong&gt;:
\(H_{\text{out}} = \left\lfloor \frac{32 + 2(1) - 3}{2} \right\rfloor + 1 = \left\lfloor \frac{31}{2} \right\rfloor + 1 = 15 + 1 = 16\)
Tương tự \(W_{\text{out}} = 16\). Do đó tensor đầu ra có kích thước \(16 \times 16 \times 16\) (giảm một nửa mỗi chiều không gian).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Tính số tham số học được&lt;/strong&gt;:
Mỗi bộ lọc có kích thước \(3 \times 3 \times 3 = 27\) trọng số cộng \(1\) bias = \(28\) tham số. Với 16 bộ lọc: \(16 \times 28 = 448\) tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Ước lượng số phép nhân-cộng (MACs)&lt;/strong&gt;:
Tại mỗi vị trí trong \(16 \times 16 = 256\) điểm đầu ra, mỗi bộ lọc thực hiện \(27\) phép nhân-cộng \(\Rightarrow 256 \times 16 \times 27 = 110{,}592\) phép tính MACs.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Phần này trình bày chi tiết về các tầng tích chập (&lt;em&gt;convolutional layers&lt;/em&gt;) — thành phần cốt lõi của CNN — theo bốn mục chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Toán học Tích chập và Kích thước&lt;/strong&gt; — khái niệm nền tảng, tích chập đa kênh, công thức tính kích thước đầu ra và số lượng tham số&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trực giác Tích chập và Ví dụ&lt;/strong&gt; — phát hiện cạnh, hệ thống đặc trưng phân cấp và sự mở rộng của trường tiếp nhận (&lt;em&gt;receptive field&lt;/em&gt;)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt Tích chập&lt;/strong&gt; — cài đặt từ đầu bằng NumPy, sử dụng API PyTorch và xây dựng khối CNN hoàn chỉnh&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khái niệm Liên quan, Cạm bẫy và Bài báo&lt;/strong&gt; — mối liên hệ với các tầng khác, lỗi thường gặp, mẹo thực hành và các công trình nền tảng&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bạn nên đọc tuần tự từng mục trước khi chuyển sang phần tầng gộp (&lt;em&gt;pooling&lt;/em&gt;) và các kiến trúc CNN kinh điển.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Giới thiệu trực giác chung về phép tích chập trước khi đi sâu vào công thức và mã nguồn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, tiếng Anh. Mở rộng phép tích chập thành tầng nhiều kênh trong mạng CNN.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa trọn vẹn cách một tầng tích chập xử lý ảnh cụ thể.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-04 Khái niệm Liên quan, Cạm bẫy và Bài báo về Tích chập</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_04_Convolution_Pitfalls_and_Papers/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_04_Convolution_Pitfalls_and_Papers</id>
   <content type="html">&lt;p&gt;Viết ra một mạng CNN chạy được mà không báo lỗi chỉ mới đi được nửa chặng đường. Nửa chặng đường khó hơn nằm ở việc nhận diện những cạm bẫy âm thầm giết chết hiệu năng — như kích thước đặc trưng co về 0 ở tầng sâu, mất thông tin biên ảnh, hay chi phí tính toán phình to khi triển khai lên điện thoại — và biết chọn đúng biến thể tích chập (Depthwise Separable, Dilated) cho từng bài toán.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nhánh-kiến-thức-nâng-cao-về-tích-chập&quot;&gt;Kiến thức cần nhớ: Bốn nhánh kiến thức nâng cao về Tích chập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập Tách theo Chiều sâu (Depthwise Separable Convolution)&lt;/strong&gt;:
Tách phép lọc không gian (1 bộ lọc riêng cho từng kênh) khỏi phép trộn kênh (tích chập \(1\times 1\)), tạo nền tảng cho MobileNet và Xception chạy mượt trên thiết bị di động.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập Giãn (Dilated / Atrous Convolution)&lt;/strong&gt;:
Chèn các khoảng trống có độ giãn \(d\) giữa các trọng số nhân để mở rộng trường tiếp nhận theo cấp số nhân mà không cần giảm độ phân giải ảnh — cực kỳ quan trọng trong phân đoạn ảnh (DeepLab) và xử lý âm thanh (WaveNet).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hệ sinh thái tầng bổ trợ (Pooling, BatchNorm, Residual)&lt;/strong&gt;:
Tầng tích chập chỉ phát huy tối đa khi đặt đúng thứ tự với BatchNorm (loại bỏ bias dư thừa) và kết nối tắt (bảo toàn đường truyền gradient).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chẩn đoán các cạm bẫy kinh điển&lt;/strong&gt;:
Từ hiệu ứng lưới bàn cờ (&lt;em&gt;checkerboard artifacts&lt;/em&gt;) khi dùng transposed convolution, lỗi quên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;padding&lt;/code&gt; khiến ảnh co nhanh, cho tới nhầm lẫn giữa bất biến (invariance) và đồng biến (equivariance).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-tỷ-lệ-tiết-kiệm-của-depthwise-separable-và-trường-tiếp-nhận-của-dilated-conv&quot;&gt;Giải thích: Tính tay tỷ lệ tiết kiệm của Depthwise Separable và Trường tiếp nhận của Dilated Conv&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Depthwise Separable vs. Standard Conv&lt;/strong&gt; (với \(k = 3, C_{\text{in}} = 64, C_{\text{out}} = 128\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Standard Conv&lt;/strong&gt;: \(3 \times 3 \times 64 \times 128 = \mathbf{73{,}728}\) tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Depthwise&lt;/strong&gt; (lọc riêng từng kênh): \(3 \times 3 \times 64 = 576\) tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pointwise \(1 \times 1\)&lt;/strong&gt; (trộn 64 kênh ra 128 kênh): \(1 \times 1 \times 64 \times 128 = 8{,}192\) tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng Depthwise Separable&lt;/strong&gt;: \(576 + 8{,}192 = \mathbf{8{,}768}\) tham số — giảm &lt;strong&gt;8,4 lần&lt;/strong&gt; (xấp xỉ công thức lý thuyết \(\frac{1}{C_{\text{out}}} + \frac{1}{k^2} = \frac{1}{128} + \frac{1}{9} \approx 0{,}119\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Kích thước hiệu dụng của Dilated Convolution&lt;/strong&gt;:
Với nhân gốc \(k = 3\) và hệ số giãn \(d\), kích thước cửa sổ hiệu dụng là \(k_{\text{eff}} = k + (k - 1)(d - 1) = 1 + 2d\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(d = 1 \Rightarrow k_{\text{eff}} = 3 \times 3\) (tích chập thường).&lt;/li&gt;
  &lt;li&gt;\(d = 2 \Rightarrow k_{\text{eff}} = 5 \times 5\) (vẫn chỉ tốn &lt;strong&gt;9&lt;/strong&gt; trọng số thay vì 25!).&lt;/li&gt;
  &lt;li&gt;\(d = 4 \Rightarrow k_{\text{eff}} = 9 \times 9\) (vẫn chỉ tốn &lt;strong&gt;9&lt;/strong&gt; trọng số thay vì 81!).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-khái-niệm-liên-quan&quot;&gt;5. Khái niệm Liên quan&lt;/h2&gt;

&lt;h3 id=&quot;cnn-so-với-mạng-neuron-liên-kết-đầy-đủ&quot;&gt;CNN so với Mạng Neuron Liên kết Đầy đủ&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv7.jpg&quot; alt=&quot;CNN vs Regular Neural Network&quot; /&gt;
&lt;em&gt;So sánh CNN và mạng neuron thông thường trên dữ liệu ảnh: CNN bảo toàn cấu trúc không gian, chia sẻ trọng số bộ lọc để giảm mạnh số tham số và nhận diện đặc trưng không phụ thuộc vị trí. Nguồn: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Khía cạnh&lt;/th&gt;
      &lt;th&gt;Liên kết đầy đủ&lt;/th&gt;
      &lt;th&gt;Tích chập&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Kết nối&lt;/td&gt;
      &lt;td&gt;Mọi đầu vào với mọi đầu ra&lt;/td&gt;
      &lt;td&gt;Cục bộ (theo kích thước nhân)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Chia sẻ tham số&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Dùng chung bộ lọc ở mọi vị trí&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Tham số (32×32×3 → 64)&lt;/td&gt;
      &lt;td&gt;196,672&lt;/td&gt;
      &lt;td&gt;1,792&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Bất biến tịnh tiến&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Có&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Bảo toàn cấu trúc không gian&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Có&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;tầng-liên-kết-đầy-đủ&quot;&gt;Tầng Liên kết Đầy đủ&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Nối mọi neuron đầu vào với mọi neuron đầu ra.&lt;/li&gt;
  &lt;li&gt;Không có giả định về cấu trúc không gian.&lt;/li&gt;
  &lt;li&gt;Thường đặt sau các tầng tích chập để thực hiện bước phân loại cuối cùng.&lt;/li&gt;
  &lt;li&gt;Số tham số tăng nhanh theo kích thước đầu vào.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tầng-gộp-pooling&quot;&gt;Tầng Gộp (&lt;em&gt;Pooling&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Giảm kích thước không gian của bản đồ đặc trưng (&lt;em&gt;downsampling&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Tăng độ ổn định trước các dịch chuyển nhỏ.&lt;/li&gt;
  &lt;li&gt;Giảm chi phí tính toán và bộ nhớ cho các tầng phía sau.&lt;/li&gt;
  &lt;li&gt;Không chứa tham số học được.&lt;/li&gt;
  &lt;li&gt;Các dạng phổ biến: Max pooling, Average pooling.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;chuẩn-hóa-batch-batch-normalization&quot;&gt;Chuẩn hóa Batch (&lt;em&gt;Batch Normalization&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Chuẩn hóa giá trị kích hoạt về trung bình 0 và phương sai 1 theo từng mini-batch.&lt;/li&gt;
  &lt;li&gt;Giúp quá trình huấn luyện ổn định hơn.&lt;/li&gt;
  &lt;li&gt;Thường đặt sau tầng tích chập và trước hàm kích hoạt.&lt;/li&gt;
  &lt;li&gt;Cho phép sử dụng tốc độ học cao hơn và hội tụ nhanh hơn.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;kết-nối-dư-residual--skip-connections&quot;&gt;Kết nối Dư (&lt;em&gt;Residual / Skip Connections&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Tạo đường dẫn trực tiếp cho tín hiệu và gradient đi qua nhiều tầng.&lt;/li&gt;
  &lt;li&gt;Cho phép huấn luyện hiệu quả các mạng rất sâu (trên 100 tầng).&lt;/li&gt;
  &lt;li&gt;Biểu thức đầu ra: \(\mathbf{y} = F(\mathbf{x}) + \mathbf{x}\).&lt;/li&gt;
  &lt;li&gt;Đóng góp cốt lõi của kiến trúc ResNet (2015).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tích-chập-tách-theo-chiều-sâu-depthwise-separable-convolutions&quot;&gt;Tích chập Tách theo Chiều sâu (&lt;em&gt;Depthwise Separable Convolutions&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Tách phép tích chập chuẩn thành hai bước: &lt;em&gt;depthwise&lt;/em&gt; và &lt;em&gt;pointwise&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Giảm đáng kể số tham số và số phép tính.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Depthwise&lt;/em&gt;: áp dụng một bộ lọc riêng cho từng kênh đầu vào.&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;Pointwise&lt;/em&gt;: dùng tích chập 1×1 để kết hợp thông tin giữa các kênh.&lt;/li&gt;
  &lt;li&gt;Được sử dụng rộng rãi trong MobileNet và EfficientNet cho thiết bị di động.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tích-chập-giãn-dilated--atrous-convolutions&quot;&gt;Tích chập Giãn (&lt;em&gt;Dilated / Atrous Convolutions&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Chèn khoảng trống giữa các phần tử của nhân tích chập.&lt;/li&gt;
  &lt;li&gt;Mở rộng trường tiếp nhận mà không tăng số lượng tham số.&lt;/li&gt;
  &lt;li&gt;Thường dùng trong bài toán phân đoạn ngữ nghĩa (như DeepLab).&lt;/li&gt;
  &lt;li&gt;Với tỷ lệ giãn \(d\), các phần tử của nhân cách nhau \(d\) điểm ảnh.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các Bài báo Nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf&quot;&gt;“Gradient-Based Learning Applied to Document Recognition” (1998)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Yann LeCun, Léon Bottou, Yoshua Bengio, Patrick Haffner&lt;br /&gt;
Giới thiệu LeNet-5 — mạng CNN đầu tiên thành công trong bài toán nhận diện chữ số viết tay. Bài báo chứng minh các tầng tích chập dùng chung trọng số có thể tự học đặc trưng phân cấp từ điểm ảnh thô và định hình khuôn mẫu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv → pool → conv → pool → FC&lt;/code&gt; được sử dụng suốt gần hai thập kỷ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks&quot;&gt;“ImageNet Classification with Deep Convolutional Neural Networks” (2012)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Alex Krizhevsky, Ilya Sutskever, Geoffrey E. Hinton&lt;br /&gt;
AlexNet giành chiến thắng tại ImageNet 2012 với cách biệt lớn (lỗi top-5 đạt 15,3% so với 26,2% của đội xếp thứ hai), khẳng định khả năng mở rộng của CNN sâu trên bài toán thị giác quy mô lớn. Công trình cũng đưa ReLU, dropout và huấn luyện trên GPU vào dòng chính của học sâu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.1556&quot;&gt;“Very Deep Convolutional Networks for Large-Scale Image Recognition” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Karen Simonyan, Andrew Zisserman&lt;br /&gt;
VGGNet nhấn mạnh vai trò của độ sâu kiến trúc và chỉ sử dụng các bộ lọc nhỏ 3×3 xếp chồng liên tiếp để đạt trường tiếp nhận lớn. Thiết kế đồng nhất, dễ lặp lại này trở thành nền tảng tham chiếu cho nhiều kiến trúc về sau.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.03385&quot;&gt;“Deep Residual Learning for Image Recognition” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun&lt;br /&gt;
Đề xuất kết nối tắt (&lt;em&gt;skip connections&lt;/em&gt;) giải quyết hiện tượng suy giảm hiệu năng khi mạng quá sâu, cho phép huấn luyện thành công mạng hơn 150 tầng. ResNet giành vị trí dẫn đầu tại ImageNet 2015 và nguyên lý học phần dư của nó hiện được dùng rộng rãi trong cả Transformer lẫn mô hình khuếch tán.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1704.04861&quot;&gt;“MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Andrew G. Howard và cộng sự&lt;br /&gt;
Giới thiệu tích chập tách theo chiều sâu giúp giảm 8–9 lần khối lượng tính toán mà vẫn giữ độ chính xác tốt, mở đường cho việc triển khai CNN trên điện thoại và thiết bị nhúng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.00567&quot;&gt;“Rethinking the Inception Architecture for Computer Vision” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Christian Szegedy và cộng sự&lt;br /&gt;
Inception-v3 đề xuất phân rã nhân tích chập (dùng cặp \(1 \times n\) và \(n \times 1\) thay cho \(n \times n\)) cùng các nhánh phân loại phụ, cho thấy thiết kế kiến trúc cẩn thận có thể cải thiện đồng thời độ chính xác và chi phí tính toán.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-cạm-bẫy-thường-gặp-và-mẹo-thực-hành&quot;&gt;7. Cạm bẫy Thường gặp và Mẹo Thực hành&lt;/h2&gt;

&lt;h3 id=&quot;cạm-bẫy-1-không-dùng-padding&quot;&gt;Cạm bẫy 1: Không Dùng Padding&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Vấn đề:&lt;/strong&gt; Kích thước bản đồ đặc trưng thu nhỏ dần sau mỗi tầng và thông tin ở vùng biên bị mất nhanh chóng.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Không padding: 32×32 → 30×30 → 28×28 → ... (co nhanh!)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Không padding
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Có padding: 32×32 → 32×32 → 32×32 (giữ kích thước)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Đệm &quot;same&quot;
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Cách khắc phục:&lt;/strong&gt; Với nhân kích thước lẻ và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=1&lt;/code&gt;, đặt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;padding = (kernel_size - 1) // 2&lt;/code&gt; để giữ nguyên kích thước không gian.&lt;/p&gt;

&lt;h3 id=&quot;cạm-bẫy-2-nhầm-thứ-tự-chiều-kênh&quot;&gt;Cạm bẫy 2: Nhầm Thứ tự Chiều Kênh&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Vấn đề:&lt;/strong&gt; Các framework sử dụng quy ước thứ tự chiều tensor khác nhau.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# PyTorch: (N, C, H, W) - Kênh trước
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_pytorch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# TensorFlow/Keras: (N, H, W, C) - Kênh sau
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_tensorflow&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Chuyển đổi giữa chúng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_tf_to_pytorch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_tensorflow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;permute&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Nếu dùng torch
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;cạm-bẫy-3-dùng-nhân-quá-lớn-ở-các-tầng-đầu&quot;&gt;Cạm bẫy 3: Dùng Nhân Quá Lớn ở Các Tầng Đầu&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Vấn đề:&lt;/strong&gt; Nhân kích thước lớn tốn nhiều tham số trong khi chỉ có một lớp phi tuyến.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Kém hiệu quả hơn (hiểu biết của VGG)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 7×7 = 49 params/kênh
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tốt hơn: Xếp chồng kernel nhỏ
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Ba 3×3 = 27 params/kênh, cùng trường tiếp nhận 7×7, gấp 3 phi tuyến
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;mẹo-1-dùng-tích-chập-11-để-điều-chỉnh-số-kênh&quot;&gt;Mẹo 1: Dùng Tích chập 1×1 để Điều chỉnh Số Kênh&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Giảm kênh (nút thắt / bottleneck)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bottleneck&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 512 → 64 kênh với tính toán tối thiểu
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tăng kênh
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expand&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Trộn thông tin kênh mà không thao tác không gian
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;mẹo-2-dùng-tích-chập-có-stride-thay-cho-pooling&quot;&gt;Mẹo 2: Dùng Tích chập có Stride thay cho Pooling&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Truyền thống: Conv → Pool
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Hiện đại: Conv stride (giảm mẫu học được)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;strided_conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Cùng kích thước đầu ra, nhưng giảm mẫu được học!
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;mẹo-3-khởi-tạo-trọng-số-phù-hợp&quot;&gt;Mẹo 3: Khởi tạo Trọng số Phù hợp&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Khởi tạo Kaiming cho mạng ReLU
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;init_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;isinstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;kaiming_normal_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mode&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;fan_out&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nonlinearity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;constant_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;isinstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;constant_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;constant_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;apply&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;mẹo-4-tính-trường-tiếp-nhận&quot;&gt;Mẹo 4: Tính Trường Tiếp nhận&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;receptive_field_1d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Tính trường tiếp nhận cho một chồng tầng conv.
    
    Mỗi tầng là (kernel_size, stride)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Bắt đầu với một điểm ảnh
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;stride_product&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride_product&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;stride_product&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ: 3 tầng conv (k=3, s=1) rồi pool (k=2, s=2)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trường tiếp nhận: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;receptive_field_1d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 8
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-tóm-tắt-các-điểm-chính&quot;&gt;8. Tóm tắt các Điểm chính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập và Tương quan chéo:&lt;/strong&gt; Học sâu thường cài đặt tương quan chéo nhưng gọi chung là tích chập; việc có lật nhân hay không không làm thay đổi khả năng học vì trọng số được tối ưu từ dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kết nối Cục bộ và Chia sẻ Trọng số:&lt;/strong&gt; Hai cơ chế này giúp CNN tiết kiệm tham số hơn rất nhiều so với mạng liên kết đầy đủ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học Đặc trưng Phân cấp:&lt;/strong&gt; CNN tự động xây dựng biểu diễn từ cạnh, kết cấu đến bộ phận và đối tượng hoàn chỉnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Công thức Kích thước Đầu ra:&lt;/strong&gt; \(n_{out} = \lfloor(n_{in} + 2p - k)/s\rfloor + 1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xếp chồng Bộ lọc Nhỏ:&lt;/strong&gt; Dùng nhiều tầng 3×3 liên tiếp thường hiệu quả hơn một tầng nhân lớn (ít tham số hơn và nhiều lớp phi tuyến hơn).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trường Tiếp nhận:&lt;/strong&gt; Mở rộng dần theo độ sâu, là đại lượng quan trọng cần theo dõi khi thiết kế kiến trúc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mẫu thiết kế phổ biến:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Chuỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv → BatchNorm → ReLU&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Kết nối dư cho các mạng sâu&lt;/li&gt;
      &lt;li&gt;Global average pooling thay cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;flatten + FC&lt;/code&gt; nhiều tham số&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Tầng tích chập là thành phần trung tâm của thị giác máy tính trong học sâu, phục vụ từ phân loại ảnh, phát hiện đối tượng cho đến các mô hình sinh ảnh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tiếp theo:&lt;/strong&gt; Tầng gộp và các kiến trúc CNN kinh điển (LeNet, AlexNet, VGG, ResNet).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, tiếng Anh. Phân tích rõ các lỗi kích thước dễ gặp khi kết hợp số kênh, padding và stride.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, tiếng Anh. Cập nhật góc nhìn hiện đại về các lựa chọn thiết kế và cạm bẫy trong CNN.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=RYth6EbBUqM&quot;&gt;C4W2L04 Why ResNets Work&lt;/a&gt; — DeepLearningAI, tiếng Anh. Giải thích nguyên nhân mạng tích chập thuần bị suy giảm hiệu năng khi tăng độ sâu và cách ResNet khắc phục.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-03 Cài đặt Tích chập</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_03_Convolution_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_03_Convolution_Implementation</id>
   <content type="html">&lt;p&gt;Một dòng code &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d(3, 64, kernel_size=3, padding=1)&lt;/code&gt; trong PyTorch chạy chỉ trong vài phần nghìn giây, nhưng chính sự tiện lợi ấy lại khiến nhiều lập trình viên gặp khó khăn khi phải debug lỗi lệch kích thước tensor, tối ưu tốc độ suy luận, hay viết lại tầng tích chập trên thiết bị nhúng không có PyTorch. Muốn làm chủ CNN, ta cần nhìn xuyên qua lớp vỏ API bằng cách tự cài đặt từ đầu bằng NumPy rồi mới đối chiếu với PyTorch.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-lớp-kỹ-thuật-khi-triển-khai-tầng-tích-chập&quot;&gt;Kiến thức cần nhớ: Ba lớp kỹ thuật khi triển khai Tầng Tích chập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tư duy chỉ số mảng và Padding tường minh (NumPy)&lt;/strong&gt;:
Tự dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.pad&lt;/code&gt; và cắt lát &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;image[i*s : i*s+kh, j*s : j*s+kw]&lt;/code&gt; giúp bạn kiểm soát tuyệt đối từng tọa độ, hiểu rõ vì sao &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output_shape&lt;/code&gt; lấy phần nguyên sàn (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;//&lt;/code&gt;) khi chia cho stride.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy ước chiều tensor (NCHW vs. NHWC)&lt;/strong&gt;:
PyTorch dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(Batch, Channels, Height, Width)&lt;/code&gt; — gọi là NCHW — tối ưu cho nhân cuDNN; trong khi ảnh đọc từ NumPy/OpenCV thường là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(Height, Width, Channels)&lt;/code&gt;. Quên chuyển trục là nguyên nhân số 1 gây lỗi im lặng hoặc crash.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Từ tích chập đơn lẻ đến Khối CNN tiêu chuẩn (Conv Block)&lt;/strong&gt;:
Trong thực tế, ít khi dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d&lt;/code&gt; đứng một mình; đơn vị xây dựng chuẩn là cụm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d(bias=False) -&amp;gt; BatchNorm2d -&amp;gt; ReLU&lt;/code&gt; (hoặc SiLU/GELU) kết hợp với tích chập \(1\times 1\) để nén hoặc mở rộng số kênh.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-lần-theo-chỉ-số-cắt-lát-slicing-trong-vòng-lặp-numpy&quot;&gt;Giải thích: Lần theo chỉ số cắt lát (slicing) trong vòng lặp NumPy&lt;/h3&gt;

&lt;p&gt;Giả sử ảnh đã pad có kích thước \(5 \times 5\), nhân \(K\) kích thước \(3 \times 3\), bước nhảy \(s = 2\). Khi đó \(H_{\text{out}} = \lfloor (5 - 3)/2 \rfloor + 1 = 2\). Với mỗi cặp chỉ số đầu ra \((i, j) \in \{0, 1\} \times \{0, 1\}\), vùng ảnh được cắt lát là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;padded[i*2 : i*2+3, j*2 : j*2+3]&lt;/code&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Chỉ số đầu ra \((i, j)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Phạm vi hàng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;r_start : r_end&lt;/code&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Phạm vi cột &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;c_start : c_end&lt;/code&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Kích thước lát cắt&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\((0, 0)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0 : 3&lt;/code&gt; (hàng 0, 1, 2)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0 : 3&lt;/code&gt; (cột 0, 1, 2)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(3 \times 3\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\((0, 1)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0 : 3&lt;/code&gt; (hàng 0, 1, 2)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2 : 5&lt;/code&gt; (cột 2, 3, 4)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(3 \times 3\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\((1, 0)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2 : 5&lt;/code&gt; (hàng 2, 3, 4)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0 : 3&lt;/code&gt; (cột 0, 1, 2)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(3 \times 3\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\((1, 1)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2 : 5&lt;/code&gt; (hàng 2, 3, 4)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2 : 5&lt;/code&gt; (cột 2, 3, 4)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(3 \times 3\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chú ý rằng chỉ số kết thúc lớn nhất là \(1\times 2 + 3 = 5\), vừa khít chiều dài mảng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt;, không bao giờ vượt biên (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;IndexError&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Phần này hướng dẫn cài đặt các tầng tích chập theo hai mức độ:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt bằng NumPy&lt;/strong&gt; — viết phép tích chập 2D từ đầu kèm các ví dụ minh họa&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;PyTorch và Khối CNN&lt;/strong&gt; — sử dụng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt;, xây dựng khối CNN chuẩn và chạy một bước huấn luyện mẫu&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pDdP0TFzsoQ&quot;&gt;PyTorch Tutorial 14 - Convolutional Neural Network (CNN)&lt;/a&gt; — Patrick Loeber, tiếng Anh. Hướng dẫn sử dụng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; tương ứng với phần PyTorch của bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, tiếng Anh. Giải thích các quy ước về kích thước tensor khi gọi tầng tích chập.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa trực tiếp phép trượt và tính tổng mà phiên bản NumPy đang cài đặt.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-03-02 Tích chập PyTorch và Khối CNN</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_03_02_Convolution_PyTorch/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_03_02_Convolution_PyTorch</id>
   <content type="html">&lt;p&gt;Khi chuyển từ công thức giấy sang PyTorch, sức mạnh thực sự nằm ở khả năng lắp ghép các mô-đun &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Module&lt;/code&gt; thành những khối xử lý thị giác chuẩn mực — từ tích chập cơ bản, giảm mẫu bằng stride, cho đến phép tích chập \(1 \times 1\) đầy quyền năng giúp trộn thông tin liên kênh. Hiểu rõ từng tham số của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; giúp bạn thiết kế kiến trúc sạch, gọn và tránh lãng phí bộ nhớ GPU.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-kỹ-năng-thiết-yếu-với-nnconv2d-trong-pytorch&quot;&gt;Kiến thức cần nhớ: Bốn kỹ năng thiết yếu với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; trong PyTorch&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn hóa kích thước tensor 4D &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, C, H, W)&lt;/code&gt;&lt;/strong&gt;:
PyTorch luôn kỳ vọng có chiều batch \(N\) ở đầu. Ngay cả khi suy luận trên một ảnh duy nhất, ta vẫn phải thêm chiều batch bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x.unsqueeze(0)&lt;/code&gt; để có dạng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(1, C, H, W)&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập \(1 \times 1\) (Pointwise Convolution) như một MLP tại mỗi pixel&lt;/strong&gt;:
Không thay đổi chiều không gian \((H, W)\), nhưng phép tích chập \(1 \times 1\) tạo ra tổ hợp tuyến tính giữa các kênh tại từng tọa độ — công cụ chủ lực để giảm chiều kênh (bottleneck) trong ResNet và MobileNet.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giảm mẫu học được bằng Stride vs. Pooling&lt;/strong&gt;:
Dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=2&lt;/code&gt; trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d&lt;/code&gt; cho phép mạng tự học cách hạ độ phân giải thay vì cố định lấy max/trung bình, đồng thời giúp kiến trúc gọn gàng hơn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra trọng số đã học (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv.weight.shape&lt;/code&gt;)&lt;/strong&gt;:
Ma trận trọng số trong PyTorch luôn có shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(out_channels, in_channels // groups, kH, kW)&lt;/code&gt; — nắm chắc cấu trúc này giúp bạn trực quan hóa bộ lọc và thiết lập tích chập nhóm (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;groups=in_channels&lt;/code&gt; cho depthwise convolution).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-lợi-ích-tiết-kiệm-phép-tính-của-tầng-cổ-chai-bottleneck-1-times-1&quot;&gt;Giải thích: Tính tay lợi ích tiết kiệm phép tính của tầng cổ chai (Bottleneck \(1 \times 1\))&lt;/h3&gt;

&lt;p&gt;Giả sử bản đồ đặc trưng có kích thước \(28 \times 28\) với \(C_{\text{in}} = 256\) kênh và ta muốn ra \(C_{\text{out}} = 256\) kênh bằng bộ lọc \(3 \times 3\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cách trực tiếp&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d(256, 256, kernel_size=3, padding=1)&lt;/code&gt;):
Số tham số trọng số = \(3 \times 3 \times 256 \times 256 = \mathbf{589{,}824}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cách dùng cổ chai \(1 \times 1\) kiểu ResNet&lt;/strong&gt; (nén \(256 \to 64\) bằng \(1\times 1\), lọc \(3\times 3\) trên 64 kênh, rồi mở rộng \(64 \to 256\) bằng \(1\times 1\)):
    &lt;ol&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d(256, 64, 1)&lt;/code&gt;: \(1 \times 1 \times 256 \times 64 = 16{,}384\) tham số.&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d(64, 64, 3, padding=1)&lt;/code&gt;: \(3 \times 3 \times 64 \times 64 = 36{,}864\) tham số.&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d(64, 256, 1)&lt;/code&gt;: \(1 \times 1 \times 64 \times 256 = 16{,}384\) tham số.
        &lt;ul&gt;
          &lt;li&gt;&lt;strong&gt;Tổng cộng&lt;/strong&gt;: \(16{,}384 + 36{,}864 + 16{,}384 = \mathbf{69{,}632}\) tham số!&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chỉ nhờ kẹp thêm hai tầng tích chập \(1 \times 1\), số tham số và chi phí tính toán giảm tới &lt;strong&gt;8,5 lần&lt;/strong&gt; mà mô hình còn thêm được hai hàm kích hoạt phi tuyến ở giữa!&lt;/p&gt;

&lt;h3 id=&quot;cài-đặt-bằng-pytorch&quot;&gt;Cài đặt bằng PyTorch&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvolutionExplained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Một tầng tích chập kèm giải thích chi tiết.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                 &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tạo tầng tích chập
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Lượt xuôi kèm theo dõi shape.
        
        Args:
            x: Tensor đầu vào dạng (batch, channels, height, width)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_in&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính kích thước đầu ra
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_in&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W_in&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Áp dụng tích chập
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Kiểm tra shape
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đếm và giải thích tham số.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Shape trọng số: (out_channels, in_channels, kernel_size, kernel_size)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;weight_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;bias_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias_params&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Phân rã tham số:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Trọng số: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; bộ lọc × &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Bias: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tổng: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== DEMO ==============
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Ví dụ Tích chập PyTorch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ 1: Tích chập cơ bản
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--- Ví dụ 1: Ảnh RGB thành 64 Bản đồ Đặc trưng ---&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv_layer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvolutionExplained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# Đầu vào RGB
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# 64 bộ lọc học được
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# Bộ lọc 3×3
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# Đệm &quot;same&quot;
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Đầu vào: batch 8 ảnh RGB, 32×32 điểm ảnh
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape đầu vào:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape đầu ra: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Ví dụ 2: Giảm mẫu bằng tích chập có stride
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--- Ví dụ 2: Tích chập Stride để Giảm mẫu ---&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv_downsample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvolutionExplained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# Stride 2 giảm một nửa kích thước không gian
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;output2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_downsample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape đầu vào:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape đầu ra: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 32×32 → 16×16
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_downsample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Ví dụ 3: Tích chập 1×1 để thao tác kênh
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--- Ví dụ 3: Tích chập 1×1 (Giảm kênh) ---&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv_1x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvolutionExplained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Giảm kênh mạnh
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;output3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_1x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape đầu vào:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape đầu ra: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cùng không gian, ít kênh hơn
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_1x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Ví dụ 4: Quan sát bộ lọc đã học
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--- Ví dụ 4: Kiểm tra Trọng số Bộ lọc ---&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Truy cập trọng số đã học
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;conv_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape tensor trọng số: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; bộ lọc kích thước &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
      &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Quan sát bộ lọc đầu tiên (sẽ hiển thị bằng matplotlib)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;first_filter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Shape: (3, 3, 3) = (in_channels, H, W)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shape bộ lọc đầu: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;first_filter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Giá trị bộ lọc (kênh 0):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;first_filter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;khối-cnn-hoàn-chỉnh-theo-cấu-trúc-chuẩn&quot;&gt;Khối CNN Hoàn chỉnh theo Cấu trúc Chuẩn&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Khối tích chập chuẩn: Conv → BatchNorm → ReLU
    
    Mẫu này dùng trong hầu hết CNN hiện đại.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tích chập (không bias khi dùng BatchNorm)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Chuẩn hóa batch ổn định huấn luyện
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Kích hoạt ReLU
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResidualBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Khối dư với kết nối bỏ qua (từ ResNet).
    
    Hiểu biết then chốt: Học phần dư F(x) = H(x) - x thay vì H(x) trực tiếp.
    Đầu ra: y = F(x) + x
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Lưu đầu vào cho kết nối bỏ qua
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Kết nối bỏ qua!
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleCNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Một CNN đơn giản nhưng hiệu quả cho phân loại ảnh.
    
    Kiến trúc: 
    Input → ConvBlocks (kèm pooling) → Global Average Pool → Classifier
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Các tầng trích xuất đặc trưng
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Khối 1: 32×32×3 → 16×16×32
&lt;/span&gt;            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Khối 2: 16×16×32 → 8×8×64
&lt;/span&gt;            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Khối 3: 8×8×64 → 4×4×128
&lt;/span&gt;            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Global average pooling: 4×4×128 → 128
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;global_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AdaptiveAvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Bộ phân loại
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Trích xuất đặc trưng
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gộp toàn cục
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;global_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Làm phẳng
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Phân loại
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== VÍ DỤ HUẤN LUYỆN ==============
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Một bước huấn luyện với lượt xuôi và ngược.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Lượt xuôi
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Lượt ngược
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tính độ chính xác
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Tạo mô hình và các thành phần huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleCNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CrossEntropyLoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Đếm tham số
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;trainable_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Thống kê Mô hình:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tổng tham số: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tham số huấn luyện được: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainable_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Mô phỏng một bước huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dummy_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Batch 32 ảnh kiểu CIFAR
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dummy_labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dummy_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dummy_labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Bước huấn luyện - Loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Accuracy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pDdP0TFzsoQ&quot;&gt;PyTorch Tutorial 14 - Convolutional Neural Network (CNN)&lt;/a&gt; — Patrick Loeber, tiếng Anh. Hướng dẫn sử dụng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; và ghép thành một mạng CNN hoàn chỉnh bằng PyTorch.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, tiếng Anh. Minh họa cách các khối tích chập được xếp chồng trong các kiến trúc CNN thực tế.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, tiếng Anh. Giải thích quy ước chiều tensor &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, C, H, W)&lt;/code&gt; mà &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; sử dụng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-03-01 Cài đặt Tích chập bằng NumPy</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_03_01_Convolution_NumPy/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_03_01_Convolution_NumPy</id>
   <content type="html">&lt;p&gt;Nhiều sinh viên học Deep Learning có thể gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; rất thành thạo, nhưng khi phỏng vấn kỹ thuật yêu cầu &lt;em&gt;“Hãy viết hàm tích chập 2D thuần NumPy không dùng thư viện DL”&lt;/em&gt; lại lúng túng ở bước xử lý biên và cộng dồn đa kênh. Tự tay cài đặt phép tích chập bằng NumPy giống như việc tự tháo lắp một động cơ: chỉ cần làm một lần, bạn sẽ hiểu vĩnh viễn điều gì đang diễn ra bên dưới GPU.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-mảnh-ghép-của-hàm-tích-chập-viết-bằng-numpy&quot;&gt;Kiến thức cần nhớ: Bốn mảnh ghép của hàm Tích chập viết bằng NumPy&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Xử lý đệm biên bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.pad&lt;/code&gt;&lt;/strong&gt;:
Chỉ đệm trên trục không gian \((H, W)\), tuyệt đối không đệm nhầm sang trục batch \(N\) hay trục kênh \(C\) (nếu dùng mảng 4D).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vòng lặp trượt và phép nhân-cộng điểm ảnh (Element-wise Multiply &amp;amp; Sum)&lt;/strong&gt;:
Với mỗi vị trí \((i, j)\), ta cắt cửa sổ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;region&lt;/code&gt; kích thước bằng đúng kernel rồi tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.sum(region * kernel)&lt;/code&gt; — đây chính là tương quan chéo (cross-correlation).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đảo ngược nhân cho tích chập toán học thuần túy&lt;/strong&gt;:
Nếu cần tích chập đúng nghĩa xử lý tín hiệu, chỉ cần lật kernel theo cả hai trục bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kernel[::-1, ::-1]&lt;/code&gt; trước khi trượt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vector hóa bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;im2col&lt;/code&gt; (Cầu nối tới hiệu năng thực tế)&lt;/strong&gt;:
Vòng lặp Python chạy chậm hàng nghìn lần; các thư viện như cuDNN trải phẳng từng cửa sổ thành các cột của một ma trận lớn rồi dùng phép nhân ma trận siêu tối ưu (GEMM) để tính toàn bộ bản đồ đặc trưng trong một lượt.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-bước-im2col-để-biến-tích-chập-thành-một-phép-nhân-ma-trận&quot;&gt;Giải thích: Tính tay bước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;im2col&lt;/code&gt; để biến tích chập thành một phép nhân ma trận&lt;/h3&gt;

&lt;p&gt;Xét ảnh đơn kênh \(3 \times 3\) và bộ lọc \(2 \times 2\) (\(P=0, S=1\)), đầu ra sẽ có kích thước \(2 \times 2\) (tức 4 cửa sổ):&lt;/p&gt;

\[I = \begin{bmatrix} 1 &amp;amp; 2 &amp;amp; 0 \\ 0 &amp;amp; 1 &amp;amp; 3 \\ 2 &amp;amp; 1 &amp;amp; 1 \end{bmatrix}, \qquad K = \begin{bmatrix} 1 &amp;amp; 0 \\ -1 &amp;amp; 2 \end{bmatrix}\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Trải phẳng từng cửa sổ \(2 \times 2\) thành 4 hàng của ma trận &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X_col&lt;/code&gt; (kích thước \(4 \times 4\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Cửa sổ \((0,0)\): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1, 2, 0, 1]&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Cửa sổ \((0,1)\): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[2, 0, 1, 3]&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Cửa sổ \((1,0)\): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0, 1, 2, 1]&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Cửa sổ \((1,1)\): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1, 3, 1, 1]&lt;/code&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Trải phẳng kernel \(K\) thành vector cột &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;W_col&lt;/code&gt; (kích thước \(4 \times 1\))&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1, 0, -1, 2]^T&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Một phép nhân ma trận duy nhất &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;X_col @ W_col&lt;/code&gt;&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Hàng 0: \(1(1) + 2(0) + 0(-1) + 1(2) = 3\)&lt;/li&gt;
      &lt;li&gt;Hàng 1: \(2(1) + 0(0) + 1(-1) + 3(2) = 7\)&lt;/li&gt;
      &lt;li&gt;Hàng 2: \(0(1) + 1(0) + 2(-1) + 1(2) = 0\)&lt;/li&gt;
      &lt;li&gt;Hàng 3: \(1(1) + 3(0) + 1(-1) + 1(2) = 2\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 4 — Định hình lại (reshape) về \(2 \times 2\)&lt;/strong&gt;: \(\begin{bmatrix} 3 &amp;amp; 7 \\ 0 &amp;amp; 2 \end{bmatrix}\). Đây chính là bí mật giúp GPU chạy CNN nhanh gấp hàng nghìn lần vòng lặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; thuần.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-cài-đặt-mã&quot;&gt;4. Cài đặt Mã&lt;/h2&gt;

&lt;h3 id=&quot;cài-đặt-tích-chập-bằng-numpy-từ-đầu&quot;&gt;Cài đặt Tích chập bằng NumPy từ Đầu&lt;/h3&gt;

&lt;p&gt;Tự viết lại phép tích chập 2D ở mức thấp bằng NumPy giúp nắm chắc cách đánh chỉ số, thêm đệm (&lt;em&gt;padding&lt;/em&gt;) và bước nhảy (&lt;em&gt;stride&lt;/em&gt;):&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Cài đặt tích chập 2D ngây thơ (tương quan chéo).
    
    Args:
        image: Mảng đầu vào dạng (H, W) cho một kênh
               hoặc (H, W, C) cho đa kênh
        kernel: Mảng bộ lọc dạng (k, k) cho một kênh
                hoặc (k, k, C) cho đa kênh
        stride: Kích thước bước khi trượt nhân
        padding: Đệm zero thêm vào biên đầu vào
    
    Returns:
        output: Bản đồ đặc trưng sau tích chập
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Xử lý trường hợp một kênh
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ndim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newaxis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kernel&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newaxis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Thêm đệm
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                       &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;mode&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;constant&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;constant_values&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tính kích thước đầu ra
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Khởi tạo đầu ra
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Thực hiện tích chập (tương quan chéo)
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Trích vùng
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;region&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Nhân theo phần tử và cộng trên mọi chiều
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;region&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_multi_filter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Tích chập 2D đa bộ lọc tạo nhiều kênh đầu ra.
    
    Args:
        image: Đầu vào dạng (H, W, C_in)
        kernels: Bộ lọc dạng (num_filters, k, k, C_in)
        
    Returns:
        output: Bản đồ đặc trưng dạng (H_out, W_out, num_filters)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;num_filters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Áp dụng từng bộ lọc
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_filters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== DEMO ==============
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Ví dụ 1: Phát hiện cạnh
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Ví dụ 1: Phát hiện Cạnh Đứng&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tạo ảnh với cạnh đứng rõ ràng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Bộ dò cạnh đứng (kiểu Sobel)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vertical_kernel&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vertical_kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Ảnh đầu vào:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nhân:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vertical_kernel&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đầu ra (đã phát hiện cạnh):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lưu ý: Giá trị cao đúng tại vị trí cạnh đứng!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Ví dụ 2: Tích chập đích thực so với Tương quan chéo
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Ví dụ 2: Tích chập so với Tương quan chéo&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;asymmetric_kernel&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;flipped_kernel&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;asymmetric_kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nhân gốc:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;asymmetric_kernel&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nhân đã lật (cho tích chập đích thực):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;flipped_kernel&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;small_image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tương quan chéo (học sâu dùng)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cross_corr_result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;small_image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;asymmetric_kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tích chập đích thực (có lật)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_conv_result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;small_image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;flipped_kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kết quả tương quan chéo:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cross_corr_result&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kết quả tích chập đích thực:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_conv_result&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lưu ý: Kết quả khác nhau! Học sâu dùng tương quan chéo.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa phép trượt nhân và tính tổng tương ứng trực tiếp với các vòng lặp NumPy ở trên.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Bổ sung góc nhìn tổng quát về phép tích chập bên cạnh phần đánh chỉ số trong mã.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, tiếng Anh. Hữu ích khi cần đối chiếu kích thước đầu ra của cài đặt NumPy với công thức lý thuyết.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-02 Trực giác Tích chập và Ví dụ</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_02_Convolution_Intuition_and_Examples/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_02_Convolution_Intuition_and_Examples</id>
   <content type="html">&lt;p&gt;Làm thế nào một mạng chỉ toàn các bộ lọc bé xíu \(3 \times 3\) — mỗi bộ lọc chỉ nhìn thấy 9 điểm ảnh — lại có thể nhận ra cả một chiếc ô tô hay một khuôn mặt người nằm trải dài hàng trăm pixel? Câu trả lời không nằm ở việc phóng to từng bộ lọc, mà nằm ở nghệ thuật &lt;strong&gt;xếp chồng&lt;/strong&gt; để mở rộng tầm nhìn và lắp ghép đặc trưng theo từng tầng bậc.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trực-giác-cốt-lõi-để-đọc-vị-một-mạng-cnn&quot;&gt;Kiến thức cần nhớ: Ba trực giác cốt lõi để “đọc vị” một mạng CNN&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bộ lọc như một máy đo độ tương đồng mẫu (Template Matching)&lt;/strong&gt;:
Phép tích vô hướng giữa cửa sổ ảnh và bộ lọc đạt cực đại khi vùng ảnh có hoa văn giống hệt bộ lọc (ví dụ Sobel dọc phản hồi cực đại tại ranh giới sáng–tối theo phương thẳng đứng).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân cấp đặc trưng tự phát (Emergent Hierarchy)&lt;/strong&gt;:
Khi trực quan hóa trọng số của một CNN đã huấn luyện trên ImageNet, tầng 1 luôn tự học các bộ lọc Gabor (cạnh và chuyển màu), tầng 2–3 ghép cạnh thành đường cong và kết cấu (lưới, lông thú), còn tầng 4–5 phản hồi với bánh xe, mắt người hay mặt chó.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sự mở rộng của Trường tiếp nhận (Receptive Field)&lt;/strong&gt;:
Mỗi neuron ở tầng \(L\) tổng hợp tín hiệu từ một vùng \(k \times k\) của tầng \(L-1\). Nhờ hiệu ứng cộng dồn (và nhân lên khi có stride/pooling), trường tiếp nhận hiệu dụng mở rộng nhanh theo chiều sâu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trường tiếp nhận lý thuyết vs. Trường tiếp nhận hiệu dụng (ERF)&lt;/strong&gt;:
Dù trường tiếp nhận lý thuyết phủ rộng, các điểm ảnh ở tâm đóng góp nhiều đường đi hơn nên trọng số ảnh hưởng thường phân bố dạng hình chuông Gaussian tập trung quanh trung tâm.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-sự-mở-rộng-trường-tiếp-nhận-qua-3-tầng-tích-chập&quot;&gt;Giải thích: Tính tay sự mở rộng trường tiếp nhận qua 3 tầng tích chập&lt;/h3&gt;

&lt;p&gt;Giả sử ta xếp chồng các tầng tích chập \(3 \times 3\) với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;padding=1&lt;/code&gt;. Công thức truy hồi trường tiếp nhận \(r_l\) và bước nhảy tích lũy \(j_l\) là:
\(r_l = r_{l-1} + (k_l - 1) \cdot j_{l-1}, \qquad j_l = j_{l-1} \cdot s_l\)
với giá trị khởi đầu tại ảnh gốc: \(r_0 = 1, \; j_0 = 1\).&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Tầng \(l\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Cấu hình tầng&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Bước nhảy tích lũy \(j_{l-1}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Công thức tính \(r_l\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Trường tiếp nhận \(r_l\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;0&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Ảnh đầu vào&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;—&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;—&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1 \times 1\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Conv \(3\times 3, s=1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1 + (3-1)\cdot 1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(3 \times 3\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Conv \(3\times 3, s=2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(3 + (3-1)\cdot 1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(5 \times 5\)&lt;/strong&gt; (và \(j_2 = 2\))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Conv \(3\times 3, s=1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(5 + (3-1)\cdot 2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(9 \times 9\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ sau 3 tầng lọc nhỏ \(3\times 3\) (với một bước stride 2 ở giữa), mỗi điểm đặc trưng đã “bao quát” một vùng ảnh gốc \(9 \times 9\), nhưng tổng số trọng số trên mỗi kênh lại nhỏ hơn rất nhiều so với một bộ lọc \(9 \times 9\) duy nhất (\(3 \times 9 = 27\) so với \(81\)).&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ--trực-giác&quot;&gt;3. Ví dụ / Trực giác&lt;/h2&gt;

&lt;h3 id=&quot;ví-dụ-1-phát-hiện-cạnh-bằng-bộ-lọc-thủ-công&quot;&gt;Ví dụ 1: Phát hiện Cạnh bằng Bộ lọc Thủ công&lt;/h3&gt;

&lt;p&gt;Trước khi học sâu phổ biến, thị giác máy tính dựa nhiều vào các bộ lọc thiết kế thủ công. Tìm hiểu cách hoạt động của chúng giúp hình dung rõ hơn những gì CNN tự học trong quá trình huấn luyện.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bộ dò cạnh đứng&lt;/strong&gt; (kiểu Sobel):&lt;/p&gt;

\[K_{vertical} = \begin{bmatrix} 1 &amp;amp; 0 &amp;amp; -1 \\ 2 &amp;amp; 0 &amp;amp; -2 \\ 1 &amp;amp; 0 &amp;amp; -1 \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Cơ chế hoạt động:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Cột bên trái mang trọng số dương, đo cường độ sáng phía trái.&lt;/li&gt;
  &lt;li&gt;Cột bên phải mang trọng số âm, đo cường độ sáng phía phải.&lt;/li&gt;
  &lt;li&gt;Nếu bên trái sáng và bên phải tối, tổng cho giá trị dương lớn (báo hiệu có cạnh đứng).&lt;/li&gt;
  &lt;li&gt;Nếu vùng ảnh đồng đều, phần dương và phần âm triệt tiêu nhau nên đầu ra gần bằng 0.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Bộ dò cạnh ngang:&lt;/strong&gt;&lt;/p&gt;

\[K_{horizontal} = \begin{bmatrix} 1 &amp;amp; 2 &amp;amp; 1 \\ 0 &amp;amp; 0 &amp;amp; 0 \\ -1 &amp;amp; -2 &amp;amp; -1 \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Ví dụ tính tay:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Xét ảnh đầu vào mô phỏng một cạnh đứng (nửa trái sáng 100, nửa phải tối 0):
\(I = \begin{bmatrix} 
100 &amp;amp; 100 &amp;amp; 100 &amp;amp; 0 &amp;amp; 0 \\
100 &amp;amp; 100 &amp;amp; 100 &amp;amp; 0 &amp;amp; 0 \\
100 &amp;amp; 100 &amp;amp; 100 &amp;amp; 0 &amp;amp; 0 \\
100 &amp;amp; 100 &amp;amp; 100 &amp;amp; 0 &amp;amp; 0 \\
100 &amp;amp; 100 &amp;amp; 100 &amp;amp; 0 &amp;amp; 0
\end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Áp dụng nhân cạnh đứng tại vị trí (1,1) (vùng đồng đều):&lt;/strong&gt;&lt;/p&gt;

\[\begin{align}
S[1,1] &amp;amp;= (100 \times 1) + (100 \times 0) + (100 \times -1) \\
&amp;amp;+ (100 \times 2) + (100 \times 0) + (100 \times -2) \\
&amp;amp;+ (100 \times 1) + (100 \times 0) + (100 \times -1) \\
&amp;amp;= 100 - 100 + 200 - 200 + 100 - 100 = 0
\end{align}\]

&lt;p&gt;&lt;strong&gt;Tại vị trí (1,2) (nằm đúng trên cạnh):&lt;/strong&gt;&lt;/p&gt;

\[\begin{align}
S[1,2] &amp;amp;= (100 \times 1) + (100 \times 0) + (0 \times -1) \\
&amp;amp;+ (100 \times 2) + (100 \times 0) + (0 \times -2) \\
&amp;amp;+ (100 \times 1) + (100 \times 0) + (0 \times -1) \\
&amp;amp;= 100 + 0 + 0 + 200 + 0 + 0 + 100 + 0 + 0 = 400
\end{align}\]

&lt;p&gt;&lt;strong&gt;Kết quả:&lt;/strong&gt; Giá trị kích hoạt tăng cao (400) đúng tại vị trí ranh giới sáng–tối.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-2-cách-cnn-xây-dựng-biểu-diễn-phân-cấp&quot;&gt;Ví dụ 2: Cách CNN Xây dựng Biểu diễn Phân cấp&lt;/h3&gt;

&lt;p&gt;Một đặc trưng quan trọng của CNN là khả năng tự động học hệ thống đặc trưng theo nhiều tầng trừu tượng:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tầng 1 (Các tầng đầu — Đặc trưng cơ bản):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Cạnh theo nhiều góc nghiêng khác nhau&lt;/li&gt;
  &lt;li&gt;Vệt màu và sự chuyển đổi độ sáng (gradient)&lt;/li&gt;
  &lt;li&gt;Kết cấu đơn giản&lt;/li&gt;
  &lt;li&gt;Ví dụ bộ lọc: \(\begin{bmatrix} -1 &amp;amp; 0 &amp;amp; 1 \\ -1 &amp;amp; 0 &amp;amp; 1 \\ -1 &amp;amp; 0 &amp;amp; 1 \end{bmatrix}\), \(\begin{bmatrix} 1 &amp;amp; 1 &amp;amp; 1 \\ 0 &amp;amp; 0 &amp;amp; 0 \\ -1 &amp;amp; -1 &amp;amp; -1 \end{bmatrix}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Tầng 2–3 (Các tầng giữa — Hình dạng sơ cấp):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Góc (nơi các cạnh giao nhau)&lt;/li&gt;
  &lt;li&gt;Hình dạng cơ bản (đường cong, hình tròn, hình chữ nhật)&lt;/li&gt;
  &lt;li&gt;Hoa văn lặp lại như sọc, lưới, chấm&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Tầng 4–5 (Các tầng sâu hơn — Bộ phận đối tượng):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mắt, mũi, tai (trong bài toán khuôn mặt)&lt;/li&gt;
  &lt;li&gt;Bánh xe, cửa sổ, đèn pha (trong bài toán nhận diện phương tiện)&lt;/li&gt;
  &lt;li&gt;Cánh hoa, lá, thân (trong bài toán phân loại thực vật)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Các tầng cuối (Mức cao — Đối tượng hoàn chỉnh):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Khuôn mặt hoàn chỉnh ở nhiều góc nhìn&lt;/li&gt;
  &lt;li&gt;Hình dáng trọn vẹn của phương tiện hoặc động vật&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hệ phân cấp này tự hình thành qua quá trình huấn luyện:&lt;/strong&gt; mạng tự phát hiện rằng việc tổ hợp cạnh thành góc, góc thành bộ phận và bộ phận thành đối tượng giúp giảm hàm mất mát hiệu quả nhất.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-3-sự-mở-rộng-của-trường-tiếp-nhận&quot;&gt;Ví dụ 3: Sự Mở rộng của Trường Tiếp nhận&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Trường tiếp nhận&lt;/strong&gt; (&lt;em&gt;receptive field&lt;/em&gt;) là vùng trên ảnh đầu vào gốc có ảnh hưởng trực tiếp tới giá trị của một phần tử đầu ra nhất định.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Một tầng tích chập 3×3:&lt;/strong&gt; Mỗi điểm ở đầu ra quan sát vùng 3×3 của đầu vào.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hai tầng tích chập 3×3 xếp chồng:&lt;/strong&gt; Mỗi điểm ở đầu ra tầng 2 quan sát vùng 3×3 của đầu ra tầng 1; nhưng mỗi điểm trong vùng đó lại đại diện cho vùng 3×3 của đầu vào gốc. Kết hợp lại, đầu ra tầng 2 bao phủ vùng &lt;strong&gt;5×5&lt;/strong&gt; trên ảnh gốc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Công thức trường tiếp nhận với \(n\) tầng tích chập 3×3 (stride = 1):&lt;/strong&gt;&lt;/p&gt;

\[RF = 1 + 2n\]

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Số tầng&lt;/th&gt;
      &lt;th&gt;Trường tiếp nhận&lt;/th&gt;
      &lt;th&gt;Tương đương một nhân&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;3×3&lt;/td&gt;
      &lt;td&gt;3×3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;5×5&lt;/td&gt;
      &lt;td&gt;5×5&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;7×7&lt;/td&gt;
      &lt;td&gt;7×7&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;5&lt;/td&gt;
      &lt;td&gt;11×11&lt;/td&gt;
      &lt;td&gt;11×11&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;10&lt;/td&gt;
      &lt;td&gt;21×21&lt;/td&gt;
      &lt;td&gt;21×21&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Vì sao nên xếp chồng nhiều bộ lọc nhỏ thay vì dùng một bộ lọc lớn?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So sánh ba tầng tích chập 3×3 với một tầng tích chập 7×7 (giả sử cùng số kênh):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Chỉ số&lt;/th&gt;
      &lt;th&gt;Ba tầng 3×3&lt;/th&gt;
      &lt;th&gt;Một tầng 7×7&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Trường tiếp nhận&lt;/td&gt;
      &lt;td&gt;7×7&lt;/td&gt;
      &lt;td&gt;7×7&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Tham số mỗi cặp kênh&lt;/td&gt;
      &lt;td&gt;3×(3×3) = 27&lt;/td&gt;
      &lt;td&gt;7×7 = 49&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Số lớp phi tuyến&lt;/td&gt;
      &lt;td&gt;3 ReLU&lt;/td&gt;
      &lt;td&gt;1 ReLU&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Ba tầng 3×3 xếp chồng đạt cùng trường tiếp nhận 7×7 nhưng:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ít tham số hơn&lt;/strong&gt; (27 so với 49 trên mỗi cặp kênh)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhiều phép biến đổi phi tuyến hơn&lt;/strong&gt; (3 lớp ReLU so với 1)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sức biểu diễn cao hơn&lt;/strong&gt; nhờ có thêm các lớp kích hoạt trung gian&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nhận xét này từ kiến trúc VGGNet (2014) đã ảnh hưởng sâu rộng đến cách thiết kế các mạng CNN hiện đại.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Diễn giải trực quan bộ lọc như bộ phát hiện cạnh và mẫu cục bộ.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa các bộ lọc dò đặc trưng trên mảng ảnh cụ thể.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[CNN là gì?&lt;/td&gt;
          &lt;td&gt;Hiểu Nhanh Mạng Nơ-ron Tích Chập [PODCAST]](https://www.youtube.com/watch?v=YlgdXkzjo3Q) — Gà AI, tiếng Việt. Giải thích trực giác cửa sổ trượt bằng tiếng Việt.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-01 Toán học Tích chập và Kích thước</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_01_Convolution_Math_and_Dimensions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_01_01_Convolution_Math_and_Dimensions</id>
   <content type="html">&lt;p&gt;Trong phòng thí nghiệm giải phẫu thần kinh năm 1959, David Hubel và Torsten Wiesel tình cờ phát hiện một điều kinh ngạc: tế bào vỏ não thị giác mèo không hề phản ứng với một đốm sáng tròn, nhưng lại phát xung dữ dội ngay khi mép tấm kính trượt tạo thành một &lt;strong&gt;vạch thẳng nghiêng&lt;/strong&gt; lướt ngang trường nhìn. Hơn nửa thế kỷ sau, phép toán mô phỏng lại cơ chế quét mẫu cục bộ ấy — tích chập 2D đa kênh — đã trở thành ngôn ngữ nền tảng của toàn bộ thị giác máy tính.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-toán-học-của-tầng-tích-chập&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột toán học của Tầng Tích chập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập (Convolution) vs. Tương quan chéo (Cross-Correlation)&lt;/strong&gt;:
Xử lý tín hiệu lật ngược bộ lọc 180° trước khi trượt để phép toán có tính giao hoán; Deep Learning bỏ bước lật vì trọng số do mạng tự học nên lật hay không cho cùng không gian hàm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập đa kênh (Multi-Channel Convolution)&lt;/strong&gt;:
Với ảnh RGB (\(C_{\text{in}} = 3\)), mỗi bộ lọc thực chất là một khối 3D kích thước \(K_h \times K_w \times C_{\text{in}}\) cộng gộp kết quả trên cả 3 kênh để sinh ra &lt;strong&gt;một&lt;/strong&gt; bản đồ đặc trưng 2D; muốn có \(C_{\text{out}}\) kênh đầu ra thì cần \(C_{\text{out}}\) khối lọc độc lập.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hình học đầu ra với Padding (\(P\)) và Stride (\(S\))&lt;/strong&gt;:
Padding giữ nguyên thông tin biên ảnh và kiểm soát kích thước; Stride lớn hơn 1 giúp giảm độ phân giải ngay trong phép tích chập mà không cần thêm tầng gộp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ngân sách tham số và độ phức tạp tính toán&lt;/strong&gt;:
Số tham số độc lập với độ phân giải ảnh \((H, W)\), nhưng số phép tính FLOPs tỷ lệ thuận với \(H_{\text{out}} \cdot W_{\text{out}}\) — đây là lý do ảnh độ phân giải cao tiêu tốn bộ nhớ kích hoạt rất lớn dù mô hình ít tham số.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-tương-quan-chéo-2d-với-padding-và-stride&quot;&gt;Giải thích: Tính tay tương quan chéo 2D với Padding và Stride&lt;/h3&gt;

&lt;p&gt;Xét ma trận đầu vào \(I\) kích thước \(4 \times 4\) và bộ lọc phát hiện cạnh dọc \(K\) kích thước \(2 \times 2\) với \(P = 0, S = 2\):&lt;/p&gt;

\[I = \begin{bmatrix} 1 &amp;amp; 3 &amp;amp; 0 &amp;amp; 2 \\ 2 &amp;amp; 4 &amp;amp; 1 &amp;amp; 0 \\ 0 &amp;amp; 1 &amp;amp; 5 &amp;amp; 2 \\ 3 &amp;amp; 2 &amp;amp; 1 &amp;amp; 4 \end{bmatrix}, \qquad K = \begin{bmatrix} -1 &amp;amp; 1 \\ -1 &amp;amp; 1 \end{bmatrix}\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra kích thước đầu ra&lt;/strong&gt;: \(H_{\text{out}} = \lfloor (4 + 0 - 2)/2 \rfloor + 1 = 2\), nên đầu ra \(O\) có kích thước \(2 \times 2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính từng phần tử của \(O\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(O[0,0]\) (cửa sổ góc trên trái): \((-1)(1) + (1)(3) + (-1)(2) + (1)(4) = -1 + 3 - 2 + 4 = 4\).&lt;/li&gt;
      &lt;li&gt;\(O[0,1]\) (dịch phải \(S=2\) cột): \((-1)(0) + (1)(2) + (-1)(1) + (1)(0) = 0 + 2 - 1 + 0 = 1\).&lt;/li&gt;
      &lt;li&gt;\(O[1,0]\) (dịch xuống \(S=2\) hàng): \((-1)(0) + (1)(1) + (-1)(3) + (1)(2) = 0 + 1 - 3 + 2 = 0\).&lt;/li&gt;
      &lt;li&gt;\(O[1,1]\) (góc dưới phải): \((-1)(5) + (1)(2) + (-1)(1) + (1)(4) = -5 + 2 - 1 + 4 = 0\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Kết quả \(O = \begin{bmatrix} 4 &amp;amp; 1 \\ 0 &amp;amp; 0 \end{bmatrix}\) cho thấy phản hồi mạnh nhất (\(4\)) nằm đúng ở góc trên trái — nơi giá trị pixel nhảy vọt từ cột trái (1, 2) sang cột phải (3, 4).&lt;/p&gt;

&lt;h1 id=&quot;tầng-tích-chập-khối-xây-dựng-của-thị-giác-máy-tính&quot;&gt;Tầng Tích chập: Khối Xây dựng của Thị giác Máy tính&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv1.jpg&quot; alt=&quot;CNN&quot; /&gt;
&lt;em&gt;Tổng quan kiến trúc Mạng Neuron Tích chập (CNN). Nguồn: AnalyticsVidhya&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Tầng tích chập&lt;/strong&gt; (&lt;em&gt;convolutional layers&lt;/em&gt;) là thành phần chuyên dụng của mạng neuron dùng để xử lý dữ liệu dạng lưới, đặc biệt là ảnh. Thay vì nối mọi đầu vào với mọi neuron như tầng liên kết đầy đủ, tầng tích chập sử dụng các bộ lọc nhỏ có thể học được, trượt qua toàn bộ đầu vào để phát hiện các mẫu cục bộ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Các ưu điểm chính của CNN:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu quả tham số:&lt;/strong&gt; Giảm hàng triệu tham số so với mạng liên kết đầy đủ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính bất biến tịnh tiến:&lt;/strong&gt; Có khả năng phát hiện cùng một đặc trưng ở bất kỳ vị trí nào trên ảnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học đặc trưng phân cấp:&lt;/strong&gt; Tự động trích xuất dần từ đặc trưng mức thấp đến mức trung bình và mức cao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu quả thực tiễn cao:&lt;/strong&gt; Đạt kết quả tốt trên nhiều bài toán thị giác máy tính.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ý tưởng cốt lõi:&lt;/strong&gt; Ảnh có cấu trúc không gian chặt chẽ — các điểm ảnh lân cận thường liên hệ mật thiết với nhau. Tầng tích chập khai thác tính chất này thông qua &lt;strong&gt;kết nối cục bộ&lt;/strong&gt; và &lt;strong&gt;chia sẻ tham số&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trực giác:&lt;/strong&gt; Có thể hình dung phép tích chập giống như việc trượt một kính lúp (bộ lọc) khắp bức ảnh để tìm một mẫu cụ thể (như cạnh, kết cấu hay hình dạng). Mỗi bộ lọc chuyên phát hiện một loại đặc trưng, và ta dùng cùng một bộ lọc đó cho mọi vị trí thay vì học riêng từng bộ trọng số cho từng vùng ảnh.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv2.jpg&quot; alt=&quot;CNN&quot; /&gt;
&lt;em&gt;Tổng quan kiến trúc Mạng Neuron Tích chập (CNN). Nguồn: AnalyticsVidhya&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;cảm-hứng-sinh-học&quot;&gt;Cảm hứng Sinh học&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv3.jpg&quot; alt=&quot;CNN Inspiration from Human Eye&quot; /&gt;
&lt;em&gt;CNN lấy cảm hứng từ cách hệ thống thị giác của não người xử lý hình ảnh: phát hiện cạnh trước, ghép thành hình dạng rồi nhận diện đối tượng. Nguồn: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Năm 1959, hai nhà thần kinh sinh lý học David Hubel và Torsten Wiesel phát hiện rằng các neuron trong vỏ não thị giác chỉ phản ứng với những mẫu nhất định nằm trong một vùng cục bộ của trường nhìn — gọi là “trường tiếp nhận” (&lt;em&gt;receptive field&lt;/em&gt;). Một số neuron nhạy với cạnh theo hướng cụ thể, trong khi các lớp sâu hơn kết hợp chúng để nhận diện cấu trúc phức tạp hơn. Cơ chế xử lý phân cấp này đã trực tiếp gợi ý cho thiết kế của mạng neuron tích chập.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;h3 id=&quot;phân-biệt-tích-chập-và-tương-quan-chéo&quot;&gt;Phân biệt Tích chập và Tương quan chéo&lt;/h3&gt;

&lt;p&gt;Đây là điểm khác biệt về thuật ngữ và định nghĩa mà người mới học thường dễ nhầm lẫn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://miro.medium.com/v2/resize:fit:1400/1*Zx-ZMLKab7VOCQTxdZ1OAw.gif&quot; alt=&quot;Convolution Operation&quot; /&gt;
&lt;em&gt;Minh họa phép tích chập 2D trên ảnh. Nguồn: Medium&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv4.jpg&quot; alt=&quot;The Convolution Filter Sliding&quot; /&gt;
&lt;em&gt;Một cửa sổ nhỏ gọi là bộ lọc trượt qua từng vùng của ảnh để kiểm tra sự hiện diện của một đặc trưng nhất định (cạnh, làm mờ, làm nét). Trong quá trình huấn luyện, CNN tự học hàng trăm bộ lọc như vậy. Nguồn: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;h4 id=&quot;tích-chập-đúng-nghĩa-định-nghĩa-trong-xử-lý-tín-hiệu&quot;&gt;Tích chập Đúng nghĩa (Định nghĩa trong Xử lý Tín hiệu)&lt;/h4&gt;

&lt;p&gt;Trong toán học và xử lý tín hiệu, &lt;strong&gt;tích chập&lt;/strong&gt; (&lt;em&gt;convolution&lt;/em&gt;) bao gồm bước &lt;strong&gt;lật nhân&lt;/strong&gt; (xoay 180°) trước khi trượt trên đầu vào. Với ảnh 2D \(I\) và nhân \(K\):&lt;/p&gt;

\[(I * K)[i,j] = \sum_{m}\sum_{n} I[m, n] \cdot K[i-m, j-n]\]

&lt;p&gt;Khi viết theo chỉ số của nhân kích thước \(k \times k\):&lt;/p&gt;

\[(I * K)[i,j] = \sum_{m=0}^{k-1}\sum_{n=0}^{k-1} I[i-m, j-n] \cdot K[m,n]\]

&lt;p&gt;Đặc trưng nhận diện là dấu &lt;strong&gt;trừ&lt;/strong&gt; ở chỉ số (\(i-m, j-n\)), tương đương với thao tác lật nhân theo cả hai trục.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vì sao xử lý tín hiệu cần lật nhân?&lt;/strong&gt; Việc lật nhân giúp phép tích chập thỏa mãn hai tính chất đại số quan trọng cho hệ thống tuyến tính bất biến theo thời gian (LTI):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính giao hoán:&lt;/strong&gt; \(I * K = K * I\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính kết hợp:&lt;/strong&gt; \((I * K_1) * K_2 = I * (K_1 * K_2)\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h4 id=&quot;tương-quan-chéo-phép-toán-học-sâu-thực-tế-sử-dụng&quot;&gt;Tương quan chéo (Phép toán Học sâu Thực tế Sử dụng)&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Tương quan chéo&lt;/strong&gt; (&lt;em&gt;cross-correlation&lt;/em&gt;) có cấu trúc tương tự nhưng &lt;strong&gt;không lật nhân&lt;/strong&gt;:&lt;/p&gt;

\[S[i,j] = \sum_{m=0}^{k-1}\sum_{n=0}^{k-1} I[i+m, j+n] \cdot K[m,n]\]

&lt;p&gt;Chú ý dấu &lt;strong&gt;cộng&lt;/strong&gt; trong chỉ số (\(i+m, j+n\)) — ta trượt trực tiếp nhân nguyên trạng qua ảnh.&lt;/p&gt;

&lt;h4 id=&quot;ví-dụ-so-sánh-tích-chập-và-tương-quan-chéo&quot;&gt;Ví dụ So sánh: Tích chập và Tương quan chéo&lt;/h4&gt;

&lt;p&gt;Xét nhân \(K\):
\(K = \begin{bmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 4 &amp;amp; 5 &amp;amp; 6 \\ 7 &amp;amp; 8 &amp;amp; 9 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Nhân sau khi lật 180° (dùng cho tích chập đúng nghĩa):
\(K_{flipped} = \begin{bmatrix} 9 &amp;amp; 8 &amp;amp; 7 \\ 6 &amp;amp; 5 &amp;amp; 4 \\ 3 &amp;amp; 2 &amp;amp; 1 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Với một bộ dò cạnh đứng:
\(K = \begin{bmatrix} 1 &amp;amp; 0 &amp;amp; -1 \\ 1 &amp;amp; 0 &amp;amp; -1 \\ 1 &amp;amp; 0 &amp;amp; -1 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Khi lật nhân, dấu hai cột đổi chỗ cho nhau:
\(K_{flipped} = \begin{bmatrix} -1 &amp;amp; 0 &amp;amp; 1 \\ -1 &amp;amp; 0 &amp;amp; 1 \\ -1 &amp;amp; 0 &amp;amp; 1 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Như vậy, bản đã lật sẽ phát hiện sự chuyển sáng–tối theo &lt;strong&gt;chiều ngược lại&lt;/strong&gt;.&lt;/p&gt;

&lt;h4 id=&quot;vì-sao-học-sâu-dùng-tương-quan-chéo-nhưng-vẫn-gọi-là-tích-chập&quot;&gt;Vì sao Học sâu Dùng Tương quan chéo nhưng Vẫn Gọi là “Tích chập”&lt;/h4&gt;

&lt;p&gt;Điểm mấu chốt là &lt;strong&gt;trong học sâu, trọng số của nhân được học tự động từ dữ liệu&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nếu cài đặt tích chập có lật:&lt;/strong&gt; Mạng học ma trận trọng số \(W\) rồi lật nó khi tính lượt xuôi.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nếu cài đặt tương quan chéo:&lt;/strong&gt; Mạng học trực tiếp ma trận trọng số \(W&apos;\) mà không cần bước lật.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Vì \(W&apos;\) chỉ đơn giản học thành phiên bản lật của \(W\), &lt;strong&gt;khả năng biểu diễn của mạng là hoàn toàn tương đương&lt;/strong&gt;. Dùng tương quan chéo vừa gọn hơn khi cài đặt, vừa trực quan hơn khi quan sát bộ lọc vì hình dạng của nhân khớp trực tiếp với mẫu mà nó phát hiện.&lt;/p&gt;

&lt;p&gt;Trong cộng đồng học sâu, thuật ngữ “tích chập” đã trở thành cách gọi quen thuộc dù đa số thư viện cài đặt phép tương quan chéo. Nắm rõ sự khác biệt này vẫn hữu ích khi đọc tài liệu xử lý tín hiệu hoặc tự viết phép toán tùy chỉnh.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-tính-tương-quan-chéo-từng-bước&quot;&gt;Ví dụ Tính Tương quan chéo Từng bước&lt;/h3&gt;

&lt;p&gt;Xét ảnh đầu vào \(I\) kích thước 5×5:
\(I = \begin{bmatrix} 
1 &amp;amp; 2 &amp;amp; 3 &amp;amp; 0 &amp;amp; 1 \\
0 &amp;amp; 1 &amp;amp; 2 &amp;amp; 3 &amp;amp; 1 \\
1 &amp;amp; 2 &amp;amp; 1 &amp;amp; 0 &amp;amp; 0 \\
0 &amp;amp; 1 &amp;amp; 2 &amp;amp; 3 &amp;amp; 2 \\
2 &amp;amp; 1 &amp;amp; 0 &amp;amp; 1 &amp;amp; 1
\end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;và nhân \(K\) kích thước 3×3:
\(K = \begin{bmatrix} 
1 &amp;amp; 0 &amp;amp; -1 \\
1 &amp;amp; 0 &amp;amp; -1 \\
1 &amp;amp; 0 &amp;amp; -1
\end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính đầu ra tại vị trí (0,0):&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Trích vùng 3×3 bắt đầu từ góc (0,0):
\(\text{region} = \begin{bmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 0 &amp;amp; 1 &amp;amp; 2 \\ 1 &amp;amp; 2 &amp;amp; 1 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Nhân từng phần tử tương ứng rồi cộng tổng:
\(\begin{align}
S[0,0] &amp;amp;= (1 \times 1) + (2 \times 0) + (3 \times -1) \\
&amp;amp;+ (0 \times 1) + (1 \times 0) + (2 \times -1) \\
&amp;amp;+ (1 \times 1) + (2 \times 0) + (1 \times -1) \\
&amp;amp;= 1 + 0 - 3 + 0 + 0 - 2 + 1 + 0 - 1 \\
&amp;amp;= -4
\end{align}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính đầu ra tại vị trí (0,1):&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Trích vùng 3×3 bắt đầu từ (0,1):
\(\text{region} = \begin{bmatrix} 2 &amp;amp; 3 &amp;amp; 0 \\ 1 &amp;amp; 2 &amp;amp; 3 \\ 2 &amp;amp; 1 &amp;amp; 0 \end{bmatrix}\)&lt;/p&gt;

\[\begin{align}
S[0,1] &amp;amp;= (2 \times 1) + (3 \times 0) + (0 \times -1) \\
&amp;amp;+ (1 \times 1) + (2 \times 0) + (3 \times -1) \\
&amp;amp;+ (2 \times 1) + (1 \times 0) + (0 \times -1) \\
&amp;amp;= 2 + 0 + 0 + 1 + 0 - 3 + 2 + 0 + 0 \\
&amp;amp;= 2
\end{align}\]

&lt;p&gt;Lặp lại phép tính này trên mọi vị trí hợp lệ sẽ thu được toàn bộ bản đồ đặc trưng đầu ra.&lt;/p&gt;

&lt;h3 id=&quot;tích-chập-đa-kênh&quot;&gt;Tích chập Đa kênh&lt;/h3&gt;

&lt;p&gt;Ảnh màu thực tế có nhiều kênh (ảnh RGB có 3 kênh; các tầng trung gian trong CNN có thể có 64, 128, 256 kênh hoặc nhiều hơn). Khi đó, phép tích chập được mở rộng như sau:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Với đầu vào có \(C_{in}\) kênh&lt;/strong&gt; (kích thước \(H \times W \times C_{in}\)) và &lt;strong&gt;một bộ lọc kích thước \(k \times k \times C_{in}\)&lt;/strong&gt;:&lt;/p&gt;

\[S[i,j] = \sum_{c=0}^{C_{in}-1} \sum_{m=0}^{k-1}\sum_{n=0}^{k-1} I[i+m, j+n, c] \cdot K[m,n,c] + b\]

&lt;p&gt;Trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(C_{in}\): số kênh đầu vào (bằng 3 với ảnh RGB)&lt;/li&gt;
  &lt;li&gt;\(b\): hệ số độ lệch (một số vô hướng cho mỗi bộ lọc)&lt;/li&gt;
  &lt;li&gt;Mỗi bộ lọc tạo ra &lt;strong&gt;một&lt;/strong&gt; kênh đầu ra&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Để tạo \(C_{out}\) kênh đầu ra&lt;/strong&gt;, tầng tích chập sử dụng \(C_{out}\) bộ lọc độc lập, mỗi bộ lọc có kích thước \(k \times k \times C_{in}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trực giác:&lt;/strong&gt; Với ảnh RGB, mỗi bộ lọc là một khối 3D (ví dụ 3×3×3) có trọng số riêng cho từng kênh màu rồi cộng gộp kết quả lại thành một số vô hướng tại mỗi vị trí. Nhờ đó bộ lọc có thể học các đặc trưng kết hợp thông tin màu sắc (ví dụ phân biệt màu xanh da trời và màu xanh của cỏ).&lt;/p&gt;

&lt;h3 id=&quot;công-thức-kích-thước-đầu-ra&quot;&gt;Công thức Kích thước Đầu ra&lt;/h3&gt;

&lt;p&gt;Nắm chắc cách thay đổi kích thước không gian qua từng tầng là điều cần thiết khi thiết kế CNN.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Các tham số:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Kích thước đầu vào: \(H_{in} \times W_{in}\)&lt;/li&gt;
  &lt;li&gt;Kích thước nhân: \(k \times k\)&lt;/li&gt;
  &lt;li&gt;Bước nhảy (&lt;em&gt;stride&lt;/em&gt;): \(s\) (số điểm ảnh dịch chuyển giữa hai vị trí liên tiếp)&lt;/li&gt;
  &lt;li&gt;Đệm (&lt;em&gt;padding&lt;/em&gt;): \(p\) (số hàng/cột giá trị 0 thêm vào mỗi cạnh)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kích thước đầu ra:&lt;/strong&gt;&lt;/p&gt;

\[H_{out} = \left\lfloor \frac{H_{in} + 2p - k}{s} \right\rfloor + 1\]

\[W_{out} = \left\lfloor \frac{W_{in} + 2p - k}{s} \right\rfloor + 1\]

&lt;p&gt;&lt;strong&gt;Các cấu hình thường gặp:&lt;/strong&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Cấu hình&lt;/th&gt;
      &lt;th&gt;Mục đích&lt;/th&gt;
      &lt;th&gt;Kết quả&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(k=3, s=1, p=1\)&lt;/td&gt;
      &lt;td&gt;Đệm “same” (giữ nguyên kích thước)&lt;/td&gt;
      &lt;td&gt;\(n_{out} = n_{in}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(k=3, s=2, p=1\)&lt;/td&gt;
      &lt;td&gt;Giảm kích thước một nửa&lt;/td&gt;
      &lt;td&gt;\(n_{out} = \lceil n_{in}/2 \rceil\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(k=1, s=1, p=0\)&lt;/td&gt;
      &lt;td&gt;Tích chập 1×1&lt;/td&gt;
      &lt;td&gt;\(n_{out} = n_{in}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(k=7, s=2, p=3\)&lt;/td&gt;
      &lt;td&gt;Giảm kích thước ở tầng đầu&lt;/td&gt;
      &lt;td&gt;\(n_{out} = \lceil n_{in}/2 \rceil\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;phân-tích-số-tham-số&quot;&gt;Phân tích Số Tham số&lt;/h3&gt;

&lt;p&gt;Tổng số tham số của một tầng tích chập:&lt;/p&gt;

\[\text{Parameters} = (k \times k \times C_{in}) \times C_{out} + C_{out}\]

&lt;p&gt;Số hạng thứ nhất là số trọng số (\(C_{out}\) bộ lọc, mỗi bộ gồm \(k \times k \times C_{in}\) trọng số), và số hạng thứ hai là số hệ số độ lệch (một cho mỗi kênh đầu ra).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ minh họa:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đầu vào: \(32 \times 32 \times 3\) (ảnh RGB CIFAR-10)&lt;/li&gt;
  &lt;li&gt;Tầng tích chập: 64 bộ lọc kích thước \(3 \times 3\)&lt;/li&gt;
  &lt;li&gt;Số tham số: \((3 \times 3 \times 3) \times 64 + 64 = 27 \times 64 + 64 = 1,792\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;So sánh với tầng liên kết đầy đủ:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đầu vào: \(32 \times 32 \times 3 = 3,072\) giá trị&lt;/li&gt;
  &lt;li&gt;Đầu ra: 64 neuron&lt;/li&gt;
  &lt;li&gt;Số tham số: \(3,072 \times 64 + 64 = 196,672\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Mức giảm:&lt;/strong&gt; \(196,672 / 1,792 \approx 110\) lần ít tham số hơn.&lt;/p&gt;

&lt;p&gt;Hiệu quả vượt trội về tham số này bắt nguồn trực tiếp từ hai cơ chế:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kết nối cục bộ:&lt;/strong&gt; Mỗi phần tử đầu ra chỉ phụ thuộc vào một vùng nhỏ của đầu vào.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chia sẻ tham số:&lt;/strong&gt; Cùng một bộ trọng số được áp dụng trên toàn bộ không gian ảnh.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Giải thích bản chất của tổng định nghĩa tích chập.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, tiếng Anh. Trình bày công thức tính chiều cao và chiều rộng đầu ra theo kích thước nhân, padding và stride.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Ví dụ số trên ảnh nhỏ giúp tự kiểm chứng công thức kích thước bằng tay.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04 Giới thiệu về Mạng Neuron Tích chập</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter04/04_00_Introduction</id>
   <content type="html">&lt;p&gt;Nếu bạn cố nhét một bức ảnh màu kích thước \(224 \times 224\) vào một mạng neuron liên kết đầy đủ (MLP) bình thường, chỉ riêng tầng ẩn đầu tiên có 1.000 neuron đã ngốn hơn &lt;strong&gt;150 triệu tham số&lt;/strong&gt; — và tệ hơn, chỉ cần dịch chuyển chú mèo sang phải một pixel, mạng MLP phải học lại gần như từ con số 0. Chính bế tắc mang tính hình học ấy đã buộc các nhà khoa học phải quay sang quan sát vỏ não thị giác động vật và khai sinh ra &lt;strong&gt;Mạng Neuron Tích chập (CNN)&lt;/strong&gt; — kiến trúc đã mở ra kỷ nguyên thị giác máy tính hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-tạo-nên-sức-mạnh-của-cnn&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột tạo nên sức mạnh của CNN&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kết nối cục bộ (Local Connectivity)&lt;/strong&gt;:
Thay vì nối mỗi neuron với toàn bộ bức ảnh, CNN chỉ nhìn vào một cửa sổ nhỏ (như \(3 \times 3\) hay \(5 \times 5\)) tại mỗi thời điểm, tận dụng tính chất rằng các điểm ảnh lân cận mang tương quan không gian chặt chẽ nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chia sẻ trọng số (Parameter Sharing) và Đồng biến tịnh tiến&lt;/strong&gt;:
Cùng một bộ lọc (kernel) được trượt khắp ảnh. Nhờ vậy số tham số giảm hàng nghìn lần, đồng thời một đặc trưng (ví dụ mép tai mèo) dù nằm ở góc trên hay góc dưới vẫn kích hoạt cùng một phản hồi tương ứng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biểu diễn phân cấp (Hierarchical Representation)&lt;/strong&gt;:
Khi xếp chồng nhiều tầng tích chập và tầng gộp, mạng tự động tổ chức tri thức theo tầng bậc: cạnh và góc ở tầng nông \(\to\) họa tiết và bộ phận ở tầng giữa \(\to\) vật thể hoàn chỉnh ở tầng sâu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hành trình kiến trúc từ LeNet đến ResNet&lt;/strong&gt;:
Từ mạng 5 tầng đọc chữ số viết tay năm 1998 đến mạng 152 tầng vượt chuẩn con người trên ImageNet năm 2015, lịch sử CNN là câu chuyện giải bài toán “làm sao đi sâu hơn mà gradient không tắt lịm”.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-bằng-số-giữa-mlp-và-cnn-trên-cùng-một-ảnh&quot;&gt;Giải thích: So sánh bằng số giữa MLP và CNN trên cùng một ảnh&lt;/h3&gt;

&lt;p&gt;Giả sử ta có một ảnh màu RGB kích thước \(64 \times 64 \times 3\) và muốn tạo ra tầng biểu diễn đầu tiên gồm 16 kênh đặc trưng cùng kích thước không gian \(64 \times 64\) (tổng cộng \(64 \times 64 \times 16 = 65{,}536\) giá trị đầu ra):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Thiết kế tầng&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Công thức số tham số (có bias)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Phép tính cụ thể&lt;/th&gt;
      &lt;th style=&quot;text-align: right&quot;&gt;Tổng số tham số&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Tầng liên kết đầy đủ (MLP)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(N_{\text{in}} \cdot N_{\text{out}} + N_{\text{out}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((64\cdot 64\cdot 3) \times 65{,}536 + 65{,}536\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;&lt;strong&gt;805,371,904&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Tầng tích chập \(3 \times 3\) (CNN)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((k_h \cdot k_w \cdot C_{\text{in}} + 1) \cdot C_{\text{out}}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\((3 \times 3 \times 3 + 1) \times 16\)&lt;/td&gt;
      &lt;td style=&quot;text-align: right&quot;&gt;&lt;strong&gt;448&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ bằng cách áp đặt hai thiên kiến quy nạp là kết nối cục bộ và chia sẻ trọng số, số tham số giảm hơn &lt;strong&gt;1,79 triệu lần&lt;/strong&gt; (từ hơn 805 triệu xuống còn 448), giúp mô hình có thể huấn luyện được trên phần cứng thực tế và tổng quát hóa tốt hơn hẳn trên ảnh chưa từng thấy.&lt;/p&gt;

&lt;h1 id=&quot;giới-thiệu-về-mạng-neuron-tích-chập&quot;&gt;Giới thiệu về Mạng Neuron Tích chập&lt;/h1&gt;

&lt;p&gt;Mạng Neuron Tích chập (&lt;em&gt;Convolutional Neural Networks&lt;/em&gt; — CNN) là họ mạng neuron chuyên dụng cho &lt;strong&gt;dữ liệu có cấu trúc dạng lưới&lt;/strong&gt;, tiêu biểu nhất là ảnh. CNN là nền tảng của nhiều hệ thống thị giác máy tính hiện đại, từ phân loại ảnh, chẩn đoán y khoa, nhận diện khuôn mặt cho đến xe tự lái.&lt;/p&gt;

&lt;p&gt;Chương này trình bày những nguyên lý cốt lõi của CNN: lý do ra đời, cơ chế hoạt động và các thành phần kiến trúc quan trọng. Sau chương này, bạn sẽ nắm vững các khối cơ bản tạo nên phần lớn mô hình thị giác máy tính.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;vì-sao-cần-cnn-hạn-chế-của-mạng-liên-kết-đầy-đủ&quot;&gt;Vì sao cần CNN? Hạn chế của Mạng Liên kết Đầy đủ&lt;/h2&gt;

&lt;p&gt;Xét một ảnh màu RGB kích thước 224×224 — kích thước đầu vào tiêu chuẩn của bộ dữ liệu ImageNet. Chỉ riêng một bức ảnh đã chứa:&lt;/p&gt;

\[224 \times 224 \times 3 = 150,528 \text{ điểm ảnh}\]

&lt;p&gt;Nếu nối trực tiếp toàn bộ điểm ảnh này vào một lớp ẩn gồm 1.000 neuron:&lt;/p&gt;

\[150,528 \times 1000 = 150,528,000 \text{ tham số}\]

&lt;p&gt;Con số lên tới &lt;strong&gt;hơn 150 triệu tham số&lt;/strong&gt; ngay ở lớp đầu tiên. Cách tiếp cận liên kết đầy đủ bộc lộ ba nhược điểm lớn:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bùng nổ số tham số và chi phí tính toán:&lt;/strong&gt; Quá nhiều trọng số cần học, dễ gây quá khớp và tốn tài nguyên.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bỏ qua cấu trúc không gian:&lt;/strong&gt; Việc làm phẳng ảnh coi mọi điểm ảnh độc lập, làm mất mối quan hệ lân cận giữa các điểm ảnh.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không có tính bất biến tịnh tiến:&lt;/strong&gt; Một đối tượng (như con mèo) xuất hiện ở góc trên bên trái và ở góc dưới bên phải phải được học lại như hai mẫu hoàn toàn tách biệt.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;CNN giải quyết cả ba hạn chế này nhờ hai cơ chế cốt lõi: &lt;strong&gt;kết nối cục bộ&lt;/strong&gt; (&lt;em&gt;local connectivity&lt;/em&gt;) và &lt;strong&gt;chia sẻ tham số&lt;/strong&gt; (&lt;em&gt;parameter sharing&lt;/em&gt;).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;tổng-quan-về-cnn&quot;&gt;Tổng quan về CNN&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv.jpg&quot; alt=&quot;CNN Pipeline Overview&quot; /&gt;
&lt;em&gt;Tổng quan về Mạng Neuron Tích chập: CNN xử lý ảnh qua chuỗi các tầng tích chập và gộp (pooling), trích xuất các đặc trưng ngày càng phức tạp trước khi bộ phân loại cuối đưa ra dự đoán. Nguồn: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Một mạng CNN tiêu biểu gồm các thành phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tầng tích chập&lt;/strong&gt; (&lt;em&gt;convolutional layers&lt;/em&gt;): Trích xuất đặc trưng cục bộ bằng các bộ lọc học được.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng gộp&lt;/strong&gt; (&lt;em&gt;pooling layers&lt;/em&gt;): Giảm kích thước không gian của bản đồ đặc trưng và tăng độ bền vững trước dịch chuyển nhỏ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm kích hoạt:&lt;/strong&gt; Đưa tính phi tuyến vào mạng (thường dùng ReLU).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng liên kết đầy đủ:&lt;/strong&gt; Tổng hợp các đặc trưng cấp cao để thực hiện phân loại ở cuối mạng.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Ý tưởng trọng tâm là thay vì học một trọng số riêng cho từng điểm ảnh đầu vào, CNN học &lt;strong&gt;các bộ lọc kích thước nhỏ&lt;/strong&gt; (thường 3×3 hoặc 5×5) trượt đều trên toàn bộ ảnh, vừa giảm mạnh số tham số vừa bảo toàn cấu trúc không gian.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;vị-trí-của-cnn-trong-học-sâu&quot;&gt;Vị trí của CNN trong Học sâu&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv1.jpg&quot; alt=&quot;AI/ML/DL Hierarchy&quot; /&gt;
&lt;em&gt;CNN là nhánh mô hình học sâu chuyên biệt cho dữ liệu thị giác (ảnh, video và dữ liệu dạng lưới điểm ảnh), bên cạnh RNN cho dữ liệu chuỗi và Transformer cho cơ chế attention. Nguồn: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Các cột mốc lịch sử chính:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;1989:&lt;/strong&gt; Yann LeCun áp dụng lan truyền ngược cho mạng tích chập.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;1998:&lt;/strong&gt; LeNet-5 đạt kết quả tốt trên bài toán nhận diện chữ số viết tay.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2012:&lt;/strong&gt; AlexNet giành chiến thắng tại cuộc thi ImageNet, mở ra giai đoạn phát triển mạnh của học sâu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2015:&lt;/strong&gt; ResNet với kết nối tắt cho phép huấn luyện mạng rất sâu và vượt mức hiệu năng con người trên ImageNet.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Từ 2020 trở đi:&lt;/strong&gt; CNN phát triển song song và kết hợp với Transformer (Vision Transformers, ConvNeXt).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bản-chất-của-cnn&quot;&gt;Bản chất của CNN&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv2.jpg&quot; alt=&quot;What is a CNN&quot; /&gt;
&lt;em&gt;CNN quan sát từng vùng cục bộ trên ảnh để bảo toàn cấu trúc không gian, phát hiện đặc trưng bất kể vị trí và xây dựng biểu diễn phức tạp từ các thành phần đơn giản. Mỗi bộ lọc tích chập đóng vai trò như một bộ phát hiện đặc trưng chuyên biệt. Nguồn: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Các khái niệm cốt lõi:&lt;/strong&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Khái niệm&lt;/th&gt;
      &lt;th&gt;Mô tả&lt;/th&gt;
      &lt;th&gt;Lợi ích&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Kết nối cục bộ&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Mỗi neuron chỉ kết nối với một vùng nhỏ của đầu vào&lt;/td&gt;
      &lt;td&gt;Giảm mạnh số tham số&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Chia sẻ tham số&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Dùng chung một bộ trọng số lọc ở mọi vị trí&lt;/td&gt;
      &lt;td&gt;Đảm bảo tính bất biến tịnh tiến&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Đặc trưng phân cấp&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Trích xuất dần từ mức thấp → trung bình → cao&lt;/td&gt;
      &lt;td&gt;Biểu diễn đối tượng theo cấu trúc thành phần&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Gộp (&lt;em&gt;pooling&lt;/em&gt;)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Giảm kích thước không gian bằng max hoặc average&lt;/td&gt;
      &lt;td&gt;Tăng độ ổn định trước dịch chuyển nhỏ&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;lộ-trình-chương&quot;&gt;Lộ trình Chương&lt;/h2&gt;

&lt;p&gt;Chương này gồm hai phần chính:&lt;/p&gt;

&lt;h3 id=&quot;04-01-tầng-tích-chập&quot;&gt;04-01: Tầng Tích chập&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Phân biệt tích chập và tương quan chéo (&lt;em&gt;cross-correlation&lt;/em&gt;)&lt;/li&gt;
  &lt;li&gt;Tích chập đa kênh&lt;/li&gt;
  &lt;li&gt;Công thức tính kích thước đầu ra và số tham số&lt;/li&gt;
  &lt;li&gt;Phát hiện cạnh và hệ thống phân cấp đặc trưng&lt;/li&gt;
  &lt;li&gt;Cài đặt bằng NumPy và PyTorch&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;04-02-tầng-gộp-và-kiến-trúc-cnn&quot;&gt;04-02: Tầng Gộp và Kiến trúc CNN&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Max pooling, average pooling và global average pooling&lt;/li&gt;
  &lt;li&gt;Các kiến trúc kinh điển: LeNet, AlexNet, VGG, ResNet&lt;/li&gt;
  &lt;li&gt;Kết nối dư (&lt;em&gt;residual connections&lt;/em&gt;) và vai trò của độ sâu&lt;/li&gt;
  &lt;li&gt;Cài đặt một mạng CNN hoàn chỉnh&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;kiến-thức-nền-cần-có&quot;&gt;Kiến thức Nền cần có&lt;/h2&gt;

&lt;p&gt;Trước khi học CNN, bạn nên nắm vững:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đại số tuyến tính:&lt;/strong&gt; Nhân ma trận, tích vô hướng&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cơ sở mạng neuron:&lt;/strong&gt; Lan truyền xuôi, lan truyền ngược và gradient descent&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm kích hoạt:&lt;/strong&gt; ReLU, softmax&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mất mát:&lt;/strong&gt; Cross-entropy cho bài toán phân loại&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nếu cần ôn lại các nội dung này, hãy xem lại Chương 2 và Chương 3 trước.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;các-câu-hỏi-trọng-tâm-của-chương&quot;&gt;Các Câu hỏi Trọng tâm của Chương&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tích chập là gì&lt;/strong&gt; và vì sao trong học sâu ta thường cài đặt bằng tương quan chéo?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các bộ lọc học đặc trưng như thế nào&lt;/strong&gt;, từ cạnh và kết cấu đến đối tượng hoàn chỉnh?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vì sao xếp chồng nhiều bộ lọc 3×3 nhỏ lại hiệu quả hơn một bộ lọc lớn?&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kết nối tắt (&lt;em&gt;skip connections&lt;/em&gt;) giúp huấn luyện mạng hơn 150 tầng ra sao?&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Max pooling khác gì so với average pooling?&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các kiến trúc kinh điển như ResNet được tổ chức như thế nào?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Hãy bắt đầu với phép toán nền tảng đầu tiên: tầng tích chập.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau các bài nền tảng về CNN, bạn có thể xem &lt;strong&gt;04-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về ConvNeXt, DINOv2 và các mô hình nền tảng thị giác vẫn sử dụng tích chập.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (luyện phỏng vấn):&lt;/strong&gt; Sau khi học tích chập và kiến trúc CNN, bạn có thể luyện tập tại &lt;strong&gt;04-98 Luyện phỏng vấn&lt;/strong&gt; với các câu hỏi gốc về hình học CNN và kết nối tắt; bộ câu hỏi kèm lời giải đầy đủ nằm trong &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Diễn giải trực quan phép tích chập như một phép trộn cục bộ trượt trên dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, tiếng Anh. Bài giảng tổng quan về CNN của MIT bao quát trọn mạch nội dung chương này.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[CNN là gì?&lt;/td&gt;
          &lt;td&gt;Hiểu Nhanh Mạng Nơ-ron Tích Chập [PODCAST]](https://www.youtube.com/watch?v=YlgdXkzjo3Q) — Gà AI, tiếng Việt. Giới thiệu ngắn gọn bằng tiếng Việt về cách mạng tích chập trích xuất thông tin từ ảnh.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Ở mức toán học, công thức lan truyền ngược của một mô hình Llama-405B năm 2026 hoàn toàn giống hệt quy tắc dây chuyền năm 1986. Thế nhưng nếu chạy theo kiểu ngây thơ từng dòng Python, mô hình ấy sẽ hết sạch bộ nhớ VRAM ngay ở lớp thứ 5 và tốn hàng tháng trời chờ GPU truyền dữ liệu qua lại bộ nhớ! Cuộc cách mạng thực sự của huấn luyện Deep Learning hiện đại (2022–2026) nằm ở &lt;strong&gt;góc nhìn trình biên dịch và hệ thống&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;, JAX &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt;, &lt;strong&gt;Kernel Fusion&lt;/strong&gt;, &lt;strong&gt;Gradient Checkpointing&lt;/strong&gt; và &lt;strong&gt;FlashAttention&lt;/strong&gt;—biến cùng một quy tắc dây chuyền thành mã máy siêu tốc, tiết kiệm bộ nhớ gấp nhiều lần.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-kỹ-thuật-trình-biên-dịch--hệ-thống-nâng-tầm-backpropagation&quot;&gt;Kiến thức cần nhớ: Bốn kỹ thuật Trình biên dịch &amp;amp; Hệ thống nâng tầm Backpropagation&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Biên dịch Đồ thị &amp;amp; Hợp nhất Nhân tính toán (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;, JAX &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt;, Kernel Fusion)&lt;/strong&gt;:
Thay vì đọc/ghi tensor trung gian ra bộ nhớ toàn cục (HBM) nhiều lần cho từng phép toán nhỏ (cộng, nhân, kích hoạt), trình biên dịch gộp chúng thành &lt;strong&gt;một GPU kernel duy nhất&lt;/strong&gt; chạy ngay trên bộ nhớ đệm siêu nhanh SRAM.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đánh đổi Tính toán lấy Bộ nhớ (Activation / Gradient Checkpointing)&lt;/strong&gt;:
Thay vì lưu toàn bộ \(L\) tầng kích hoạt trung gian khi forward (tốn \(O(L)\) VRAM), chỉ lưu ở các mốc cách nhau \(\sqrt{L}\) tầng và &lt;strong&gt;tính lại cục bộ&lt;/strong&gt; lúc backward—giảm bộ nhớ activation từ \(O(L)\) xuống \(O(\sqrt{L})\) với chi phí thêm chỉ ~30% thời gian tính!&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Huấn luyện Độ chính xác Hỗn hợp (Mixed Precision — BF16 / FP8)&lt;/strong&gt;:
Chạy phép nhân ma trận ở &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BF16&lt;/code&gt; (hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FP8&lt;/code&gt;) nhanh gấp 2–4 lần trên Tensor Cores, trong khi vẫn giữ bản sao trọng số gốc (&lt;em&gt;master weights&lt;/em&gt;) và phép cộng dồn ở &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FP32&lt;/code&gt; để không mất độ chính xác tích lũy.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;FlashAttention (Nhận thức Phân cấp Bộ nhớ GPU — IO-Aware Backprop)&lt;/strong&gt;:
Chia nhỏ ma trận Attention theo từng khối (&lt;em&gt;tiling&lt;/em&gt;) vừa khít SRAM và tái tính toán ma trận chú ý lúc backward thay vì ghi ma trận \(N \times N\) khổng lồ xuống HBM—giảm bộ nhớ từ \(O(N^2)\) xuống \(O(N)\) mà kết quả toán học &lt;strong&gt;chính xác 100%&lt;/strong&gt;!&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-mức-tiết-kiệm-vram-của-gradient-checkpointing-trên-mạng-100-tầng&quot;&gt;Giải thích: Tính tay mức tiết kiệm VRAM của Gradient Checkpointing trên mạng 100 tầng&lt;/h3&gt;

&lt;p&gt;Giả sử bạn huấn luyện một mạng có \(L = 100\) tầng giống nhau, mỗi tầng sinh ra tensor kích hoạt (&lt;em&gt;activation&lt;/em&gt;) nặng \(100\text{ MB}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Backpropagation tiêu chuẩn (Lưu toàn bộ kích hoạt)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Bộ nhớ VRAM cho activation: \(100 \times 100\text{ MB} = \mathbf{10{,}000\text{ MB}\; (10\text{ GB})}\).&lt;/li&gt;
      &lt;li&gt;Số lượt tính forward cho 1 bước train: \(100\) tầng.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Backpropagation có Gradient Checkpointing (đặt mốc mỗi \(\sqrt{100} = 10\) tầng)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Lưu đúng 10 mốc checkpoint (mỗi mốc \(100\text{ MB}\)): \(1{,}000\text{ MB}\).&lt;/li&gt;
      &lt;li&gt;Khi backward qua một đoạn 10 tầng, tính lại và giữ tạm tối đa 10 tầng trong đoạn đó: \(1{,}000\text{ MB}\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tổng VRAM đỉnh&lt;/strong&gt;: chỉ khoảng &lt;strong&gt;\(2{,}000\text{ MB}\; (2\text{ GB})\)&lt;/strong&gt;—&lt;strong&gt;tiết kiệm gấp 5 lần bộ nhớ VRAM!&lt;/strong&gt;&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Chi phí phải trả&lt;/strong&gt;: mỗi tầng được forward thêm 1 lần nữa (tổng thời gian 1 bước tăng khoảng 25–33%, đổi lại bạn chạy vừa mô hình lớn gấp 5 lần trên cùng một GPU!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-lan-truyền-ngược-dưới-góc-nhìn-trình-biên-dịch&quot;&gt;Tùy chọn: Lan truyền ngược dưới góc nhìn trình biên dịch&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế lý thuyết về hàm mất mát, gradient descent hay lan truyền ngược. Mục đích của bài là kết nối các thuật toán nền tảng đó với trình biên dịch và nhân tính toán (&lt;em&gt;kernel&lt;/em&gt;) dùng trong thực tế huấn luyện từ sau năm 2022.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Về bản chất toán học, lan truyền ngược vẫn là vi phân tự động chế độ ngược cho hàm mất mát vô hướng \(\mathcal{L}\). Điểm thay đổi lớn giai đoạn 2022–2026 nằm ở cách thực thi: &lt;strong&gt;đồ thị tính toán được biên dịch trước&lt;/strong&gt; — nhiều toán tử được hợp nhất (&lt;em&gt;fused&lt;/em&gt;), các giá trị kích hoạt có thể được tính lại thay vì lưu toàn bộ, và huấn luyện độ chính xác hỗn hợp (&lt;em&gt;mixed precision&lt;/em&gt;) trở thành thiết lập mặc định.&lt;/p&gt;

&lt;h2 id=&quot;1-cùng-quy-tắc-dây-chuyền-khác-cách-lập-lịch-thực-thi&quot;&gt;1. Cùng quy tắc dây chuyền, khác cách lập lịch thực thi&lt;/h2&gt;

&lt;p&gt;Nếu một lớp tính \(\mathbf{y} = f(\mathbf{x}; \theta)\), lượt ngược vẫn cần tính \(\frac{\partial \mathcal{L}}{\partial \mathbf{x}}\) và \(\frac{\partial \mathcal{L}}{\partial \theta}\). Các trình biên dịch như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;, XLA hay Triton sẽ tự động quyết định:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;những giá trị trung gian nào nên &lt;strong&gt;lưu lại&lt;/strong&gt; và những giá trị nào nên &lt;strong&gt;tính lại&lt;/strong&gt; (&lt;em&gt;activation checkpointing&lt;/em&gt;),&lt;/li&gt;
  &lt;li&gt;những phép toán theo từng phần tử nào nên &lt;strong&gt;hợp nhất&lt;/strong&gt; (&lt;em&gt;fuse&lt;/em&gt;) thành một nhân tính toán GPU duy nhất,&lt;/li&gt;
  &lt;li&gt;có thực thi phép tính ở định dạng BF16/FP8 và tích lũy ở FP32 hay không.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Toán học của Chương 03 giữ nguyên; điều thay đổi là thời gian chạy thực tế (&lt;em&gt;wall-clock time&lt;/em&gt;) và lượng bộ nhớ tiêu thụ.&lt;/p&gt;

&lt;h2 id=&quot;2-các-ứng-dụng-và-kỹ-thuật-tiêu-biểu&quot;&gt;2. Các ứng dụng và kỹ thuật tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;torchcompile-và-jax-jit&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt; và JAX &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2404.14294&quot;&gt;Ansel et al., 2024&lt;/a&gt; mô tả kiến trúc Dynamo + AOTAutograd + TorchInductor của PyTorch 2: bytecode Python được ghi nhận thành đồ thị FX rồi biên dịch xuống mã máy tối ưu cho phần cứng. JAX áp dụng tư duy tương tự thông qua &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad&lt;/code&gt;. Cả hai là lời giải trong thực tế sản xuất cho câu hỏi: “Sau khi hiểu lan truyền ngược bằng NumPy, hệ thống lớn triển khai nó như thế nào?”&lt;/p&gt;

&lt;h3 id=&quot;huấn-luyện-độ-chính-xác-hỗn-hợp-và-tỷ-lệ-hóa-mất-mát-loss-scaling&quot;&gt;Huấn luyện độ chính xác hỗn hợp và tỷ lệ hóa mất mát (&lt;em&gt;loss scaling&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Một bước cập nhật tiêu chuẩn có dạng:&lt;/p&gt;

\[\theta \leftarrow \theta - \eta \cdot \mathrm{Cast}_{fp32}(\widehat{\nabla \mathcal{L}}),\]

&lt;p&gt;trong đó \(\widehat{\nabla \mathcal{L}}\) được tính bằng BF16 hoặc FP16. Để tránh hiện tượng tràn số dưới (&lt;em&gt;underflow&lt;/em&gt;) ở FP16, giá trị hàm mất mát thường được nhân thêm một hệ số trước khi chạy lượt ngược (cơ chế AMP trong PyTorch). Bản chất cập nhật SGD/Adam không đổi, chỉ bổ sung chính sách quản lý định dạng dấu phẩy động.&lt;/p&gt;

&lt;h3 id=&quot;lượt-ngược-mức-kernel-cho-attention&quot;&gt;Lượt ngược mức kernel cho attention&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;Dao et al., 2022&lt;/a&gt; (FlashAttention) thiết kế &lt;strong&gt;lượt ngược tối ưu truy cập bộ nhớ (IO-aware)&lt;/strong&gt; mà không cần lưu tường minh ma trận attention kích thước \(N\times N\). Đạo hàm của softmax-attention vẫn giống hệt công thức lý thuyết ở Chương 07, nhưng phần cài đặt là một nhân tính toán lượt ngược đã hợp nhất xử lý theo từng khối nhỏ (&lt;em&gt;tiling&lt;/em&gt;). Đây là một trong những cải tiến kỹ thuật quan trọng nhất về lan truyền ngược trong giai đoạn gần đây.&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-công-cụ-phổ-biến&quot;&gt;3. Thư viện và công cụ phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://pytorch.org/&quot;&gt;PyTorch 2&lt;/a&gt; — &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.func&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.utils.checkpoint&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX&lt;/a&gt; — &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;value_and_grad&lt;/code&gt;, trình biên dịch XLA.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/triton-lang/triton&quot;&gt;Triton&lt;/a&gt; — ngôn ngữ viết nhân GPU tùy chỉnh cho lượt xuôi/ngược khi trình biên dịch mặc định chưa đủ tối ưu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2404.14294&quot;&gt;PyTorch 2 (Ansel et al., 2024)&lt;/a&gt; — ghi nhận đồ thị động kết hợp autograd biên dịch.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;FlashAttention (Dao et al., 2022)&lt;/a&gt; — tính chính xác gradient attention với lượt ngược chia khối tiết kiệm băng thông bộ nhớ.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1805.02867&quot;&gt;Online softmax (Milakov &amp;amp; Gimelshein, 2018)&lt;/a&gt; — thuật toán softmax trực tuyến dùng bên trong các kernel này và vẫn là nền tảng số học phổ biến giai đoạn 2024–2026.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-mối-liên-hệ-với-các-bài-học-cốt-lõi&quot;&gt;5. Mối liên hệ với các bài học cốt lõi&lt;/h2&gt;

&lt;p&gt;Nên hoàn thành phần lý thuyết lan truyền ngược và cài đặt bằng NumPy trước. Bài này chỉ bổ sung lớp hạ tầng kỹ thuật mà ngành công nghiệp đặt xung quanh thuật toán cốt lõi — trình biên dịch, AMP và kernel lượt ngược hợp nhất — chứ không thay đổi bản chất toán học của quá trình học.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Ôn lại quy tắc dây chuyền cốt lõi — phần không đổi dù lớp biên dịch và tối ưu thực thi bên dưới có thay đổi.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Giới thiệu Adam — bộ tối ưu mặc định thường dùng song song với các kỹ thuật huấn luyện hiện đại.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, tiếng Anh. So sánh tổng quan Momentum, RMSprop, AdaGrad và Adam trong cùng một khung nhìn.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-98 Luyện phỏng vấn (autodiff, Hessian, logistic)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Trong các vòng phỏng vấn chuyên sâu về Deep Learning và Machine Learning, ba chủ đề &lt;strong&gt;Tự động tính đạo hàm (Autodiff)&lt;/strong&gt;, &lt;strong&gt;Ma trận Hessian (độ cong bậc hai)&lt;/strong&gt; và &lt;strong&gt;Hồi quy Logistic&lt;/strong&gt; xuất hiện dày đặc đến mức gần như trở thành “bài thi nhập môn bắt buộc”. Tại sao? Bởi vì hồi quy logistic là trường hợp nhỏ nhất, trong suốt nhất của mạng nơ-ron, nơi bạn có thể tự tay chứng minh tính lồi toàn cục của Cross-Entropy, giải thích ý nghĩa log-odds và tính trọn vẹn cả gradient lẫn ma trận Hessian chỉ trên một trang giấy!&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trọng-tâm-phỏng-vấn-của-chương-03&quot;&gt;Kiến thức cần nhớ: Bốn trọng tâm Phỏng vấn của Chương 03&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Autodiff (Chế độ Tiến vs. Chế độ Lùi — Forward vs. Reverse Mode)&lt;/strong&gt;:
Với hàm \(f: \mathbb{R}^n \to \mathbb{R}^m\): Forward-mode tính nhanh khi \(n \ll m\) (ít biến vào, nhiều đầu ra); Reverse-mode (Backprop) tính nhanh khi \(n \gg m\) (hàng triệu trọng số \(\to\) 1 giá trị loss vô hướng).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Gradient và Tính Lồi của Hồi quy Logistic&lt;/strong&gt;:
Đạo hàm âm log-likelihood theo \(\mathbf{w}\) là \(\nabla_{\mathbf{w}} L = \frac{1}{N}\mathbf{X}^\top(\hat{\mathbf{y}} - \mathbf{y})\); ma trận Hessian là \(\mathbf{H} = \frac{1}{N}\mathbf{X}^\top \mathbf{D} \mathbf{X}\) với \(D_{ii} = \hat{y}_i(1 - \hat{y}_i) &amp;gt; 0\), luôn nửa xác định dương \(\implies\) hàm mất mát &lt;strong&gt;lồi toàn cục&lt;/strong&gt;, không bao giờ có cực tiểu địa phương xấu!&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ý nghĩa Odds và Log-Odds (Logit)&lt;/strong&gt;:
Từ \(p = \frac{1}{1+e^{-z}}\) suy ra \(\ln\frac{p}{1-p} = \mathbf{w}^\top\mathbf{x} + b\): tăng đặc trưng \(x_j\) thêm 1 đơn vị sẽ nhân tỷ lệ cược (&lt;em&gt;odds&lt;/em&gt;) \(\frac{p}{1-p}\) lên đúng \(e^{w_j}\) lần.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân biệt Độ cong Hessian &amp;amp; Phương pháp Newton&lt;/strong&gt;:
Dấu của các giá trị riêng Hessian phân loại tức thì điểm dừng: toàn dương (cực tiểu), toàn âm (cực đại), lẫn lộn dương và âm (&lt;strong&gt;điểm yên ngựa&lt;/strong&gt;).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-chứng-minh-tay-tính-nửa-xác-định-dương-của-hessian-hồi-quy-logistic-trên-2-mẫu&quot;&gt;Giải thích: Chứng minh tay tính nửa xác định dương của Hessian Hồi quy Logistic trên 2 mẫu&lt;/h3&gt;

&lt;p&gt;Xét 2 mẫu 1 chiều \(x_1 = 1, x_2 = 2\) với dự đoán xác suất hiện tại \(\hat{y}_1 = 0.5, \hat{y}_2 = 0.8\) (bỏ qua bias):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính các phần tử đường chéo \(D_{ii} = \hat{y}_i(1 - \hat{y}_i)\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(D_{11} = 0.5(1 - 0.5) = 0.25 &amp;gt; 0\).&lt;/li&gt;
      &lt;li&gt;\(D_{22} = 0.8(1 - 0.8) = 0.16 &amp;gt; 0\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính Hessian (ở 1 chiều là đạo hàm bậc hai \(L&apos;&apos;(w)\))&lt;/strong&gt;:
\(H = \frac{1}{2}\big(x_1^2 D_{11} + x_2^2 D_{22}\big) = \frac{1}{2}\big(1^2(0.25) + 2^2(0.16)\big) = \frac{1}{2}(0.25 + 0.64) = \mathbf{0.445 &amp;gt; 0}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng quát hóa cho mọi vector \(\mathbf{v} \in \mathbb{R}^d\)&lt;/strong&gt;:
\(\mathbf{v}^\top \mathbf{H} \mathbf{v} = \frac{1}{N}\sum_{i=1}^N \underbrace{\hat{y}_i(1-\hat{y}_i)}_{&amp;gt; 0}\,\underbrace{(\mathbf{x}_i^\top \mathbf{v})^2}_{\ge 0} \ge 0.\)
Chỉ bằng đúng 3 dòng đại số ấy, bạn đã chứng minh chặt chẽ trước người phỏng vấn rằng Hồi quy Logistic với Cross-Entropy &lt;strong&gt;luôn lồi toàn cục&lt;/strong&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-luyện-phỏng-vấn--autodiff-hessian-và-hồi-quy-logistic&quot;&gt;Tùy chọn: Luyện phỏng vấn — Autodiff, Hessian và Hồi quy Logistic&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; thay thế phần lý thuyết về hàm mất mát, gradient descent hay lan truyền ngược. Sau khi học các bài chính trong chương, bạn có thể luyện với bộ câu hỏi dưới đây rồi mở &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) để tham khảo thêm các câu hỏi kèm lời giải đầy đủ về vi phân tự động, độ cong và hồi quy logistic.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Chủ đề tham khảo trong sách cho chương này (đọc trực tiếp trong bản PDF):&lt;/strong&gt; vi phân tự động, trực giác về ma trận Hessian và phân loại logistic / log-odds.&lt;/p&gt;

&lt;p&gt;Trang tổng hợp: &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;câu-hỏi-luyện-tập&quot;&gt;Câu hỏi luyện tập&lt;/h2&gt;

&lt;h3 id=&quot;q1-gradient-của-hồi-quy-logistic&quot;&gt;Q1. Gradient của hồi quy logistic&lt;/h3&gt;

&lt;p&gt;Mô hình hồi quy logistic nhị phân dự đoán \(\hat y=\sigma(\mathbf{w}^\top\mathbf{x})\) và dùng hàm mất mát \(\ell= -y\log\hat y-(1-y)\log(1-\hat y)\). Hãy chứng minh:&lt;/p&gt;

\[\nabla_{\mathbf{w}}\ell = (\hat y-y)\,\mathbf{x}.\]

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Sử dụng \(\sigma&apos;(z)=\sigma(z)(1-\sigma(z))\) và quy tắc dây chuyền từ Chương 00 hoặc bài lan truyền ngược.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Đặt \(z=\mathbf{w}^\top\mathbf{x}\). Khi đó \(\partial\ell/\partial z = -\frac{y}{\hat y}\sigma&apos;(z)+\frac{1-y}{1-\hat y}\sigma&apos;(z)\). Thay \(\sigma&apos;(z)=\hat y(1-\hat y)\) vào, các thừa số ở mẫu triệt tiêu và biểu thức rút gọn thành \(\hat y-y\). Nhân tiếp với \(\partial z/\partial\mathbf{w}=\mathbf{x}\) ta thu được kết quả cần chứng minh. Đây cũng là lý do phép kết hợp “sigmoid + BCE” ổn định hơn về mặt số học khi được gộp chung (&lt;em&gt;fused&lt;/em&gt;): ta không cần tính tách rời \(\sigma&apos;(z)\) vốn dễ bị tràn số dưới (&lt;em&gt;underflow&lt;/em&gt;).&lt;/p&gt;

&lt;h3 id=&quot;q2-odds-log-odds-và-ý-nghĩa-của-hệ-số&quot;&gt;Q2. Odds, log-odds và ý nghĩa của hệ số&lt;/h3&gt;

&lt;p&gt;Một mô hình hồi quy logistic học được \(z = -1 + 2\,x_{\mathrm{smoke}}\) với \(x_{\mathrm{smoke}}\in\{0,1\}\). Tỷ lệ odds của biến cố \(y=1\) đối với người không hút thuốc và người hút thuốc là bao nhiêu? Hệ số \(2\) có ý nghĩa gì trên thang log-odds?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Odds được định nghĩa là \(\hat y/(1-\hat y)=e^{z}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Với người không hút thuốc (\(x_{\mathrm{smoke}}=0\)): \(z=-1\), odds bằng \(e^{-1}\approx 0.37\). Với người hút thuốc (\(x_{\mathrm{smoke}}=1\)): \(z=1\), odds bằng \(e^{1}\approx 2.72\). Hệ số \(2\) chính là &lt;em&gt;log của tỷ số odds&lt;/em&gt; (&lt;em&gt;log-odds ratio&lt;/em&gt;) gắn với đặc trưng nhị phân này: việc hút thuốc làm odds nhân lên \(e^{2}\approx 7.4\) lần. Câu hỏi này thường dùng để kiểm tra xem ứng viên có tránh được sai lầm coi trọng số logistic là tác động cộng tuyến tính lên xác suất hay không.&lt;/p&gt;

&lt;h3 id=&quot;q3-chế-độ-xuôi-và-chế-độ-ngược-trên-đồ-thị-nhỏ&quot;&gt;Q3. Chế độ xuôi và chế độ ngược trên đồ thị nhỏ&lt;/h3&gt;

&lt;p&gt;Giả sử cần tính \(\partial f/\partial x\) và \(\partial f/\partial y\) cho hàm \(f=(x y)+ \sin(x)\). Hãy so sánh chi phí tính toán (số phép nhân vô hướng và phép gọi hàm lượng giác) giữa (a) hai lượt chế độ xuôi (&lt;em&gt;forward mode&lt;/em&gt;) và (b) một lượt chế độ ngược (&lt;em&gt;reverse mode&lt;/em&gt;). Nếu \(f\) là hàm mất mát của một mạng 50 lớp với hàng triệu trọng số, bạn sẽ chọn chế độ nào?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Chế độ xuôi khởi tạo đạo hàm ở một đầu vào; chế độ ngược khởi tạo đạo hàm ở đầu ra.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Với hai lượt chế độ xuôi, ta chạy riêng một lượt cho \(x\) và một lượt cho \(y\), mỗi lượt đều phải đánh giá lại \(xy\) và \(\sin x\). Với một lượt chế độ ngược, ta chỉ cần một lượt xuôi lưu các giá trị trung gian rồi truyền ngược tín hiệu đạo hàm (&lt;em&gt;adjoint&lt;/em&gt;) qua các phép toán \(+\), \(\times\) và \(\sin\) để thu đồng thời cả hai đạo hàm. Khi hàm mất mát là một số vô hướng còn số tham số \(\mathbf{w}\) rất lớn, chế độ ngược (lan truyền ngược) là lựa chọn thực tế duy nhất — đây là trọng tâm của Chương 03. Chế độ xuôi chỉ có lợi khi số đầu vào rất ít nhưng số đầu ra rất nhiều (ví dụ tính ma trận Jacobian của một ánh xạ từ ít biến sang vector nhiều chiều).&lt;/p&gt;

&lt;h3 id=&quot;q4-ma-trận-hessian-của-hồi-quy-logistic-và-tính-lồi&quot;&gt;Q4. Ma trận Hessian của hồi quy logistic và tính lồi&lt;/h3&gt;

&lt;p&gt;Với một mẫu dữ liệu, xét \(\ell(\mathbf{w})= -y\log\sigma(\mathbf{w}^\top\mathbf{x})-(1-y)\log\bigl(1-\sigma(\mathbf{w}^\top\mathbf{x})\bigr)\). Hãy chứng minh ma trận Hessian:&lt;/p&gt;

\[\nabla^2_{\mathbf{w}}\ell = \hat y(1-\hat y)\,\mathbf{x}\mathbf{x}^\top\]

&lt;p&gt;là nửa xác định dương (&lt;em&gt;positive semi-definite&lt;/em&gt;). Điều này cho biết gì về cực tiểu cục bộ của hồi quy logistic không có chính quy hóa?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Với mọi vector \(\mathbf{v}\), ta có \(\mathbf{v}^\top(\mathbf{x}\mathbf{x}^\top)\mathbf{v}=(\mathbf{v}^\top\mathbf{x})^2\ge 0\) và \(\hat y(1-\hat y)\in(0,1)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Vì Hessian là tích của một số dương với ma trận nửa xác định dương hạng 1 nên \(\ell(\mathbf{w})\) là hàm lồi theo \(\mathbf{w}\). Tổng các hàm lồi trên toàn tập dữ liệu vẫn là hàm lồi, do đó mọi cực tiểu cục bộ đều là cực tiểu toàn cục. Nếu cộng thêm hạng tử chính quy hóa L2 \(\tfrac{\lambda}{2}\|\mathbf{w}\|_2^2\) với \(\lambda&amp;gt;0\), Hessian trở thành xác định dương chặt và bài toán có nghiệm cực tiểu duy nhất. Khi ghép thêm các lớp ẩn phi tuyến trong mạng sâu, tính lồi này không còn được bảo toàn.&lt;/p&gt;

&lt;h3 id=&quot;q5-ma-trận-hessian-dưới-góc-độ-chẩn-đoán&quot;&gt;Q5. Ma trận Hessian dưới góc độ chẩn đoán&lt;/h3&gt;

&lt;p&gt;Hãy nêu một hiện tượng khi huấn luyện có thể giải thích bằng phần tử &lt;em&gt;đường chéo&lt;/em&gt; của ma trận Hessian (hoặc moment bậc hai theo từng tham số), và một lý do khiến ta không chạy phương pháp Newton đầy đủ trên các mạng CNN hiện đại.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Liên hệ khái niệm “hướng dốc và hướng phẳng” từ Q5 Chương 00 cùng độ phức tạp lưu trữ \(n_{\mathrm{params}}^2\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Một phần tử đường chéo lớn cho thấy hàm mất mát có độ cong rất gắt theo tọa độ đó: một tốc độ học phù hợp cho các hướng phẳng hơn sẽ dễ gây dao động hoặc vượt quá cực tiểu theo hướng này — đây là động lực cho các bộ tối ưu thích nghi như RMSprop và Adam (Chương 10). Phương pháp Newton đầy đủ đòi hỏi tạo và giải hệ phương trình tuyến tính với ma trận Hessian kích thước \(P\times P\); với hàng triệu tham số, ngay cả việc lưu trữ ma trận này cũng bất khả thi, và kể cả phép nhân Hessian–vector cũng chỉ được dùng trong các tình huống chuyên biệt chứ không làm bước cập nhật mặc định.&lt;/p&gt;

&lt;h2 id=&quot;ghi-công&quot;&gt;Ghi công&lt;/h2&gt;

&lt;p&gt;Kashani, S., và Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Bạn có thể tải bản PDF từ arXiv để xem đầy đủ bộ câu hỏi và lời giải. Trang này là bài luyện tập gốc của khóa học, không phải bản sao chép từ sách.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Hữu ích cho các câu hỏi về vi phân tự động (autodiff).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Backpropagation calculus&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 4](https://www.youtube.com/watch?v=tIeHLnjs5U8) — 3Blue1Brown, tiếng Anh. Ôn lại quy tắc dây chuyền vô hướng cần dùng khi chứng minh các công thức đạo hàm.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yIYKR4sgzI8&quot;&gt;StatQuest: Logistic Regression&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Ôn lại hồi quy logistic — nhóm chủ đề thứ ba trong bài luyện này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-04 Kỹ thuật Huấn luyện Thực tế</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_04_Training_Techniques/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_04_Training_Techniques</id>
   <content type="html">&lt;p&gt;Hai kỹ sư cùng dùng một kiến trúc mạng y hệt nhau và cùng một tập dữ liệu, nhưng người thứ nhất đạt độ chính xác 96% chỉ sau 15 epoch còn người thứ hai mãi dậm chân ở 50% hoặc vọt lỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;. Sự khác biệt không nằm ở công thức mới lạ nào, mà nằm ở &lt;strong&gt;kỹ thuật huấn luyện thực tế&lt;/strong&gt;: cách khởi tạo trọng số ban đầu, cách chuẩn hóa dữ liệu tránh rò rỉ (&lt;em&gt;data leakage&lt;/em&gt;), cách chọn batch size và cách đọc biểu đồ loss để dừng đúng lúc. Mục tổng quan này mở đầu hai bài thực chiến giúp biến kiến thức lý thuyết thành mô hình chạy ổn định ngoài đời thực.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-của-kỹ-thuật-huấn-luyện-thực-tế&quot;&gt;Kiến thức cần nhớ: Ba trụ cột của Kỹ thuật Huấn luyện Thực tế&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Khởi tạo Trọng số &amp;amp; Tiền xử lý Sạch (Initialization &amp;amp; Preprocessing)&lt;/strong&gt;:
Dùng Xavier cho Sigmoid/Tanh và He/Kaiming cho ReLU để giữ phương sai tín hiệu ổn định; luôn tính tham số chuẩn hóa (\(\mu, \sigma\)) &lt;strong&gt;chỉ trên tập Train&lt;/strong&gt; rồi mới áp dụng lên Validation và Test.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Chiến lược Chia tập &amp;amp; Chọn Batch Size (Train / Val / Test Split)&lt;/strong&gt;:
Tách bạch rạch ròi vai trò của 3 tập: Train để cập nhật trọng số, Validation để chọn siêu tham số và kiến trúc, và Test giữ kín tuyệt đối cho lần đánh giá cuối cùng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Giám sát Đường cong Học &amp;amp; Dừng sớm (Monitoring &amp;amp; Early Stopping)&lt;/strong&gt;:
Đọc bệnh của mô hình qua khoảng cách giữa &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train_loss&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;val_loss&lt;/code&gt;, lưu lại &lt;em&gt;checkpoint&lt;/em&gt; tốt nhất và dừng huấn luyện ngay khi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;val_loss&lt;/code&gt; ngừng cải thiện trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;patience&lt;/code&gt; epoch liên tiếp.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-bảng-chẩn-đoán-nhanh-4-triệu-chứng-đường-cong-loss-khi-huấn-luyện&quot;&gt;Giải thích: Bảng chẩn đoán nhanh 4 triệu chứng đường cong Loss khi huấn luyện&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Triệu chứng quan sát được&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Nguyên nhân gốc rễ khả năng cao nhất&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hành động xử lý ưu tiên&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Cả Train Loss và Val Loss đều cao &amp;amp; đi ngang&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Underfitting, learning rate quá nhỏ, hoặc bug code&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Kiểm tra lại phép thử overfit 1 batch, tăng dung lượng mạng hoặc tăng learning rate&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Train Loss giảm sâu nhưng Val Loss quay đầu tăng&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Overfitting&lt;/strong&gt; (mô hình học thuộc nhiễu tập train)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bật Early Stopping, thêm Regularization (Dropout, Weight Decay), tăng dữ liệu / Data Augmentation&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Loss dao động dữ dội hoặc bùng thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Learning rate quá lớn, chưa chuẩn hóa dữ liệu, hoặc chia 0&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Hạ learning rate 5–10 lần, bật Gradient Clipping, kiểm tra chuẩn hóa đầu vào&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Val Loss thấp hơn Train Loss một chút ở đầu&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bình thường khi đang bật Dropout mạnh lúc train (tắt lúc val)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Tiếp tục theo dõi; không phải lỗi!&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Phần này tổng hợp các kỹ thuật thực tế giúp huấn luyện mạng neuron ổn định và hiệu quả:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Khởi tạo, tiền xử lý, batch và chia tập&lt;/strong&gt; — khởi tạo trọng số, chuẩn hóa đặc trưng, tạo mini-batch và chia train/validation/test&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giám sát, dừng sớm và vòng lặp huấn luyện&lt;/strong&gt; — theo dõi chỉ số, dừng sớm (&lt;em&gt;early stopping&lt;/em&gt;), cắt ngưỡng gradient và tinh chỉnh siêu tham số&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Lecture 6&lt;/td&gt;
          &lt;td&gt;Training Neural Networks I](https://www.youtube.com/watch?v=wEoyxE0GP2M) — Stanford University School of Engineering, tiếng Anh. Trình bày các bước chuẩn bị huấn luyện: khởi tạo trọng số, tiền xử lý và chia batch.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 7&lt;/td&gt;
          &lt;td&gt;Training Neural Networks II](https://www.youtube.com/watch?v=_JB0AO7QxSA) — Stanford University School of Engineering, tiếng Anh. Phần tiếp nối bàn về tối ưu hóa, chính quy hóa và theo dõi quá trình huấn luyện.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Zi-0rlM4RDs&quot;&gt;Train, Test, &amp;amp; Validation Sets explained&lt;/a&gt; — deeplizard, tiếng Anh. Giải thích vai trò của ba tập train, validation và test trong quy trình chuẩn bị dữ liệu.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-04-02 Giám sát, Dừng sớm và Vòng lặp Huấn luyện</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_04_02_Monitoring_and_Training_Loop/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_04_02_Monitoring_and_Training_Loop</id>
   <content type="html">&lt;p&gt;Huấn luyện một mạng nơ-ron mà không theo dõi biểu đồ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train_loss&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;val_loss&lt;/code&gt; và chuẩn gradient giống như lái máy bay xuyên mây mà tắt toàn bộ bảng đồng hồ buồng lái: bạn không biết mình đang tăng độ cao êm đẹp hay sắp lao xuống đất. Nhiều mô hình đạt đỉnh hiệu năng ở epoch 18, nhưng vì người chạy cứ để mặc tới epoch 100 nên mô hình học vẹt hoàn toàn tập huấn luyện và tụt dốc không phanh trên tập thật. Bài học này hướng dẫn bạn xây dựng một &lt;strong&gt;vòng lặp huấn luyện chuyên nghiệp&lt;/strong&gt; với hệ thống giám sát chỉ số, lưu checkpoint tốt nhất và cơ chế &lt;strong&gt;Dừng sớm (&lt;em&gt;Early Stopping&lt;/em&gt;)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-thành-phần-của-vòng-lặp-huấn-luyện-chuyên-nghiệp&quot;&gt;Kiến thức cần nhớ: Bốn thành phần của Vòng lặp Huấn luyện Chuyên nghiệp&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tách biệt Chế độ Huấn luyện (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.train()&lt;/code&gt;) và Đánh giá (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.no_grad()&lt;/code&gt;)&lt;/strong&gt;:
Lúc đánh giá bắt buộc chuyển sang &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval()&lt;/code&gt; để tắt Dropout và khóa thống kê chạy (&lt;em&gt;running stats&lt;/em&gt;) của BatchNorm, đồng thời bọc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.no_grad()&lt;/code&gt; để không tốn VRAM lưu đồ thị đạo hàm.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Bộ chỉ số Giám sát Đa chiều (Metrics &amp;amp; Diagnostics)&lt;/strong&gt;:
Không chỉ nhìn Loss: theo dõi song song Accuracy/F1/MAE, learning rate hiện hành, và chuẩn \(L_2\) của gradient (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad_norm&lt;/code&gt;) để phát hiện sớm dấu hiệu bùng nổ hay bão hòa.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Dừng sớm (Early Stopping) với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;patience&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min_delta&lt;/code&gt;&lt;/strong&gt;:
Theo dõi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_val_loss&lt;/code&gt;; mỗi khi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;val_loss&lt;/code&gt; cải thiện ít nhất &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min_delta&lt;/code&gt;, lưu lại trọng số (&lt;em&gt;model checkpoint&lt;/em&gt;) và reset bộ đếm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;counter = 0&lt;/code&gt;. Nếu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;counter&lt;/code&gt; chạm ngưỡng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;patience&lt;/code&gt;, dừng sớm và nạp lại bản trọng số tốt nhất.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tính Tái lập Thực nghiệm (Reproducibility &amp;amp; Logging)&lt;/strong&gt;:
Cố định hạt giống ngẫu nhiên (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;seed&lt;/code&gt;), ghi nhật ký đầy đủ siêu tham số và biểu đồ học (TensorBoard / Weights &amp;amp; Biases) để mọi kết quả tốt đều có thể lặp lại chính xác.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-mô-phỏng-tay-cơ-chế-early-stopping-với-patience--3-min_delta--001&quot;&gt;Giải thích: Mô phỏng tay cơ chế Early Stopping với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;patience = 3&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min_delta = 0.01&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;Theo dõi chuỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;val_loss&lt;/code&gt; qua 9 epoch liên tiếp để thấy chính xác thời điểm lưu checkpoint và thời điểm dừng:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Epoch&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;val_loss&lt;/code&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;So với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_loss - 0.01&lt;/code&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hành động&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_loss&lt;/code&gt;&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;counter&lt;/code&gt;&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;1&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.85&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Cải thiện lần đầu&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Lưu checkpoint (Epoch 1)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.85&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;2&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.62&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.62 &amp;lt; 0.84&lt;/code&gt; (Tốt hơn)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Lưu checkpoint (Epoch 2)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.62&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;3&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.48&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.48 &amp;lt; 0.61&lt;/code&gt; (Tốt hơn)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Lưu checkpoint (Epoch 3)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.48&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;4&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.475&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.475 &amp;gt;= 0.47&lt;/code&gt; (Cải thiện quá nhỏ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt; 0.01&lt;/code&gt;)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Không lưu, tăng bộ đếm&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.48&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;5&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.45&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.45 &amp;lt; 0.47&lt;/code&gt; (Tốt hơn!)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Lưu checkpoint (Epoch 5)&lt;/strong&gt;, reset&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.45&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;6&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.46&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Tăng nhẹ&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Tăng bộ đếm&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.45&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;7&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.49&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Tiếp tục tăng (overfitting)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Tăng bộ đếm&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.45&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;8&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.52&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Tăng liên tiếp 3 lần&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;counter == 3&lt;/code&gt; \(\to\) &lt;strong&gt;DỪNG SỚM!&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.45&lt;/code&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Sau khi dừng ở Epoch 8, ta &lt;strong&gt;không dùng&lt;/strong&gt; trọng số Epoch 8 (đang có &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;val_loss = 0.52&lt;/code&gt;), mà nạp lại bản checkpoint tốt nhất ở &lt;strong&gt;Epoch 5&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;val_loss = 0.45&lt;/code&gt;) để đánh giá trên tập Test!&lt;/p&gt;

&lt;h2 id=&quot;giám-sát-quá-trình-huấn-luyện&quot;&gt;Giám sát Quá trình Huấn luyện&lt;/h2&gt;

&lt;h3 id=&quot;các-chỉ-số-cần-theo-dõi&quot;&gt;Các Chỉ số Cần Theo dõi&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mất mát huấn luyện (&lt;em&gt;training loss&lt;/em&gt;):&lt;/strong&gt; Cần giảm ổn định qua các epoch.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mất mát kiểm định (&lt;em&gt;validation loss&lt;/em&gt;):&lt;/strong&gt; Cần giảm song hành; nếu quay đầu tăng trong khi mất mát huấn luyện vẫn giảm, mô hình đang bị quá khớp (&lt;em&gt;overfitting&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ chính xác huấn luyện (&lt;em&gt;training accuracy&lt;/em&gt;):&lt;/strong&gt; Cần tăng dần.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ chính xác kiểm định (&lt;em&gt;validation accuracy&lt;/em&gt;):&lt;/strong&gt; Cần tăng theo; khoảng cách lớn giữa độ chính xác huấn luyện và kiểm định là dấu hiệu rõ rệt của quá khớp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;trực-quan-hóa-lịch-sử-huấn-luyện&quot;&gt;Trực quan hóa Lịch sử Huấn luyện&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;plot_training_history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vẽ lịch sử huấn luyện&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Biểu đồ mất mát
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Validation Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training and Validation Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Biểu đồ độ chính xác
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Validation Accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training and Validation Accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;dừng-sớm-early-stopping&quot;&gt;Dừng sớm (Early Stopping)&lt;/h2&gt;

&lt;p&gt;Kỹ thuật này dừng huấn luyện khi mất mát trên tập kiểm định ngừng cải thiện sau một số epoch chờ (&lt;em&gt;patience&lt;/em&gt;) và khôi phục lại bộ tham số tốt nhất đã lưu.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;EarlyStopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_delta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        patience: số epoch chờ trước khi dừng
        min_delta: thay đổi tối thiểu để coi là cải thiện
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_delta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_delta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;early_stop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__call__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_loss&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_delta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;EarlyStopping counter: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;early_stop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;early_stop&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sử dụng trong vòng lặp huấn luyện
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;early_stopping&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;EarlyStopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Huấn luyện...
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_one_epoch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(...)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;validate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(...)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;early_stopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Early stopping triggered!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;early_stopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_parameters&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;cắt-ngưỡng-gradient-gradient-clipping&quot;&gt;Cắt ngưỡng Gradient (Gradient Clipping)&lt;/h2&gt;

&lt;p&gt;Giúp hạn chế hiện tượng gradient bùng nổ bằng cách giới hạn biên độ hoặc chuẩn của vector gradient.&lt;/p&gt;

&lt;h3 id=&quot;cắt-theo-giá-trị&quot;&gt;Cắt theo Giá trị&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;clip_gradients_by_value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cắt gradient về [-max_value, max_value]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;keys&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;cắt-theo-chuẩn-toàn-cục&quot;&gt;Cắt theo Chuẩn Toàn cục&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;clip_gradients_by_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_norm&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cắt gradient theo chuẩn toàn cục&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Tính chuẩn toàn cục
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;total_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;total_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Cắt nếu cần
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;clip_coef&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clip_coef&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clip_coef&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;vòng-lặp-huấn-luyện-hoàn-chỉnh&quot;&gt;Vòng lặp Huấn luyện Hoàn chỉnh&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;initialization&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;he&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;early_stopping_patience&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Hàm huấn luyện đầy đủ với mọi thực hành tốt nhất
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Khởi tạo
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;initialize_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;early_stopping&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;EarlyStopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;early_stopping_patience&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Lịch sử
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Vòng lặp huấn luyện
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Tạo mini-batch
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Xử lý mỗi mini-batch
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Lan truyền xuôi
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward_propagation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Tính chi phí
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;batch_cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;compute_cost&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_cost&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Lan truyền ngược
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward_propagation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Gradient clipping (tùy chọn)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;clip_gradients_by_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_norm&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật tham số
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;update_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Mất mát trung bình trên mọi batch
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính độ chính xác huấn luyện
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;train_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Kiểm định
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;val_predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward_propagation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;compute_cost&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;val_pred_labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_pred_labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# In tiến độ
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;or&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
                  &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Train Loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Train Acc: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
                  &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Val Loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Val Acc: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Dừng sớm
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;early_stopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Early stopping at epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;early_stopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_parameters&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Vẽ lịch sử
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;plot_training_history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;tinh-chỉnh-siêu-tham-số&quot;&gt;Tinh chỉnh Siêu tham số&lt;/h2&gt;

&lt;h3 id=&quot;các-siêu-tham-số-quan-trọng&quot;&gt;Các Siêu tham số Quan trọng&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tốc độ học (&lt;em&gt;learning rate&lt;/em&gt;)&lt;/strong&gt; — thường có ảnh hưởng lớn nhất&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kích thước batch (&lt;em&gt;batch size&lt;/em&gt;)&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Số lượng lớp&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Số neuron mỗi lớp&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm kích hoạt&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương pháp khởi tạo trọng số&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;các-chiến-lược-tìm-kiếm&quot;&gt;Các Chiến lược Tìm kiếm&lt;/h3&gt;

&lt;h4 id=&quot;1-thử-nghiệm-thủ-công&quot;&gt;1. Thử nghiệm Thủ công&lt;/h4&gt;

&lt;p&gt;Điều chỉnh dần các giá trị dựa trên kinh nghiệm và quan sát đường cong huấn luyện.&lt;/p&gt;

&lt;h4 id=&quot;2-tìm-kiếm-lưới-grid-search&quot;&gt;2. Tìm kiếm Lưới (&lt;em&gt;Grid Search&lt;/em&gt;)&lt;/h4&gt;

&lt;p&gt;Thử toàn bộ các tổ hợp có thể từ một tập giá trị định trước.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;learning_rates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;batch_sizes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;best_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;history&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                     &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Độ chính xác kiểm định cuối
&lt;/span&gt;        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;best_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Best: LR=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, BS=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Val Acc=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;3-tìm-kiếm-ngẫu-nhiên-random-search&quot;&gt;3. Tìm kiếm Ngẫu nhiên (&lt;em&gt;Random Search&lt;/em&gt;)&lt;/h4&gt;

&lt;p&gt;Lấy mẫu ngẫu nhiên trong không gian siêu tham số — thường hiệu quả hơn grid search khi có nhiều siêu tham số với mức độ nhạy khác nhau.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;num_trials&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trial&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_trials&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Log-uniform giữa 0.0001 và 0.1
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;history&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                                 &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;New best: LR=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, BS=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Val Acc=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Khởi tạo phù hợp&lt;/strong&gt; (như khởi tạo He cho ReLU) giúp tránh nhiều lỗi hội tụ ngay từ đầu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tiền xử lý dữ liệu&lt;/strong&gt; (standardization hoặc min-max) cải thiện tốc độ và độ ổn định khi tối ưu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mini-batch&lt;/strong&gt; cân bằng tốt giữa tốc độ cập nhật và độ mượt của gradient.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chia tập Train/Val/Test&lt;/strong&gt; đảm bảo đánh giá khách quan và hạn chế quá khớp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giám sát đồng thời&lt;/strong&gt; chỉ số trên tập huấn luyện và tập kiểm định giúp phát hiện sớm dấu hiệu quá khớp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dừng sớm&lt;/strong&gt; giúp tránh huấn luyện thừa và giữ lại phiên bản tham số tốt nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cắt ngưỡng gradient&lt;/strong&gt; ngăn chặn hiện tượng gradient bùng nổ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tinh chỉnh siêu tham số&lt;/strong&gt; đóng vai trò quan trọng để đạt hiệu năng tốt trên bài toán thực tế.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chương tiếp theo sẽ giới thiệu &lt;strong&gt;Mạng Neuron Tích chập (CNN)&lt;/strong&gt; chuyên dụng cho các bài toán thị giác máy tính.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=BOCLq2gpcGU&quot;&gt;Other Regularization Methods (C2W1L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Trình bày dừng sớm (&lt;em&gt;early stopping&lt;/em&gt;) cùng các phương pháp chính quy hóa liên quan.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, tiếng Anh. Minh họa vòng lặp huấn luyện chuẩn ghi nhận loss và cập nhật tham số.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 7&lt;/td&gt;
          &lt;td&gt;Training Neural Networks II](https://www.youtube.com/watch?v=_JB0AO7QxSA) — Stanford University School of Engineering, tiếng Anh. Phân tích cách đọc đường cong huấn luyện và lựa chọn siêu tham số.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-04-01 Khởi tạo, Tiền xử lý, Batch và Chia tập</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_04_01_Init_Preprocessing_and_Data/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_04_01_Init_Preprocessing_and_Data</id>
   <content type="html">&lt;p&gt;Một trong những sai lầm kinh điển nhất của người mới tự xây mạng nơ-ron là khởi tạo toàn bộ ma trận trọng số bằng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.zeros(...)&lt;/code&gt; cho “gọn gàng”. Kết quả là mạng có thể chạy 1{,}000 epoch mà &lt;strong&gt;mọi nơ-ron trong cùng một tầng học ra đúng một giá trị giống hệt nhau&lt;/strong&gt;—hiện tượng &lt;strong&gt;đối xứng chết (&lt;em&gt;symmetry trap&lt;/em&gt;)&lt;/strong&gt; khiến 1{,}000 nơ-ron chỉ mạnh ngang 1 nơ-ron duy nhất! Tương tự, chỉ một lỗi nhỏ tính trung bình chuẩn hóa trên cả tập Train lẫn Test đã đủ làm kết quả đánh giá bị gian lận (&lt;em&gt;data leakage&lt;/em&gt;). Bài học này trang bị quy chuẩn vàng cho khởi tạo trọng số (Xavier/He), chuẩn hóa dữ liệu và tổ chức tập dữ liệu sạch.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-quy-chuẩn-vàng-về-khởi-tạo-và-dữ-liệu&quot;&gt;Kiến thức cần nhớ: Bốn quy chuẩn Vàng về Khởi tạo và Dữ liệu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phá vỡ Đối xứng và Bảo toàn Phương sai (Xavier vs. He Initialization)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Xavier/Glorot&lt;/strong&gt;: \(\text{Var}(w) = \frac{2}{n_{\text{in}} + n_{\text{out}}}\) — tối ưu cho hàm đối xứng quanh \(0\) như Tanh/Sigmoid.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;He/Kaiming&lt;/strong&gt;: \(\text{Var}(w) = \frac{2}{n_{\text{in}}}\) — nhân thêm hệ số &lt;strong&gt;2&lt;/strong&gt; để bù lại việc ReLU cắt mất đúng một nửa tín hiệu ở miền âm!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Chuẩn hóa Đặc trưng (Standardization vs. Min-Max Scaling)&lt;/strong&gt;:
Đưa mọi đặc trưng về trung bình \(0\), độ lệch chuẩn \(1\) giúp các đường đồng mức hàm mất mát tròn trịa hơn, cho phép dùng learning rate lớn hơn và hội tụ nhanh hơn nhiều lần.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Nguyên tắc Chống Rò rỉ Dữ liệu (Zero Data Leakage)&lt;/strong&gt;:
Mọi thống kê tiền xử lý (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;std&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt;, từ điển mã hóa) &lt;strong&gt;chỉ được fit trên tập Train&lt;/strong&gt;, sau đó dùng đúng các con số đó để &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transform&lt;/code&gt; tập Validation và Test.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân chia Phân tầng (Stratified Split) và Cân bằng Batch Size&lt;/strong&gt;:
Với dữ liệu phân loại mất cân bằng, luôn chia phân tầng để giữ nguyên tỷ lệ các lớp ở cả 3 tập Train/Val/Test; chọn batch size là lũy thừa của 2 (32, 64, 128, 256) để tối ưu căn chỉnh bộ nhớ GPU.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-độ-lệch-chuẩn-khởi-tạo-xavier-vs-he-và-chuẩn-hóa-chống-data-leakage&quot;&gt;Giải thích: Tính tay độ lệch chuẩn khởi tạo Xavier vs. He và chuẩn hóa chống Data Leakage&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — So sánh số học Xavier vs. He cho một lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(256, 128)&lt;/code&gt;:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xavier Normal&lt;/strong&gt;: \(\text{Var}(w) = \frac{2}{256 + 128} = \frac{2}{384} \approx 0.00521 \implies \sigma_{\text{Xavier}} = \sqrt{0.00521} \approx \mathbf{0.0722}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;He Normal (cho ReLU)&lt;/strong&gt;: \(\text{Var}(w) = \frac{2}{256} = 0.00781 \implies \sigma_{\text{He}} = \sqrt{0.00781} \approx \mathbf{0.0884}\).
Độ lệch chuẩn của He lớn hơn khoảng 22% so với Xavier để giữ nguyên phương sai kích hoạt sau khi ReLU xóa bỏ nửa âm!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Chuẩn hóa Z-score đúng cách (không rò rỉ):&lt;/strong&gt;
Giả sử đặc trưng “Thu nhập (triệu VND)” ở tập Train gồm 3 mẫu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[10, 20, 30]&lt;/code&gt; và tập Test có 1 mẫu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[40]&lt;/code&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tính trên &lt;strong&gt;Train&lt;/strong&gt;: \(\mu_{\text{train}} = \frac{10+20+30}{3} = 20\), \(\sigma_{\text{train}} = \sqrt{\frac{(-10)^2 + 0^2 + 10^2}{3}} = \sqrt{\frac{200}{3}} \approx 8.165\).&lt;/li&gt;
  &lt;li&gt;Chuẩn hóa &lt;strong&gt;Train&lt;/strong&gt;: \([-1.225,\; 0.000,\; +1.225]\).&lt;/li&gt;
  &lt;li&gt;Chuẩn hóa &lt;strong&gt;Test&lt;/strong&gt; bằng &lt;strong&gt;đúng \(\mu_{\text{train}}, \sigma_{\text{train}}\)&lt;/strong&gt;: \(\frac{40 - 20}{8.165} = \mathbf{+2.449}\).
Tuyệt đối KHÔNG cộng gộp số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;40&lt;/code&gt; của tập Test vào lúc tính trung bình \(\mu\)!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bài này tổng hợp các kỹ thuật nền tảng trong giai đoạn chuẩn bị huấn luyện mạng neuron: khởi tạo trọng số, tiền xử lý dữ liệu, chia mini-batch và phân tách tập dữ liệu.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;khởi-tạo-trọng-số&quot;&gt;Khởi tạo Trọng số&lt;/h2&gt;

&lt;p&gt;Khởi tạo trọng số hợp lý ảnh hưởng trực tiếp tới khả năng hội tụ của mạng. Khởi tạo sai có thể dẫn đến hiện tượng gradient biến mất, bùng nổ hoặc khiến quá trình học diễn ra rất chậm.&lt;/p&gt;

&lt;h3 id=&quot;các-cách-khởi-tạo-nên-tránh&quot;&gt;Các Cách Khởi tạo Nên Tránh&lt;/h3&gt;

&lt;h4 id=&quot;1-khởi-tạo-toàn-0&quot;&gt;1. Khởi tạo toàn 0&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Hạn chế:&lt;/strong&gt; Tất cả neuron trong cùng một lớp tính ra cùng giá trị và nhận gradient giống hệt nhau, nên mạng không thể học được các đặc trưng khác nhau.&lt;/p&gt;

&lt;h4 id=&quot;2-khởi-tạo-cùng-một-hằng-số&quot;&gt;2. Khởi tạo cùng một hằng số&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Hạn chế:&lt;/strong&gt; Tương tự khởi tạo toàn 0 — không phá vỡ được tính đối xứng giữa các neuron.&lt;/p&gt;

&lt;h3 id=&quot;các-phương-pháp-khởi-tạo-tốt&quot;&gt;Các Phương pháp Khởi tạo Tốt&lt;/h3&gt;

&lt;h4 id=&quot;1-giá-trị-ngẫu-nhiên-nhỏ&quot;&gt;1. Giá trị Ngẫu nhiên Nhỏ&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt; Phá vỡ đối xứng.&lt;br /&gt;
&lt;strong&gt;Nhược điểm:&lt;/strong&gt; Có thể làm tín hiệu và gradient co quá nhỏ trong các mạng nhiều lớp.&lt;/p&gt;

&lt;h4 id=&quot;2-khởi-tạo-xavierglorot&quot;&gt;2. Khởi tạo Xavier/Glorot&lt;/h4&gt;

&lt;p&gt;Phù hợp với các hàm kích hoạt &lt;strong&gt;sigmoid&lt;/strong&gt; hoặc &lt;strong&gt;tanh&lt;/strong&gt;:&lt;/p&gt;

\[\mathbf{W}^{[l]} \sim \mathcal{N}\left(0, \frac{1}{n^{[l-1]}}\right)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;hoặc phiên bản cân bằng cả chiều vào và chiều ra:&lt;/p&gt;

\[\mathbf{W}^{[l]} \sim \mathcal{N}\left(0, \frac{2}{n^{[l-1]} + n^{[l]}}\right)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Mục đích:&lt;/strong&gt; Giữ cho phương sai của các giá trị kích hoạt ổn định khi đi qua nhiều lớp.&lt;/p&gt;

&lt;h4 id=&quot;3-khởi-tạo-he&quot;&gt;3. Khởi tạo He&lt;/h4&gt;

&lt;p&gt;Phù hợp với hàm kích hoạt &lt;strong&gt;ReLU&lt;/strong&gt; (được sử dụng rộng rãi nhất):&lt;/p&gt;

\[\mathbf{W}^{[l]} \sim \mathcal{N}\left(0, \frac{2}{n^{[l-1]}}\right)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Vì sao có hệ số 2?&lt;/strong&gt; Vì ReLU đưa trung bình một nửa số đầu vào âm về 0, nên phương sai cần tăng gấp đôi để duy trì thang đo kích hoạt.&lt;/p&gt;

&lt;h3 id=&quot;khởi-tạo-độ-lệch&quot;&gt;Khởi tạo Độ lệch&lt;/h3&gt;

&lt;p&gt;Khác với trọng số, độ lệch thường có thể khởi tạo bằng 0:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;hàm-khởi-tạo-đầy-đủ&quot;&gt;Hàm Khởi tạo Đầy đủ&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;initialize_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization_method&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;he&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Khởi tạo tham số mạng
    
    layer_dims: danh sách kích thước lớp [n_x, n_h1, ..., n_y]
    initialization_method: &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xavier&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;he&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization_method&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization_method&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization_method&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xavier&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization_method&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;he&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;tiền-xử-lý-dữ-liệu&quot;&gt;Tiền xử lý Dữ liệu&lt;/h2&gt;

&lt;h3 id=&quot;1-chuẩn-hóa-thang-đo-đặc-trưng&quot;&gt;1. Chuẩn hóa Thang đo Đặc trưng&lt;/h3&gt;

&lt;p&gt;Đưa các đặc trưng đầu vào về cùng thang đo giúp bề mặt hàm mất mát cân đối hơn và gradient descent hội tụ nhanh hơn.&lt;/p&gt;

&lt;h4 id=&quot;chuẩn-hóa-z-score-standardization&quot;&gt;Chuẩn hóa Z-score (&lt;em&gt;Standardization&lt;/em&gt;)&lt;/h4&gt;

\[x_{\text{norm}} = \frac{x - \mu}{\sigma}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;standardize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Chuẩn hóa đặc trưng về mean=0, std=1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;X_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Thêm epsilon tránh chia cho không
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;chuẩn-hóa-min-max&quot;&gt;Chuẩn hóa Min-Max&lt;/h4&gt;

\[x_{\text{norm}} = \frac{x - x_{\min}}{x_{\max} - x_{\min}}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min_max_normalize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Scale đặc trưng về [0, 1]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;X_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_max&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Cách chọn phương pháp:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Standardization:&lt;/strong&gt; Thích hợp khi đặc trưng có phân phối gần chuẩn hoặc xuất hiện điểm ngoại lai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Min-Max:&lt;/strong&gt; Thích hợp khi cần ép toàn bộ giá trị vào một khoảng cố định (ví dụ \([0, 1]\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-xáo-trộn-dữ-liệu&quot;&gt;2. Xáo trộn Dữ liệu&lt;/h3&gt;

&lt;p&gt;Cần xáo trộn tập dữ liệu huấn luyện trước mỗi epoch để tránh việc mô hình học theo thứ tự sắp xếp của mẫu dữ liệu.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;shuffle_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Xáo trộn dữ liệu huấn luyện&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;permutation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;permutation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;permutation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;permutation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;xử-lý-theo-batch&quot;&gt;Xử lý theo Batch&lt;/h2&gt;

&lt;h3 id=&quot;tạo-các-mini-batch&quot;&gt;Tạo Các Mini-Batch&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Tạo danh sách các mini-batch
    
    X: (n_x, m)
    Y: (n_y, m)
    batch_size: kích thước mỗi mini-batch
    
    Returns: danh sách các tuple (X_batch, Y_batch)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Xáo trộn dữ liệu
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;shuffle_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Phân hoạch
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;num_complete_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_complete_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Xử lý các mẫu còn lại (nếu m không chia hết cho batch_size)
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_complete_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_complete_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;chia-tập-train--validation--test&quot;&gt;Chia Tập Train / Validation / Test&lt;/h2&gt;

&lt;h3 id=&quot;vai-trò-của-ba-tập-dữ-liệu&quot;&gt;Vai trò của Ba Tập dữ liệu&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tập huấn luyện (&lt;em&gt;train&lt;/em&gt;):&lt;/strong&gt; Dùng để học tham số mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tập kiểm định (&lt;em&gt;validation&lt;/em&gt;):&lt;/strong&gt; Dùng để chọn siêu tham số và theo dõi dấu hiệu quá khớp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tập kiểm tra (&lt;em&gt;test&lt;/em&gt;):&lt;/strong&gt; Dùng để đánh giá khách quan chất lượng cuối cùng (chỉ nên dùng sau khi đã chốt mô hình).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tỷ-lệ-chia-thường-dùng&quot;&gt;Tỷ lệ Chia Thường dùng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tập dữ liệu nhỏ (dưới 10.000 mẫu):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Train: 60%, Validation: 20%, Test: 20%&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Tập dữ liệu trung bình (10.000 – 1.000.000 mẫu):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Train: 80%, Validation: 10%, Test: 10%&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Tập dữ liệu lớn (trên 1.000.000 mẫu):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Train: 98%, Validation: 1%, Test: 1%&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;cài-đặt&quot;&gt;Cài đặt&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_val_test_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_ratio&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_ratio&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Chia dữ liệu thành tập train, validation và test
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Xáo trộn trước
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;shuffle_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Tính chỉ số chia
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_ratio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_end&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_ratio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Chia
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Y_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=ScWTYHQra5E&quot;&gt;L11.6 Xavier Glorot and Kaiming He Initialization&lt;/a&gt; — Sebastian Raschka, tiếng Anh. Giải thích cơ sở toán học của quy tắc khởi tạo Xavier và He được trình bày trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 6&lt;/td&gt;
          &lt;td&gt;Training Neural Networks I](https://www.youtube.com/watch?v=wEoyxE0GP2M) — Stanford University School of Engineering, tiếng Anh. Bối cảnh tổng thể về khởi tạo trọng số, tiền xử lý dữ liệu và xử lý theo batch.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Zi-0rlM4RDs&quot;&gt;Train, Test, &amp;amp; Validation Sets explained&lt;/a&gt; — deeplizard, tiếng Anh. Giải thích rõ mục đích của việc chia dữ liệu thành ba tập trước khi huấn luyện.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-03 Thuật toán Lan truyền Ngược</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_03_Backpropagation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_03_Backpropagation</id>
   <content type="html">&lt;p&gt;Nếu phải chọn ra một thuật toán duy nhất làm nên cả đế chế Trí tuệ Nhân tạo hiện đại, đó chắc chắn là &lt;strong&gt;Lan truyền Ngược (&lt;em&gt;Backpropagation&lt;/em&gt;)&lt;/strong&gt;—được phổ biến rộng rãi bởi Rumelhart, Hinton và Williams năm 1986. Trước khi có Backpropagation hiệu quả, việc tính đạo hàm cho một mạng 1 triệu tham số bằng sai phân hữu hạn đòi hỏi chạy lan truyền xuôi tới &lt;strong&gt;1 triệu lần&lt;/strong&gt; cho mỗi bước cập nhật! Backpropagation rút gọn chi phí khổng lồ đó xuống chỉ còn &lt;strong&gt;đúng 1 lượt đi ngược&lt;/strong&gt;. Mục tổng quan này phác họa trực giác trước khi bạn tự tay giải toán và tự code một động cơ Backprop hoàn chỉnh.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-của-thuật-toán-lan-truyền-ngược&quot;&gt;Kiến thức cần nhớ: Ba trụ cột của Thuật toán Lan truyền Ngược&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đồ thị Tính toán và Quy tắc Dây chuyền (Computational Graph &amp;amp; Chain Rule)&lt;/strong&gt;:
Mọi mạng nơ-ron phức tạp đều phân rã được thành đồ thị các phép toán sơ cấp (cộng, nhân, mũ, ReLU). Mỗi nút chỉ cần biết đạo hàm cục bộ của riêng mình rồi nhân với tín hiệu lỗi truyền từ phía sau về.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tái sử dụng Kết quả Trung gian bằng Quy hoạch Động (Reverse-Mode Autodiff)&lt;/strong&gt;:
Thay vì tính lại đạo hàm từ đầu cho từng trọng số, Backpropagation tính tín hiệu lỗi \(\boldsymbol{\delta}^{(\ell)} = \frac{\partial L}{\partial \mathbf{Z}^{(\ell)}}\) từ tầng cuối \(L\) ngược về tầng \(1\), tái sử dụng kết quả của tầng sau cho toàn bộ các tầng trước.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kiểm tra Gradient bằng Số học (Numerical Gradient Checking)&lt;/strong&gt;:
So sánh gradient giải tích từ Backpropagation với sai phân trung tâm \(\frac{L(\theta + \varepsilon) - L(\theta - \varepsilon)}{2\varepsilon}\)—vũ khí kiểm chứng chuẩn xác tuyệt đối mỗi khi bạn tự viết lớp tùy chỉnh.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-chi-phí-tính-gradient-giữa-sai-phân-hữu-hạn-và-backpropagation&quot;&gt;Giải thích: So sánh chi phí tính Gradient giữa Sai phân Hữu hạn và Backpropagation&lt;/h3&gt;

&lt;p&gt;Giả sử mạng nơ-ron của bạn có \(P = 1{,}000{,}000\) tham số và 1 lần chạy lan truyền xuôi mất \(1\text{ ms}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cách ngây thơ (Sai phân hữu hạn — nhích từng tham số \(\theta_i \pm \varepsilon\))&lt;/strong&gt;:
Để tính gradient cho cả \(1{,}000{,}000\) tham số, cần chạy \(2 \times 1{,}000{,}000 = 2{,}000{,}000\) lượt forward \(\implies\) tốn &lt;strong&gt;2{,}000 giây (hơn 33 phút)&lt;/strong&gt; chỉ cho &lt;strong&gt;1 bước cập nhật duy nhất&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cách của Backpropagation (Reverse-Mode Autodiff)&lt;/strong&gt;:
1 lượt forward (\(1\text{ ms}\)) + 1 lượt backward (\(\approx 2\text{ ms}\)) = &lt;strong&gt;3 mili-giây&lt;/strong&gt; cho toàn bộ 1 triệu đạo hàm cùng lúc—nhanh hơn gần &lt;strong&gt;700{,}000 lần&lt;/strong&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chính sự chênh lệch tốc độ hàng trăm nghìn lần này biến việc huấn luyện mạng hàng trăm tỷ tham số từ điều bất khả thi thành hiện thực hàng ngày.&lt;/p&gt;

&lt;p&gt;Phần này trình bày thuật toán lan truyền ngược (&lt;em&gt;backpropagation&lt;/em&gt;) — cơ chế tính gradient cốt lõi của học sâu:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết và ví dụ tính toán&lt;/strong&gt; — khái niệm, nền tảng toán học và ví dụ số từng bước&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Triển khai&lt;/strong&gt; — cài đặt từ đầu bằng NumPy và bằng PyTorch, các bài báo nền tảng, lỗi thường gặp và điểm then chốt&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Backpropagation, intuitively&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 3](https://www.youtube.com/watch?v=Ilg3gGewQ5U) — 3Blue1Brown, tiếng Anh. Diễn giải trực quan cách mỗi mẫu dữ liệu điều chỉnh từng trọng số trong mạng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Backpropagation calculus&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 4](https://www.youtube.com/watch?v=tIeHLnjs5U8) — 3Blue1Brown, tiếng Anh. Phép tính quy tắc dây chuyền đứng sau quá trình cập nhật trọng số.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Cài đặt hoàn chỉnh thuật toán lan truyền ngược bằng mã nguồn, tương ứng với bài thứ hai trong phần này.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-03-02 Triển khai Lan truyền Ngược</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_03_02_Backprop_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_03_02_Backprop_Implementation</id>
   <content type="html">&lt;p&gt;Hiểu lý thuyết Backpropagation trên giấy mới đi được nửa chặng đường; nửa chặng đường còn lại—và là trải nghiệm đáng giá nhất với mọi kỹ sư Học sâu—là &lt;strong&gt;tự tay cài đặt toàn bộ mạng MLP và lan truyền ngược từ đầu chỉ bằng NumPy&lt;/strong&gt;, rồi thấy nó tự học giải gọn bài toán XOR mà không cần bất kỳ dòng PyTorch nào! Một lỗi nhỏ về chiều ma trận (quên chuyển vị, quên chia cho kích thước batch \(B\), hay dùng nhầm giá trị đã kích hoạt thay vì tiền kích hoạt) có thể khiến mạng học sai lặng lẽ. Bài thực hành này giúp bạn viết mã sạch, kiểm tra kích thước chặt chẽ và kiểm chứng độ chính xác bằng Gradient Checking.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-kỷ-luật-lập-trình-khi-tự-cài-backpropagation-bằng-numpy&quot;&gt;Kiến thức cần nhớ: Bốn kỷ luật lập trình khi Tự cài Backpropagation bằng NumPy&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Quy tắc Khớp Chiều Ma trận (Shape Invariant Check)&lt;/strong&gt;:
Gradient của mọi tham số &lt;strong&gt;bắt buộc phải có kích thước giống hệt chính tham số đó&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dW.shape == W.shape&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;db.shape == b.shape&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dA.shape == A.shape&lt;/code&gt;. Cài sẵn các dòng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;assert&lt;/code&gt; kiểm tra shape giúp bắt ngay 90% lỗi lập trình.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lưu Cache đúng lúc Forward để dùng lúc Backward&lt;/strong&gt;:
Để tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dW_l = A_{l-1}.T @ dZ_l / B&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dZ_l = dA_l * act_deriv(Z_l)&lt;/code&gt;, hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;forward&lt;/code&gt; phải lưu lại danh sách &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(A_{l-1}, Z_l)&lt;/code&gt; theo đúng thứ tự tầng để &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;backward&lt;/code&gt; duyệt ngược từ tầng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;L&lt;/code&gt; về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt;.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Cẩn thận phép Cộng dồn và Broadcasting cho Bias (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;axis=0, keepdims=True&lt;/code&gt;)&lt;/strong&gt;:
Vì bias \(\mathbf{b}^{(\ell)} \in \mathbb{R}^{1 \times n_\ell}\) được cộng vào mọi mẫu trong batch \(B\), khi đạo hàm ngược ta phải cộng (hoặc lấy trung bình) dọc theo trục mẫu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;axis=0&lt;/code&gt; để giữ nguyên kích thước &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(1, n_l)&lt;/code&gt;.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kiểm tra Sai số Tương đối bằng Sai phân Trung tâm (Gradient Checking)&lt;/strong&gt;:
So sánh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad_analytic&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad_numeric&lt;/code&gt; qua công thức \(\frac{\|g_a - g_n\|_2}{\|g_a\|_2 + \|g_n\|_2}\): nếu nhỏ hơn \(10^{-7}\) (với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt;), cài đặt Backprop của bạn đã chính xác tuyệt đối!&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-một-phép-kiểm-tra-gradient-checking-với-varepsilon--10-4&quot;&gt;Giải thích: Tính tay một phép kiểm tra Gradient Checking với \(\varepsilon = 10^{-4}\)&lt;/h3&gt;

&lt;p&gt;Giả sử bạn nghi ngờ công thức đạo hàm giải tích của hàm \(L(w) = w^3\) tại \(w = 2.0\) (đạo hàm đúng là \(g_a = 3(2)^2 = 12.000000\)). Hãy kiểm tra bằng sai phân trung tâm với \(\varepsilon = 10^{-4}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Tính \(L(2 + 10^{-4}) = (2.0001)^3 = 8.001200060001\).&lt;/li&gt;
  &lt;li&gt;Tính \(L(2 - 10^{-4}) = (1.9999)^3 = 7.998800059999\).&lt;/li&gt;
  &lt;li&gt;Lấy hiệu chia cho \(2\varepsilon = 2 \times 10^{-4}\):
\(g_n = \frac{8.001200060001 - 7.998800059999}{0.0002} = \frac{0.002400000002}{0.0002} = 12.00000001.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sai số tương đối&lt;/strong&gt;:
\(\frac{\lvert 12.0 - 12.00000001 \rvert}{12.0 + 12.00000001} \approx 4.17 \times 10^{-10} \ll 10^{-7} \implies \textbf{ĐẠT CHUẨN!}\)
Ngược lại, nếu bạn lỡ viết nhầm đạo hàm trong code thành \(2w^2 = 8.0\), sai số tương đối lập tức nhảy lên \(\frac{4}{20} = 0.2\)—phát hiện bug ngay trong nháy mắt!&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-đoạn-mã&quot;&gt;4. Đoạn Mã&lt;/h2&gt;

&lt;p&gt;Dưới đây là cài đặt lan truyền ngược từ đầu bằng NumPy để nắm rõ từng bước tính toán, sau đó đối chiếu với cách PyTorch tự động hóa quá trình này:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Kích hoạt sigmoid: ánh xạ số thực về (0, 1)
    
    Vì sao sigmoid? Nó trơn (khả vi mọi nơi), bị chặn (đầu ra
    không bùng nổ), và có diễn giải xác suất. Đạo hàm có dạng
    đẹp: σ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(z) = σ(z)(1 - σ(z)), có thể tính từ chính kích hoạt
    mà không cần lưu z.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Clip để ổn định số
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đạo hàm theo kích hoạt (không phải z!)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    ReLU: max(0, z) - cho ra đầu vào nếu dương, không nếu ngược lại
    
    Vì sao ReLU? Tính toán tầm thường (chỉ ngưỡng hóa), không
    bão hòa với đầu vào dương (gradient bằng 1, không tiến về 0),
    và tạo biểu diễn thưa. Các tính chất này làm nó vượt trội
    hơn nhiều so với sigmoid/tanh cho mạng sâu.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Đạo hàm bằng 1 nơi z &amp;gt; 0, bằng không nơi khác
    
    Lưu ý: tại z=0, đạo hàm không xác định. Trong thực tế, ta định nghĩa bằng 0
    hoặc đôi khi 0.5, nhưng điều này hiếm khi quan trọng vì đẳng thức chính xác hiếm gặp.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetworkBackprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Triển khai lan truyền ngược thủ công để hiểu mọi bước.
    
    Triển khai này ưu tiên rõ ràng hơn hiệu quả. Mỗi phép toán
    tường minh, gradient được tính thủ công, và ta lưu mọi thứ
    cần cho việc hiểu. Triển khai sản xuất sẽ vectorize
    mạnh hơn và dùng vi phân tự động.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        layer_sizes: danh sách như [2, 4, 3, 1] cho 2 đầu vào, lớp ẩn 4 và 3, 1 đầu ra
        
        Ta khởi tạo trọng số bằng khởi tạo He cho lớp ẩn (giả định ReLU)
        và giá trị ngẫu nhiên nhỏ cho lớp đầu ra. Lược đồ khởi tạo này đảm bảo
        kích hoạt duy trì thang đo hợp lý qua lan truyền xuôi và gradient
        duy trì thang đo hợp lý qua lan truyền ngược.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Số lớp trọng số
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;c1&quot;&gt;# Khởi tạo He cho lớp ReLU: phương sai = 2/n_in
&lt;/span&gt;                &lt;span class=&quot;c1&quot;&gt;# Vì sao? ReLU triệt tiêu một nửa neuron, nên cần √2 thay vì √1
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;c1&quot;&gt;# Lớp đầu ra: trọng số nhỏ hơn cho ổn định số
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Initialized network with architecture: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Total parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đếm tổng số tham số có thể huấn luyện&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Lan truyền xuôi với cache chi tiết cho lan truyền ngược.
        
        Ta phải lưu Z (tiền kích hoạt) và A (kích hoạt) cho mỗi lớp
        vì lan truyền ngược cần chúng. Đây là đánh đổi bộ nhớ vs tính toán:
        ta có thể tính lại lan truyền xuôi trong lan truyền ngược, nhưng lưu nhanh hơn.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lớp ẩn với ReLU
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lớp đầu ra với sigmoid
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;compute_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Mất mát entropy chéo nhị phân với các mẹo ổn định số.
        
        Mất mát -[y log(ŷ) + (1-y) log(1-ŷ)] có vấn đề: nếu ŷ đúng bằng
        0 hoặc 1, ta tính log(0) = -∞. Ta cắt dự đoán về [ε, 1-ε] để ngăn điều này.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;AL_clipped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL_clipped&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL_clipped&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Lan truyền ngược: tính tất cả gradient tham số hiệu quả.
        
        Thuật toán xử lý các lớp theo thứ tự ngược, duy trì các hạng tử sai số
        và dùng các giá trị lan truyền xuôi đã cache. Gradient mỗi lớp phụ thuộc
        gradient từ các lớp trên nó, tạo luồng thông tin ngược
        mang tên thuật toán.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Sai số lớp đầu ra (với BCE + sigmoid điều này đơn giản đáng kể!)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dAL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Đạo hàm mất mát
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dZL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dAL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Nhưng thực ra, dZL = AL - Y hoạt động trực tiếp
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Đơn giản hóa cho BCE + Sigmoid (nên dùng trong thực tế)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dZL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient lớp đầu ra
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;dW&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dZL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dZL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Khởi tạo dA để truyền
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dA&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dZL&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lớp ẩn (ngược qua các lớp L-1 xuống 1)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;reversed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Sai số lớp hiện tại
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dZ&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dA&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Gradient cho lớp này
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;dW&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dZ&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dZ&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Truyền sai số về lớp trước (nếu không phải lớp đầu vào)
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;dA&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dZ&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;update_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Cập nhật gradient descent: θ ← θ - η ∇θ L
        
        Ta dịch tham số theo hướng giảm mất mát. Learning rate
        η điều khiển kích thước bước — quá lớn gây vượt và bất ổn,
        quá nhỏ gây hội tụ chậm.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;dW&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;print_every&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Vòng lặp huấn luyện đầy đủ: xuôi → mất mát → ngược → cập nhật
        
        Đây là vòng lặp huấn luyện chuẩn cho mạng neuron. Mỗi vòng lặp
        xử lý toàn bộ tập dữ liệu (batch gradient descent). Trong thực tế, ta
        dùng mini-batch vì hiệu quả.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Lan truyền xuôi
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Tính mất mát
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;compute_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Lan truyền ngược
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật tham số
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;update_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# In tiến độ
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;print_every&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Iteration &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Accuracy = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Minh họa trên bài toán XOR
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Neural Network on XOR using Manual Backpropagation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tập dữ liệu XOR
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                  &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Dạng: (2, 4)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Dạng: (1, 4)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Tạo và huấn luyện mạng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Để tái lập
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;network&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetworkBackprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Kiến trúc 2→4→4→1
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;network&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;print_every&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra hiệu năng cuối
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Final Results&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;AL_final&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;network&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL_final&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, True: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Probability: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL_final&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Final accuracy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Success! Backpropagation enabled the network to learn XOR.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Tiếp theo, hãy xem cách PyTorch tự động hóa toàn bộ quá trình tính gradient trên:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleNetPyTorch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Cùng mạng dùng vi phân tự động của PyTorch.
    
    Chú ý ta không triển khai backward() - PyTorch tính tất cả gradient
    tự động bằng cách xây đồ thị tính toán trong lan truyền xuôi và
    áp dụng lan truyền ngược khi ta gọi loss.backward().
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SimpleNetPyTorch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện với PyTorch
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleNetPyTorch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BCELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Chuyển sang tensor PyTorch
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_torch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (4, 2)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y_torch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (4, 1)
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training with PyTorch Automatic Differentiation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Lan truyền xuôi
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Lan truyền ngược - PyTorch thực hiện backpropagation tự động!
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Xóa gradient cũ
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Tính gradient qua vi phân tự động
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;       &lt;span class=&quot;c1&quot;&gt;# Cập nhật trọng số
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Accuracy = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra cuối
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;final_preds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PyTorch Final Results&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Predicted: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;final_preds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Sự đối chiếu giữa hai đoạn mã cho thấy rõ lợi ích của các framework hiện đại: bản cài đặt thủ công cần khoảng 100 dòng mã chỉ cho một mạng đơn giản, trong khi PyTorch xử lý tự động mọi kiến trúc. Tuy nhiên, việc tự viết lan truyền ngược vẫn rất giá trị khi cần gỡ lỗi mô hình không hội tụ, xây dựng lớp tính toán tùy chỉnh hoặc đọc hiểu các phân tích về luồng gradient trong tài liệu nghiên cứu.&lt;/p&gt;

&lt;h2 id=&quot;5-các-khái-niệm-liên-quan&quot;&gt;5. Các Khái niệm Liên quan&lt;/h2&gt;

&lt;p&gt;Lan truyền ngược gắn chặt với nhiều khái niệm nền tảng khác trong học sâu và học máy. Nắm rõ các mối liên hệ này giúp hiểu vai trò thực sự của thuật toán trong toàn bộ quy trình huấn luyện.&lt;/p&gt;

&lt;p&gt;Mối liên hệ trực tiếp nhất là với gradient descent và các bộ tối ưu hóa. Lan truyền ngược chỉ giải bài toán &lt;strong&gt;tính gradient&lt;/strong&gt;, còn bộ tối ưu (như SGD, SGD với momentum, Adam) quyết định cách dùng gradient đó để cập nhật tham số. Tách biệt hai vai trò này giúp làm rõ cơ chế: lan truyền ngược chỉ ra hướng giảm hàm mất mát, còn bộ tối ưu quyết định độ dài bước đi và cách tích lũy thông tin từ các bước trước.&lt;/p&gt;

&lt;p&gt;Vi phân tự động (&lt;em&gt;automatic differentiation&lt;/em&gt;) — công nghệ lõi của PyTorch và TensorFlow — là dạng tổng quát hơn của lan truyền ngược. Trong khi lan truyền ngược thường được trình bày cho mạng neuron, vi phân tự động áp dụng cho mọi chương trình tính toán khả vi. Framework sẽ dựng đồ thị tính toán trong lượt xuôi (mỗi nút là một phép toán, mỗi cạnh là luồng dữ liệu), sau đó chạy vi phân tự động chế độ ngược (&lt;em&gt;reverse-mode autodiff&lt;/em&gt;) trên đồ thị đó. Nhờ vậy, bất kỳ kiến trúc nào tạo từ các phép toán khả vi đều có thể huấn luyện tự động.&lt;/p&gt;

&lt;p&gt;Hiện tượng gradient biến mất và bùng nổ là hệ quả trực tiếp của việc nhân dồn đạo hàm qua nhiều lớp. Ở mỗi lớp, tín hiệu sai số được nhân với ma trận trọng số và đạo hàm của hàm kích hoạt. Nếu các hệ số nhân này liên tục nhỏ hơn 1 (chẳng hạn khi sigmoid hoặc tanh bị bão hòa), gradient giảm theo cấp số nhân theo độ sâu; ngược lại, nếu lớn hơn 1, gradient tăng vọt mất kiểm soát. Nhận thức này là động lực cho hàng loạt cải tiến như ReLU, batch normalization, kết nối tắt (&lt;em&gt;residual connections&lt;/em&gt;) và các phương pháp khởi tạo trọng số phù hợp.&lt;/p&gt;

&lt;p&gt;Cơ chế đồ thị tính toán cũng giúp lan truyền ngược mở rộng ra ngoài mạng truyền thẳng: nó áp dụng được cho mạng hồi quy (lan truyền ngược theo thời gian — BPTT), các mạng có nhánh điều khiển phức tạp và cả những kiến trúc động thay đổi theo dữ liệu đầu vào. Nguyên lý chung không đổi: xây dựng đồ thị trong lượt xuôi và truyền ngược đạo hàm bằng quy tắc dây chuyền.&lt;/p&gt;

&lt;p&gt;Cuối cùng, lan truyền ngược là một cách giải quyết bài toán &lt;strong&gt;phân bổ đóng góp&lt;/strong&gt; (&lt;em&gt;credit assignment&lt;/em&gt;): khi mô hình dự đoán sai, tham số nào chịu trách nhiệm bao nhiêu? Lan truyền ngược phân bổ mức trách nhiệm tỷ lệ với gradient cục bộ. Tuy đây là giải pháp rất hiệu quả cho học có giám sát khả vi, các lĩnh vực khác như học tăng cường hoặc mô hình tuần tự vẫn cần thêm các cơ chế khác (như hàm giá trị hoặc cơ chế attention) khi giả định khả vi trực tiếp không còn thỏa mãn.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các Bài báo Nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.nature.com/articles/323533a0&quot;&gt;“Learning representations by back-propagating errors” (1986)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: David E. Rumelhart, Geoffrey E. Hinton, Ronald J. Williams&lt;br /&gt;
Bài báo kinh điển trên tạp chí &lt;em&gt;Nature&lt;/em&gt; đã phổ biến rộng rãi thuật toán lan truyền ngược và chứng minh tính hiệu quả trên các bài toán thực tế như nhận dạng giọng nói và phân loại ảnh. Các tác giả trình bày rõ ràng thuật toán dựa trên quy tắc dây chuyền và cho thấy các lớp ẩn có thể tự học biểu diễn đặc trưng hữu ích — vượt qua giới hạn của perceptron một lớp. Đây là một trong những công trình được trích dẫn nhiều nhất trong lịch sử học máy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf&quot;&gt;“Efficient BackProp” (1998)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Yann LeCun, Léon Bottou, Genevieve B. Orr, Klaus-Robert Müller&lt;br /&gt;
Báo cáo kỹ thuật này phân tích có hệ thống các yếu tố giúp lan truyền ngược hoạt động ổn định trong thực tế: phương pháp khởi tạo trọng số với phương sai hợp lý, chuẩn hóa dữ liệu đầu vào, lựa chọn tốc độ học và hàm kích hoạt. Nhiều kỹ thuật tiêu chuẩn trong học sâu ngày nay bắt nguồn từ những đúc kết thực nghiệm trong tài liệu này.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1211.5063&quot;&gt;“On the difficulty of training Recurrent Neural Networks” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Razvan Pascanu, Tomas Mikolov, Yoshua Bengio&lt;br /&gt;
Bài báo phân tích chặt chẽ nguyên nhân khiến lan truyền ngược theo thời gian trong RNN dễ gặp tình trạng gradient biến mất hoặc bùng nổ do phép nhân ma trận lặp lại nhiều bước: nếu trị riêng lớn nhất nhỏ hơn 1, gradient suy giảm theo hàm mũ; nếu lớn hơn 1, gradient bùng nổ. Các tác giả đề xuất kỹ thuật cắt ngưỡng gradient (&lt;em&gt;gradient clipping&lt;/em&gt;) để kiểm soát bùng nổ và phân tích vai trò của cơ chế cổng trong LSTM.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://openreview.net/forum?id=BJJsrmfCZ&quot;&gt;“Automatic differentiation in PyTorch” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Adam Paszke, Sam Gross, Soumith Chintala, et al.&lt;br /&gt;
Bài báo mô tả hệ thống &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;autograd&lt;/code&gt; của PyTorch với đồ thị tính toán động được xây dựng ngay trong lượt lan truyền xuôi, kết hợp vi phân tự động chế độ ngược. Thiết kế linh hoạt này đặc biệt phù hợp với các kiến trúc có cấu trúc thay đổi theo dữ liệu và giúp PyTorch trở nên phổ biến trong nghiên cứu cũng như triển khai thực tế.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://www.deeplearningbook.org/contents/mlp.html&quot;&gt;“Deep Learning” - Chương 6 (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Ian Goodfellow, Yoshua Bengio, Aaron Courville&lt;br /&gt;
Chương sách giáo khoa này trình bày toàn diện và chặt chẽ nền tảng toán học của lan truyền ngược, đồ thị tính toán, độ phức tạp cũng như các vấn đề thực tế như ổn định số và quản lý bộ nhớ. Tài liệu được cung cấp miễn phí trực tuyến và là nguồn tham khảo chuẩn mực về chủ đề này.&lt;/p&gt;

&lt;h2 id=&quot;cạm-bẫy-và-mẹo-thường-gặp&quot;&gt;Cạm bẫy và Mẹo Thường gặp&lt;/h2&gt;

&lt;p&gt;Một lỗi rất hay gặp khi tự cài đặt lan truyền ngược là quên lưu đệm (&lt;em&gt;cache&lt;/em&gt;) các giá trị trung gian từ lượt xuôi. Lượt ngược cần dùng lại cả tiền kích hoạt \(\mathbf{z}^{[l]}\) lẫn kích hoạt \(\mathbf{a}^{[l]}\) của từng lớp. Nếu bỏ sót hoặc vô tình ghi đè chúng, chương trình hoặc phải tính lại lượt xuôi (làm chậm gấp đôi), hoặc tính ra gradient sai. Khi viết thủ công, nên duy trì một cấu trúc từ điển &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cache&lt;/code&gt; rõ ràng cho từng lớp.&lt;/p&gt;

&lt;p&gt;Lỗi không khớp kích thước giữa gradient và tham số cũng rất dễ gây sai sót khó phát hiện. Gradient \(\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[l]}}\) luôn phải có đúng kích thước của \(\mathbf{W}^{[l]}\) (\(n_{out} \times n_{in}\)). Nhầm thứ tự nhân ma trận hoặc quên chuyển vị trong biểu thức \(\boldsymbol{\delta}^{[l]} (\mathbf{a}^{[l-1]})^T\) có thể bị NumPy tự động &lt;em&gt;broadcast&lt;/em&gt; mà không báo lỗi ngay, dẫn tới cập nhật sai. Nên đặt câu lệnh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;assert&lt;/code&gt; kiểm tra kích thước gradient khớp với tham số.&lt;/p&gt;

&lt;p&gt;Bất ổn số học khi tính đạo hàm cũng có thể làm hỏng quá trình huấn luyện. Ví dụ với đạo hàm sigmoid \(\sigma&apos;(z) = \sigma(z)(1-\sigma(z))\), khi \(z\) rất lớn, giá trị số thực của \(\sigma(z)\) làm tròn thành \(1\) khiến đạo hàm thành \(1 \times (1-1) = 0\) dù về mặt toán học vẫn dương. Giới hạn miền giá trị trung gian và dùng công thức ổn định số (như log-sum-exp cho softmax) giúp hạn chế lỗi này.&lt;/p&gt;

&lt;p&gt;Một kỹ thuật gỡ lỗi hiệu quả là &lt;strong&gt;kiểm tra gradient bằng số&lt;/strong&gt; (&lt;em&gt;gradient checking&lt;/em&gt;). Với từng tham số \(\theta\), ta xấp xỉ đạo hàm bằng sai phân trung tâm:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \theta} \approx \frac{\mathcal{L}(\theta + \epsilon) - \mathcal{L}(\theta - \epsilon)}{2\epsilon}\]

&lt;p&gt;với \(\epsilon \approx 10^{-7}\). Đối chiếu kết quả này với gradient do lan truyền ngược tính ra sẽ nhanh chóng phát hiện lỗi cài đặt (sai số tương đối nên nhỏ hơn \(10^{-7}\)). Tuy nhiên, do phương pháp này rất chậm, chỉ nên dùng khi kiểm thử mã nguồn chứ không bật trong lúc huấn luyện thật.&lt;/p&gt;

&lt;p&gt;Cắt ngưỡng gradient (&lt;em&gt;gradient clipping&lt;/em&gt;) là kỹ thuật quan trọng khi huấn luyện RNN hoặc các mạng sâu dễ bùng nổ gradient. Ta tính chuẩn toàn cục \(\|\nabla_\theta \mathcal{L}\|_2 = \sqrt{\sum_{\theta} (\frac{\partial \mathcal{L}}{\partial \theta})^2}\); nếu giá trị này vượt ngưỡng cho phép (thường chọn 5 hoặc 10), toàn bộ gradient được thu nhỏ theo tỷ lệ \(\frac{\text{threshold}}{\|\nabla_\theta \mathcal{L}\|_2}\). Thao tác này giữ nguyên hướng cập nhật trong khi ngăn các bước nhảy quá lớn làm hỏng trọng số.&lt;/p&gt;

&lt;p&gt;Cuối cùng, vì lan truyền ngược đơn thuần là quy tắc dây chuyền trên từng phép toán, bạn hoàn toàn có thể tự định nghĩa đạo hàm cục bộ cho các lớp tùy chỉnh và ghép chúng vào mạng để hệ thống autograd xử lý phần còn lại.&lt;/p&gt;

&lt;h2 id=&quot;điểm-then-chốt&quot;&gt;Điểm Then chốt&lt;/h2&gt;

&lt;p&gt;Lan truyền ngược áp dụng quy tắc dây chuyền một cách hiệu quả để tính đồng thời gradient cho mọi tham số với chi phí tương đương một lượt lan truyền xuôi. Thuật toán duyệt ngược qua các lớp, truyền tín hiệu sai số và kết hợp với các giá trị trung gian đã lưu đệm để tính đạo hàm. Các cặp hàm mất mát và kích hoạt chuẩn mang lại biểu thức sai số đầu ra rất gọn (\(\boldsymbol{\delta}^{[L]} = \mathbf{a}^{[L]} - \mathbf{y}\)). Dù các framework hiện đại đã tự động hóa quy trình này bằng vi phân tự động chế độ ngược, việc hiểu rõ cơ chế bên trong — từ lưu đệm, kích thước ma trận đến nguyên nhân gradient biến mất hay bùng nổ — vẫn là nền tảng thiết yếu để gỡ lỗi và thiết kế mô hình hiệu quả.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Xây dựng từng dòng một bộ máy autograd gọn nhẹ để hiểu trọn vẹn lan truyền ngược.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=IN2XmBhILt4&quot;&gt;Neural Networks Pt. 2: Backpropagation Main Ideas&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa quy tắc dây chuyền trên đại lượng vô hướng để đối chiếu song song với mã nguồn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Xây dựng mạng nơ-ron nhân tạo từ con số 0&lt;/td&gt;
          &lt;td&gt;Writing a Neural Network from scratch](https://www.youtube.com/watch?v=VBviWbusHd8) — Học Lập Trình cùng Phát, tiếng Việt. Hướng dẫn viết mạng neuron từ đầu bằng tiếng Việt, bao gồm cả bước lan truyền ngược.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-03-01 Lý thuyết Lan truyền Ngược và Ví dụ Tính toán</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_03_01_Backprop_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_03_01_Backprop_Theory</id>
   <content type="html">&lt;p&gt;Nhiều sinh viên thấy công thức lan truyền ngược đầy chỉ số \(\delta_j^{(\ell)}, w_{jk}^{(\ell+1)}\) nên học thuộc lòng một cách máy móc, để rồi chỉ cần đổi hàm kích hoạt hay thêm một nhánh nối tắt là lập tức lúng túng. Thực ra, toàn bộ lý thuyết Backpropagation chỉ xoay quanh &lt;strong&gt;một quy tắc địa phương duy nhất&lt;/strong&gt; tại mỗi nút trong đồ thị tính toán: \(\text{gradient về đầu vào} = \text{gradient từ đầu ra} \times \text{đạo hàm cục bộ}\). Bài học này chứng minh tường minh bốn phương trình cơ bản của Backpropagation và dẫn bạn tính tay từng con số để biến công thức thành phản xạ tự nhiên.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-phương-trình-vàng-của-lan-truyền-ngược-dạng-ma-trận&quot;&gt;Kiến thức cần nhớ: Bốn phương trình Vàng của Lan truyền Ngược (Dạng Ma trận)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Sai số tại Tầng Đầu ra (\(\boldsymbol{\delta}^{(L)}\))&lt;/strong&gt;:
\(\boldsymbol{\delta}^{(L)} = \frac{\partial L}{\partial \mathbf{Z}^{(L)}} = \frac{\partial L}{\partial \mathbf{A}^{(L)}} \odot \sigma&apos;_L(\mathbf{Z}^{(L)})\). Riêng với tổ hợp vàng &lt;em&gt;Softmax + Cross-Entropy&lt;/em&gt; hoặc &lt;em&gt;Sigmoid + BCE&lt;/em&gt;, biểu thức rút gọn tuyệt đẹp còn \(\boldsymbol{\delta}^{(L)} = \hat{\mathbf{Y}} - \mathbf{Y}\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lan truyền Sai số Ngược về Tầng Trước (\(\boldsymbol{\delta}^{(\ell)}\))&lt;/strong&gt;:
\(\boldsymbol{\delta}^{(\ell)} = \big(\boldsymbol{\delta}^{(\ell+1)} \mathbf{W}^{(\ell+1)\top}\big) \odot \sigma&apos;_\ell(\mathbf{Z}^{(\ell)})\). Lưu ý vai trò của ma trận chuyển vị \(\mathbf{W}^{(\ell+1)\top}\) trong việc phân phối lại lỗi về từng nơ-ron tầng trước.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Gradient theo Trọng số và Độ lệch (\(\nabla_{\mathbf{W}^{(\ell)}} L,\; \nabla_{\mathbf{b}^{(\ell)}} L\))&lt;/strong&gt;:
Với mini-batch \(B\) mẫu: \(\frac{\partial L}{\partial \mathbf{W}^{(\ell)}} = \frac{1}{B}\mathbf{A}^{(\ell-1)\top} \boldsymbol{\delta}^{(\ell)}\) và \(\frac{\partial L}{\partial \mathbf{b}^{(\ell)}} = \frac{1}{B}\sum_{i=1}^B \boldsymbol{\delta}_i^{(\ell)}\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ba Cổng Phép toán Cơ bản trong Đồ thị Tính toán&lt;/strong&gt;:&lt;/p&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Cổng Cộng (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt;)&lt;/strong&gt;: phân phối nguyên vẹn gradient về cả hai nhánh.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Cổng Nhân (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;*&lt;/code&gt;)&lt;/strong&gt;: đổi chéo giá trị hai đầu vào khi nhân ngược gradient.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Cổng Max (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ReLU&lt;/code&gt;)&lt;/strong&gt;: chỉ dẫn gradient đi qua nhánh thắng (\(z &amp;gt; 0\)) và chặn về \(0\) ở nhánh thua.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-lan-truyền-ngược-qua-mạng-2-tầng-có-1-nút-ẩn-relu&quot;&gt;Giải thích: Tính tay Lan truyền Ngược qua mạng 2 tầng có 1 nút ẩn ReLU&lt;/h3&gt;

&lt;p&gt;Xét mạng chuỗi cực gọn \(x \xrightarrow{\times w_1} z_1 \xrightarrow{\text{ReLU}} a_1 \xrightarrow{\times w_2} \hat{y} \to L = \frac{1}{2}(\hat{y} - y)^2\) với \(x = 2,\; y = 1,\; w_1 = 0.5,\; w_2 = -2.0\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lượt Xuôi (Forward &amp;amp; Cache)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(z_1 = w_1 x = 0.5 \times 2 = 1.0\).&lt;/li&gt;
      &lt;li&gt;\(a_1 = \text{ReLU}(1.0) = 1.0\) (nằm trong miền dương nên \(\text{ReLU}&apos;(1.0) = 1\)).&lt;/li&gt;
      &lt;li&gt;\(\hat{y} = w_2 a_1 = (-2.0)(1.0) = -2.0\).&lt;/li&gt;
      &lt;li&gt;\(L = \frac{1}{2}(-2.0 - 1)^2 = \frac{1}{2}(-3)^2 = 4.5\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lượt Ngược (Backward từng bước)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Tại hàm mất mát: \(\frac{\partial L}{\partial \hat{y}} = \hat{y} - y = -2.0 - 1 = -3.0\).&lt;/li&gt;
      &lt;li&gt;Gradient cho \(w_2\): \(\frac{\partial L}{\partial w_2} = \frac{\partial L}{\partial \hat{y}} \cdot a_1 = (-3.0)(1.0) = \mathbf{-3.0}\).&lt;/li&gt;
      &lt;li&gt;Truyền lỗi qua cổng nhân \(w_2\) về \(a_1\): \(\frac{\partial L}{\partial a_1} = \frac{\partial L}{\partial \hat{y}} \cdot w_2 = (-3.0)(-2.0) = +6.0\).&lt;/li&gt;
      &lt;li&gt;Truyền qua cổng ReLU về \(z_1\): \(\frac{\partial L}{\partial z_1} = (+6.0) \times 1 = +6.0\).&lt;/li&gt;
      &lt;li&gt;Gradient cho \(w_1\): \(\frac{\partial L}{\partial w_1} = \frac{\partial L}{\partial z_1} \cdot x = (+6.0)(2) = \mathbf{+12.0}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Kiểm tra nhanh trực giác: vì \(w_2 = -2 &amp;lt; 0\) và \(\hat{y} = -2\) đang quá thấp so với \(y = 1\), muốn kéo \(\hat{y}\) tăng lên ta cần &lt;strong&gt;tăng \(w_2\)&lt;/strong&gt; (gradient \(-3 &amp;lt; 0\)) hoặc &lt;strong&gt;giảm \(w_1\)&lt;/strong&gt; (gradient \(+12 &amp;gt; 0\) để giảm \(a_1\) nhân với số âm \(w_2\)). Dấu và độ lớn đều khớp hoàn hảo!&lt;/p&gt;

&lt;h1 id=&quot;lan-truyền-ngược-động-cơ-của-học-sâu&quot;&gt;Lan truyền Ngược: Động cơ của Học sâu&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Backpropagation_example.svg/600px-Backpropagation_example.svg.png&quot; alt=&quot;Backpropagation Visualization&quot; /&gt;
&lt;em&gt;Hình ảnh: Minh họa quá trình lan truyền ngược (Backpropagation) trong mạng neuron. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Lan truyền ngược (&lt;em&gt;backpropagation&lt;/em&gt;) là thuật toán cốt lõi giúp việc huấn luyện mạng neuron sâu trở nên khả thi trong thực tế. Thuật toán này giải quyết một bài toán căn bản: với một mạng neuron có thể chứa hàng triệu tham số và một hàm đo sai số giữa dự đoán và nhãn thật, ta cần điều chỉnh từng tham số theo hướng nào để giảm sai số? Cách tiếp cận trực tiếp — ước lượng đạo hàm của từng tham số riêng lẻ bằng sai phân hữu hạn — đòi hỏi hàng triệu lượt lan truyền xuôi cho mỗi mẫu huấn luyện, vượt quá khả năng tính toán thực tế. Ngược lại, lan truyền ngược tính đồng thời gradient cho toàn bộ tham số với chi phí chỉ tương đương khoảng một lượt lan truyền xuôi.&lt;/p&gt;

&lt;p&gt;Ý tưởng then chốt của lan truyền ngược là &lt;strong&gt;tái sử dụng các phép tính trung gian&lt;/strong&gt;. Khi tính độ nhạy của hàm mất mát theo một tham số ở các lớp sâu, ta áp dụng quy tắc dây chuyền (&lt;em&gt;chain rule&lt;/em&gt;) của giải tích theo thứ tự từ đầu ra ngược về đầu vào. Thay vì tính lại toàn bộ chuỗi đạo hàm cho từng tham số riêng biệt, thuật toán tính các đạo hàm trung gian một lần rồi truyền ngược lại để dùng chung. Tư duy quy hoạch động này rút giảm độ phức tạp xuống mức tuyến tính theo kích thước mạng, giúp việc huấn luyện thực hiện được trên quy mô lớn.&lt;/p&gt;

&lt;p&gt;Một ưu điểm nổi bật khác của lan truyền ngược là tính mô-đun cục bộ. Mỗi lớp chỉ cần biết cách tính đạo hàm cục bộ của mình — tức đầu ra thay đổi thế nào theo đầu vào và tham số của lớp đó. Khi huấn luyện, lớp nhận tín hiệu gradient từ lớp kế tiếp và truyền gradient xuống lớp đứng trước. Nhờ tính chất này, ta có thể kết hợp tự do nhiều loại lớp khác nhau (tích chập, hồi quy, attention,…) trong cùng một kiến trúc; miễn là mọi phép toán đều khả vi, lan truyền ngược sẽ hoạt động thống nhất trên toàn bộ đồ thị tính toán.&lt;/p&gt;

&lt;p&gt;Hiểu sâu lan truyền ngược không chỉ là thuộc công thức, mà còn là nắm rõ các giả định và giới hạn đi kèm. Thuật toán yêu cầu các phép toán khả vi — đây là lý do hàm kích hoạt cần trơn hoặc khả vi từng khúc. Nó cần lưu giữ các giá trị trung gian từ lượt xuôi — đây là nguyên nhân bộ nhớ GPU giới hạn kích thước batch. Hơn nữa, vì tín hiệu sai số bị nhân liên tiếp với ma trận trọng số khi đi ngược qua các lớp, trọng số quá lớn hoặc quá nhỏ sẽ dẫn tới gradient bùng nổ hoặc biến mất. Đây là những đặc tính nền tảng ảnh hưởng trực tiếp tới cách thiết kế và huấn luyện mạng.&lt;/p&gt;

&lt;p&gt;Về mặt lịch sử, dù gradient descent và quy tắc dây chuyền đã có từ rất lâu, việc kết hợp chúng thành thuật toán lan truyền ngược hiệu quả cho mạng nhiều lớp đã khôi phục lại lĩnh vực mạng neuron vào thập niên 1980 sau mùa đông AI lần thứ nhất. Thuật toán được phát hiện độc lập nhiều lần (như Werbos năm 1974 và Rumelhart, Hinton, Williams năm 1986), trong đó bài báo trên tạp chí &lt;em&gt;Nature&lt;/em&gt; năm 1986 đã phổ biến rộng rãi phương pháp này và minh chứng hiệu quả trên các bài toán thực tế như nhận dạng giọng nói và phân loại ảnh.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Mục tiêu của huấn luyện là cực tiểu hóa hàm mất mát \(\mathcal{L}(\mathbf{y}, \hat{\mathbf{y}})\) đo sai lệch giữa dự đoán \(\hat{\mathbf{y}}\) và nhãn thực tế \(\mathbf{y}\). Mạng neuron là phép hợp của nhiều hàm lớp nối tiếp nhau, mỗi lớp chứa các tham số (trọng số và độ lệch) cần tối ưu. Theo gradient descent, mỗi tham số \(\theta\) được cập nhật ngược chiều gradient:&lt;/p&gt;

\[\theta \leftarrow \theta - \eta \frac{\partial \mathcal{L}}{\partial \theta}\]

&lt;p&gt;Bài toán đặt ra là tính \(\frac{\partial \mathcal{L}}{\partial \theta}\) nhanh và chính xác cho tất cả tham số. Hãy bắt đầu với một mạng hai lớp đơn giản rồi mở rộng sang mạng tổng quát.&lt;/p&gt;

&lt;p&gt;Xét mạng có đầu vào \(\mathbf{x}\), một lớp ẩn với kích hoạt \(\mathbf{h}\) và đầu ra \(\hat{\mathbf{y}}\). Lượt lan truyền xuôi thực hiện:&lt;/p&gt;

&lt;p&gt;\(\mathbf{z}^{[1]} = \mathbf{W}^{[1]} \mathbf{x} + \mathbf{b}^{[1]}\)
\(\mathbf{h} = \mathbf{a}^{[1]} = g^{[1]}(\mathbf{z}^{[1]})\)
\(\mathbf{z}^{[2]} = \mathbf{W}^{[2]} \mathbf{h} + \mathbf{b}^{[2]}\)
\(\hat{\mathbf{y}} = \mathbf{a}^{[2]} = g^{[2]}(\mathbf{z}^{[2]})\)
\(\mathcal{L} = \mathcal{L}(\mathbf{y}, \hat{\mathbf{y}})\)&lt;/p&gt;

&lt;p&gt;trong đó \(g^{[l]}\) là hàm kích hoạt tại lớp \(l\). Để tính \(\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[1]}}\), ta áp dụng quy tắc dây chuyền:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[1]}} = \frac{\partial \mathcal{L}}{\partial \hat{\mathbf{y}}} \frac{\partial \hat{\mathbf{y}}}{\partial \mathbf{z}^{[2]}} \frac{\partial \mathbf{z}^{[2]}}{\partial \mathbf{h}} \frac{\partial \mathbf{h}}{\partial \mathbf{z}^{[1]}} \frac{\partial \mathbf{z}^{[1]}}{\partial \mathbf{W}^{[1]}}\]

&lt;p&gt;Thay vì nhân trực tiếp nhiều ma trận Jacobian tốn kém, lan truyền ngược tính tích này từ phía đầu ra (từ trái sang phải theo biểu thức trên, tức đi ngược qua các lớp) và lưu dùng lại các đại lượng trung gian.&lt;/p&gt;

&lt;p&gt;Ta định nghĩa vector sai số (&lt;em&gt;error term&lt;/em&gt;) của lớp \(l\) là:&lt;/p&gt;

\[\boldsymbol{\delta}^{[l]} = \frac{\partial \mathcal{L}}{\partial \mathbf{z}^{[l]}}\]

&lt;p&gt;Đại lượng này cho biết hàm mất mát nhạy cảm thế nào với thay đổi ở giá trị tiền kích hoạt của lớp \(l\). Xét lớp đầu ra dùng hàm mất mát entropy chéo nhị phân kết hợp với kích hoạt sigmoid:&lt;/p&gt;

\[\boldsymbol{\delta}^{[L]} = \frac{\partial \mathcal{L}}{\partial \mathbf{z}^{[L]}} = \frac{\partial \mathcal{L}}{\partial \mathbf{a}^{[L]}} \frac{\partial \mathbf{a}^{[L]}}{\partial \mathbf{z}^{[L]}}\]

&lt;p&gt;Ta có đạo hàm của mất mát là \(\frac{\partial \mathcal{L}}{\partial \mathbf{a}^{[L]}} = -\frac{\mathbf{y}}{\mathbf{a}^{[L]}} + \frac{1-\mathbf{y}}{1-\mathbf{a}^{[L]}}\), còn đạo hàm của sigmoid là \(\frac{\partial \mathbf{a}^{[L]}}{\partial \mathbf{z}^{[L]}} = \mathbf{a}^{[L]}(1-\mathbf{a}^{[L]})\). Khi nhân hai biểu thức này lại, các thừa số ở mẫu triệt tiêu hoàn toàn, chỉ còn lại:&lt;/p&gt;

\[\boldsymbol{\delta}^{[L]} = \mathbf{a}^{[L]} - \mathbf{y}\]

&lt;p&gt;Kết quả gọn gàng này — sai số tại lớp đầu ra bằng đúng hiệu giữa dự đoán và nhãn thật — cũng xuất hiện ở các cặp hàm mất mát và kích hoạt chuẩn khác (như MSE với kích hoạt tuyến tính, hoặc entropy chéo đa lớp với softmax). Các cặp này được thiết kế tương thích với nhau chính để tạo ra gradient đơn giản và ổn định.&lt;/p&gt;

&lt;p&gt;Đối với các lớp ẩn, tín hiệu sai số được truyền ngược từ lớp \(l+1\) về lớp \(l\) theo công thức:&lt;/p&gt;

\[\boldsymbol{\delta}^{[l]} = (\mathbf{W}^{[l+1]})^T \boldsymbol{\delta}^{[l+1]} \odot g&apos;^{[l]}(\mathbf{z}^{[l]})\]

&lt;p&gt;Phương trình này thể hiện đúng cơ chế cốt lõi của lan truyền ngược. Số hạng \((\mathbf{W}^{[l+1]})^T \boldsymbol{\delta}^{[l+1]}\) phân bổ sai số từ lớp \(l+1\) về lớp \(l\) theo độ lớn của các trọng số kết nối: neuron ẩn nào nối mạnh tới các neuron có sai số lớn ở lớp sau sẽ nhận tín hiệu sai số lớn hơn. Tiếp theo, phép nhân theo từng phần tử (tích Hadamard) \(\odot g&apos;^{[l]}(\mathbf{z}^{[l]})\) điều chỉnh tín hiệu này theo độ dốc cục bộ của hàm kích hoạt. Nếu hàm kích hoạt rơi vào vùng bão hòa (đạo hàm gần 0), tín hiệu sai số sẽ bị suy giảm mạnh — đó chính là nguồn gốc của hiện tượng gradient biến mất ở mạng sâu dùng sigmoid hoặc tanh.&lt;/p&gt;

&lt;p&gt;Khi đã tính được \(\boldsymbol{\delta}^{[l]}\), gradient theo trọng số và độ lệch của lớp \(l\) được suy ra trực tiếp:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[l]}} = \boldsymbol{\delta}^{[l]} (\mathbf{a}^{[l-1]})^T\]

\[\frac{\partial \mathcal{L}}{\partial \mathbf{b}^{[l]}} = \boldsymbol{\delta}^{[l]}\]

&lt;p&gt;Gradient theo trọng số là tích ngoài giữa tín hiệu sai số của lớp hiện tại và kích hoạt đầu vào từ lớp trước: nếu cả kích hoạt đầu vào lẫn sai số đều lớn thì trọng số kết nối giữa chúng cần điều chỉnh mạnh. Gradient theo độ lệch bằng đúng tín hiệu sai số vì độ lệch luôn tương ứng với đầu vào hằng bằng 1.&lt;/p&gt;

&lt;p&gt;Xét về độ phức tạp tính toán, một lượt lan truyền xuôi qua mạng \(L\) lớp, mỗi lớp \(n\) neuron, với batch kích thước \(m\) tốn \(O(L \cdot n^2 \cdot m)\) phép toán (chủ yếu là nhân ma trận). Lượt lan truyền ngược cũng có cùng bậc độ phức tạp \(O(L \cdot n^2 \cdot m)\) — nghĩa là tính toàn bộ gradient cho mọi tham số chỉ tốn thời gian tương đương một lượt xuôi. Trong khi đó, ước lượng bằng sai phân hữu hạn đòi hỏi \(O(P)\) lượt xuôi với \(P\) là tổng số tham số. Mức giảm chi phí từ bậc hai xuống tuyến tính theo số tham số này chính là yếu tố giúp học sâu có thể huấn luyện được các mô hình lớn.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ--trực-giác&quot;&gt;3. Ví dụ / Trực giác&lt;/h2&gt;

&lt;p&gt;Để thấy rõ từng phép tính của lan truyền ngược, ta xét một ví dụ cụ thể bằng số: mạng hai lớp cho bài toán phân loại nhị phân gồm 2 đầu vào, 2 neuron ẩn dùng ReLU và 1 đầu ra dùng sigmoid.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiến trúc mạng:&lt;/strong&gt;
\(\mathbf{x} \in \mathbb{R}^2 \xrightarrow{\mathbf{W}^{[1]}, \mathbf{b}^{[1]}} \mathbf{z}^{[1]} \in \mathbb{R}^2 \xrightarrow{\text{ReLU}} \mathbf{a}^{[1]} \in \mathbb{R}^2 \xrightarrow{\mathbf{W}^{[2]}, \mathbf{b}^{[2]}} z^{[2]} \in \mathbb{R} \xrightarrow{\text{Sigmoid}} \hat{y} \in (0,1)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tham số khởi tạo:&lt;/strong&gt;
\(\mathbf{W}^{[1]} = \begin{bmatrix} 0.5 &amp;amp; -0.3 \\ 0.2 &amp;amp; 0.8 \end{bmatrix}, \quad \mathbf{b}^{[1]} = \begin{bmatrix} 0.1 \\ -0.2 \end{bmatrix}\)&lt;/p&gt;

\[\mathbf{W}^{[2]} = \begin{bmatrix} 1.0 &amp;amp; -0.5 \end{bmatrix}, \quad b^{[2]} = 0.5\]

&lt;p&gt;&lt;strong&gt;Đầu vào và nhãn:&lt;/strong&gt; \(\mathbf{x} = \begin{bmatrix} 1.0 \\ 2.0 \end{bmatrix}\), \(y = 1\) (lớp dương).&lt;/p&gt;

&lt;p&gt;Bây giờ ta lần lượt thực hiện lan truyền xuôi và lan truyền ngược.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lan truyền Xuôi:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{z}^{[1]} = \begin{bmatrix} 0.5 &amp;amp; -0.3 \\ 0.2 &amp;amp; 0.8 \end{bmatrix} \begin{bmatrix} 1.0 \\ 2.0 \end{bmatrix} + \begin{bmatrix} 0.1 \\ -0.2 \end{bmatrix} = \begin{bmatrix} 0.5 - 0.6 + 0.1 \\ 0.2 + 1.6 - 0.2 \end{bmatrix} = \begin{bmatrix} 0.0 \\ 1.6 \end{bmatrix}\]

&lt;p&gt;Neuron ẩn thứ nhất có \(z^{[1]}_1 = 0\) (ngay tại ngưỡng ReLU), còn neuron thứ hai có \(z^{[1]}_2 = 1.6\) (dương mạnh). Áp dụng ReLU:&lt;/p&gt;

\[\mathbf{a}^{[1]} = \max(0, \mathbf{z}^{[1]}) = \begin{bmatrix} 0.0 \\ 1.6 \end{bmatrix}\]

&lt;p&gt;Chỉ neuron thứ hai hoạt động và truyền tín hiệu sang lớp đầu ra:&lt;/p&gt;

\[z^{[2]} = \begin{bmatrix} 1.0 &amp;amp; -0.5 \end{bmatrix} \begin{bmatrix} 0.0 \\ 1.6 \end{bmatrix} + 0.5 = 0 - 0.8 + 0.5 = -0.3\]

&lt;p&gt;Giá trị tiền kích hoạt hơi âm cho thấy mô hình hiện nghiêng về dự đoán lớp 0. Áp dụng sigmoid:&lt;/p&gt;

\[\hat{y} = \sigma(-0.3) = \frac{1}{1 + e^{0.3}} \approx 0.426\]

&lt;p&gt;Mô hình dự đoán xác suất thuộc lớp 1 là 42.6%, trong khi nhãn thật là 1. Giá trị mất mát entropy chéo nhị phân bằng:&lt;/p&gt;

\[\mathcal{L} = -[1 \cdot \log(0.426) + 0 \cdot \log(1-0.426)] = -\log(0.426) \approx 0.853\]

&lt;p&gt;Bây giờ lan truyền ngược sẽ xác định hướng cập nhật cho từng trọng số để giảm mức sai số này.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lan truyền Ngược:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Bắt đầu từ lớp đầu ra, sai số bằng:&lt;/p&gt;

\[\delta^{[2]} = \hat{y} - y = 0.426 - 1 = -0.574\]

&lt;p&gt;Sai số âm cho biết đầu ra dự đoán đang thấp hơn nhãn thật và cần được tăng lên. Gradient theo trọng số lớp đầu ra là:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[2]}} = \delta^{[2]} (\mathbf{a}^{[1]})^T = -0.574 \times \begin{bmatrix} 0.0 &amp;amp; 1.6 \end{bmatrix} = \begin{bmatrix} 0 &amp;amp; -0.918 \end{bmatrix}\]

&lt;p&gt;Kết nối từ neuron ẩn thứ nhất có gradient bằng 0 (vì \(a^{[1]}_1 = 0\)), còn kết nối từ neuron thứ hai có gradient là \(-0.918\). Khi cập nhật bằng gradient descent (trừ đi \(\eta \cdot \text{gradient}\)), giá trị \(W^{[2]}_2\) (đang là \(-0.5\)) sẽ tăng lên (bớt âm hơn), từ đó kéo đầu ra \(z^{[2]}\) và \(\hat{y}\) tăng lên gần 1 hơn.&lt;/p&gt;

&lt;p&gt;Tiếp theo, ta truyền sai số ngược về lớp ẩn:&lt;/p&gt;

\[\boldsymbol{\delta}^{[1]} = (\mathbf{W}^{[2]})^T \delta^{[2]} \odot \text{ReLU}&apos;(\mathbf{z}^{[1]})\]

&lt;p&gt;Tính từng thành phần:&lt;/p&gt;

\[(\mathbf{W}^{[2]})^T \delta^{[2]} = \begin{bmatrix} 1.0 \\ -0.5 \end{bmatrix} \times (-0.574) = \begin{bmatrix} -0.574 \\ 0.287 \end{bmatrix}\]

&lt;p&gt;Đạo hàm của ReLU bằng 1 với đầu vào dương và bằng 0 tại các điểm còn lại (theo quy ước \(\text{ReLU}&apos;(0) = 0\)):&lt;/p&gt;

\[\text{ReLU}&apos;(\mathbf{z}^{[1]}) = \text{ReLU}&apos;\begin{pmatrix} \begin{bmatrix} 0.0 \\ 1.6 \end{bmatrix} \end{pmatrix} = \begin{bmatrix} 0 \\ 1 \end{bmatrix}\]

&lt;p&gt;Neuron ẩn thứ nhất nằm đúng tại ngưỡng \(z = 0\) nên không truyền gradient qua — đây là minh họa trực tiếp cho cơ chế ReLU chặn gradient ở miền không dương. Lấy tích theo từng phần tử:&lt;/p&gt;

\[\boldsymbol{\delta}^{[1]} = \begin{bmatrix} -0.574 \\ 0.287 \end{bmatrix} \odot \begin{bmatrix} 0 \\ 1 \end{bmatrix} = \begin{bmatrix} 0 \\ 0.287 \end{bmatrix}\]

&lt;p&gt;Cuối cùng, tính gradient theo trọng số lớp đầu vào:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[1]}} = \boldsymbol{\delta}^{[1]} \mathbf{x}^T = \begin{bmatrix} 0 \\ 0.287 \end{bmatrix} \begin{bmatrix} 1.0 &amp;amp; 2.0 \end{bmatrix} = \begin{bmatrix} 0 &amp;amp; 0 \\ 0.287 &amp;amp; 0.574 \end{bmatrix}\]

&lt;p&gt;Chỉ các trọng số của neuron ẩn thứ hai nhận gradient khác 0. Vì cả hai gradient đều dương (\(+0.287\) và \(+0.574\)), bước cập nhật gradient descent (\(\mathbf{W}^{[1]} \leftarrow \mathbf{W}^{[1]} - \eta \nabla \mathbf{W}^{[1]}\)) sẽ &lt;strong&gt;giảm&lt;/strong&gt; cả hai trọng số này. Điều này hoàn toàn nhất quán về mặt toán học: do trọng số nối sang đầu ra \(W^{[2]}_2 = -0.5\) đang âm, việc giảm kích hoạt \(a^{[1]}_2\) sẽ làm giảm phần đóng góp âm \(-0.5 \cdot a^{[1]}_2\) vào \(z^{[2]}\), nhờ đó đẩy dự đoán \(\hat{y}\) tăng lên gần mục tiêu 1 hơn.&lt;/p&gt;

&lt;p&gt;Ví dụ từng bước trên cho thấy rõ logic của lan truyền ngược: sai số đi ngược từ đầu ra về các lớp trước và được điều chỉnh bởi trọng số kết nối cùng đạo hàm cục bộ của hàm kích hoạt. Những neuron đang hoạt động và nối mạnh tới đầu ra sẽ nhận gradient lớn hơn, còn những neuron tắt hoặc nối yếu sẽ ít thay đổi. Nhờ cơ chế phân bổ sai số tự động này, mọi tham số trong mạng đều được cập nhật tỷ lệ thuận với mức độ ảnh hưởng của nó lên sai số cuối cùng.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Backpropagation, intuitively&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 3](https://www.youtube.com/watch?v=Ilg3gGewQ5U) — 3Blue1Brown, tiếng Anh. Diễn giải trực quan cách một mẫu huấn luyện tạo ra lực đẩy cập nhật lên các trọng số.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Backpropagation calculus&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 4](https://www.youtube.com/watch?v=tIeHLnjs5U8) — 3Blue1Brown, tiếng Anh. Trình bày chi tiết phép tính quy tắc dây chuyền tương ứng với ví dụ số trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=IN2XmBhILt4&quot;&gt;Neural Networks Pt. 2: Backpropagation Main Ideas&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa một lượt lan truyền ngược gắn nhãn rõ từng bước, tiện đối chiếu với ví dụ tính toán trên.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-02 Gradient Descent</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_02_Gradient_Descent/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_02_Gradient_Descent</id>
   <content type="html">&lt;p&gt;Đã có bản đồ sai số (hàm mất mát), bước tiếp theo là trả lời câu hỏi cốt lõi nhất của tối ưu hóa: &lt;em&gt;làm thế nào để điều chỉnh hàng triệu trọng số cùng lúc sao cho hàm mất mát tụt xuống đáy nhanh và ổn định nhất?&lt;/em&gt; Câu trả lời mang tính biểu tượng của cả ngành Học sâu là &lt;strong&gt;Gradient Descent&lt;/strong&gt;—thuật toán xuống dốc từng bước ngược hướng vector gradient. Mục tổng quan này phác họa bức tranh chung về quy tắc cập nhật, ba biến thể theo kích thước batch và những cạm bẫy hình học sẽ được mổ xẻ sâu ở hai bài kế tiếp.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-của-thuật-toán-gradient-descent&quot;&gt;Kiến thức cần nhớ: Ba trụ cột của Thuật toán Gradient Descent&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Quy tắc Cập nhật và Vai trò của Learning Rate (\(\theta_{t+1} = \theta_t - \eta \nabla L(\theta_t)\))&lt;/strong&gt;:
\(\eta\) quá nhỏ khiến huấn luyện rùa bò và dễ mắc kẹt; \(\eta\) quá lớn khiến tham số bật qua lại hai bờ thung lũng và phân kỳ về vô cực.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ba chế độ ước lượng Gradient (Batch, SGD, Mini-Batch)&lt;/strong&gt;:
Đánh đổi giữa độ chính xác của hướng đi (Batch GD), tốc độ cập nhật và nhiễu giúp thoát cực tiểu nông (SGD), và hiệu suất tận dụng song song GPU (Mini-Batch GD—chuẩn mực thực tế).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Địa hình Bề mặt Mất mát Phi lồi (Non-Convex Landscape)&lt;/strong&gt;:
Khác với bài toán lồi chỉ có 1 đáy duy nhất, bề mặt mất mát của mạng sâu đầy rẫy điểm yên ngựa (&lt;em&gt;saddle points&lt;/em&gt;), thung lũng hẹp dài (&lt;em&gt;ill-conditioned ravines&lt;/em&gt;) và vùng phẳng (&lt;em&gt;plateaus&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-thấy-ngay-tác-động-của-learning-rate-trên-parabol-lw--w2&quot;&gt;Giải thích: Thấy ngay tác động của Learning Rate trên parabol \(L(w) = w^2\)&lt;/h3&gt;

&lt;p&gt;Xét hàm đơn giản \(L(w) = w^2\) (đáy tại \(w^* = 0\)), có đạo hàm \(L&apos;(w) = 2w\). Xuất phát từ \(w_0 = 4\), công thức cập nhật là \(w_{t+1} = w_t - \eta(2w_t) = (1 - 2\eta)w_t\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Learning rate \(\eta\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Hệ số co \((1 - 2\eta)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Chuỗi \(w_0 \to w_1 \to w_2 \to w_3\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hành vi hội tụ&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(\eta = 0.05\) (Nhỏ)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.9\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4.0 \to 3.6 \to 3.24 \to 2.916\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Hội tụ êm nhưng chậm&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(\eta = 0.50\) (Lý tưởng)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4.0 \to 0.0 \to 0.0 \to 0.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Chạm đáy trong đúng &lt;strong&gt;1 bước&lt;/strong&gt;!&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(\eta = 0.90\) (Hơi lớn)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(-0.8\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4.0 \to -3.2 \to +2.56 \to -2.048\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Dao động nhảy qua lại hai bờ&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(\eta = 1.10\) (Quá lớn)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(-1.2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(4.0 \to -4.8 \to +5.76 \to -6.912\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Phân kỳ nổ tung!&lt;/strong&gt; (\(\lvert 1-2\eta \rvert &amp;gt; 1\))&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Bất đẳng thức vàng rút ra ngay từ bảng trên: để hội tụ trên parabol độ cong \(H = 2\), điều kiện bắt buộc là \(0 &amp;lt; \eta &amp;lt; \frac{2}{H} = 1\)!&lt;/p&gt;

&lt;p&gt;Phần này trình bày thuật toán gradient descent và các biến thể thực tế:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Các biến thể Gradient Descent và Learning Rate&lt;/strong&gt; — Batch GD, SGD, Mini-batch GD và lịch trình điều chỉnh tốc độ học&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Triển khai và thách thức&lt;/strong&gt; — mã nguồn cài đặt, tiêu chí hội tụ và các khó khăn thường gặp khi tối ưu&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, tiếng Anh. Minh họa trực giác quá trình đi xuống dốc của gradient descent.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Ví dụ tính từng bước cập nhật bằng số kèm cách chọn tốc độ học.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vMh0zPT0tLI&quot;&gt;Stochastic Gradient Descent, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích SGD để so sánh trực tiếp với Batch Gradient Descent.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-02-02 Triển khai Gradient Descent và Thách thức</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_02_02_GD_Implementation_and_Challenges/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_02_02_GD_Implementation_and_Challenges</id>
   <content type="html">&lt;p&gt;Viết công thức &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w = w - lr * grad&lt;/code&gt; chỉ tốn đúng một dòng code, nhưng đưa Gradient Descent vào huấn luyện mạng sâu thực tế lại giống như lái xe địa hình qua sa mạc đầy bẫy cát lún: hẻm núi dốc hẹp khiến tham số đập qua đập lại mãi không tiến tới, điểm yên ngựa làm gradient gần như bằng 0, và đặc trưng chưa chuẩn hóa khiến mặt cắt hàm mất mát méo xệch. Bài học này hướng dẫn cách triển khai Mini-Batch GD sạch sẽ bằng mã nguồn, đồng thời giải phẫu các thách thức hình học kinh điển mở đường cho Momentum và Adam.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-thách-thức-thực-chiến-khi-triển-khai-gradient-descent&quot;&gt;Kiến thức cần nhớ: Bốn thách thức thực chiến khi Triển khai Gradient Descent&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hẻm núi hẹp mất cân bằng độ cong (Ill-Conditioned Ravines)&lt;/strong&gt;:
Khi một chiều có độ cong (giá trị riêng Hessian) lớn gấp trăm lần chiều kia, Gradient Descent buộc phải dùng \(\eta\) rất nhỏ để không nổ ở chiều dốc, dẫn tới lê lết cực chậm ở chiều phẳng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Điểm Yên ngựa (Saddle Points) thay vì Cực tiểu Địa phương&lt;/strong&gt;:
Trong không gian hàng triệu chiều, cực tiểu địa phương thực sự rất hiếm (đòi hỏi &lt;em&gt;mọi&lt;/em&gt; chiều đều cong lên); thứ cản đường chủ yếu là &lt;strong&gt;điểm yên ngựa&lt;/strong&gt;—nơi gradient \(\approx \mathbf{0}\) nhưng vẫn có hướng cong xuống để thoát ra.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tầm quan trọng của Xáo trộn Dữ liệu (Shuffling) và Chuẩn hóa Đặc trưng (Feature Scaling)&lt;/strong&gt;:
Nếu không xáo trộn trước mỗi epoch, các batch liên tiếp bị lệch nhãn làm hướng cập nhật dao động tuần hoàn; nếu không chuẩn hóa đặc trưng về cùng thang đo, đường đồng mức bị kéo dẹt thành hình elip cực hẹp.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lịch sử Động lượng (Momentum) &amp;amp; Cắt ngưỡng Gradient (Gradient Clipping)&lt;/strong&gt;:
Cộng dồn vận tốc quá khứ \(\mathbf{v}_t = \beta \mathbf{v}_{t-1} + \nabla L\) giúp triệt tiêu dao động zig-zag và tăng tốc dọc đáy hẻm núi; còn Gradient Clipping chặn đứng những cú nhảy đột biến do vách đá dựng đứng.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-hiện-tượng-zig-zag-trên-thung-lũng-elip-lx-y--frac12x2--10y2&quot;&gt;Giải thích: Tính tay hiện tượng Zig-Zag trên thung lũng elip \(L(x, y) = \frac{1}{2}(x^2 + 10y^2)\)&lt;/h3&gt;

&lt;p&gt;Xét bề mặt có độ cong trục \(y\) gấp 10 lần trục \(x\), với gradient \(\nabla L = (x,\; 10y)\). Xuất phát từ \((x_0, y_0) = (10, 1)\) và thử bước học \(\eta = 0.18\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1&lt;/strong&gt;: \(\nabla L(10, 1) = (10,\; 10)\).
    &lt;ul&gt;
      &lt;li&gt;\(x_1 = 10 - 0.18(10) = 8.20\) (tiến chậm về 0).&lt;/li&gt;
      &lt;li&gt;\(y_1 = 1 - 0.18(10) = -0.80\) (&lt;strong&gt;nhảy vọt sang bờ bên kia!&lt;/strong&gt;).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2&lt;/strong&gt;: \(\nabla L(8.2, -0.8) = (8.2,\; -8.0)\).
    &lt;ul&gt;
      &lt;li&gt;\(x_2 = 8.20 - 0.18(8.2) = 6.724\).&lt;/li&gt;
      &lt;li&gt;\(y_2 = -0.80 - 0.18(-8.0) = +0.64\) (&lt;strong&gt;lại bật ngược lại!&lt;/strong&gt;).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quan sát chẩn đoán&lt;/strong&gt;: Trục \(y\) cứ đổi dấu liên tục \(+1 \to -0.8 \to +0.64 \to -0.512\) lãng phí phần lớn năng lượng, còn nếu tăng \(\eta \ge 0.2\) thì trục \(y\) lập tức phân kỳ! Đây chính là lý do trực giác khiến việc chuẩn hóa đặc trưng và thêm &lt;strong&gt;Momentum&lt;/strong&gt; lại tạo ra khác biệt một trời một vực khi huấn luyện thực tế.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;triển-khai&quot;&gt;Triển khai&lt;/h2&gt;

&lt;h3 id=&quot;gradient-descent-cơ-bản&quot;&gt;Gradient Descent Cơ bản&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Gradient descent cơ bản cho hồi quy tuyến tính
    
    X: ma trận đầu vào (m, n)
    y: vectơ mục tiêu (m, 1)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Khởi tạo tham số
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Lan truyền xuôi: dự đoán
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính chi phí
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính gradient
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Cập nhật tham số
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# In tiến độ
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Iteration &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Cost = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ sử dụng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 100 mẫu, 3 đặc trưng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 100 mục tiêu
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_optimal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;costs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;mini-batch-gradient-descent&quot;&gt;Mini-Batch Gradient Descent&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mini_batch_gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Mini-batch gradient descent
    
    X: ma trận đầu vào (m, n)
    y: vectơ mục tiêu (m, 1)
    batch_size: kích thước mỗi mini-batch
    num_epochs: số lần quét đầy đủ tập dữ liệu
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Xáo trộn dữ liệu
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;permutation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Xử lý các mini-batch
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Lấy batch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;y_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Lan truyền xuôi
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Tính gradient trên batch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cập nhật tham số
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính chi phí trên toàn tập (để giám sát)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;y_pred_full&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred_full&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Cost = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ sử dụng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_optimal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;costs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mini_batch_gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
    &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
    &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
    &lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;kết-hợp-lịch-điều-chỉnh-tốc-độ-học&quot;&gt;Kết hợp Lịch Điều chỉnh Tốc độ Học&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LearningRateSchedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;get_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;decay_rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;decay_steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;decay_steps&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decay_steps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;exponential&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;decay_rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;inverse&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;decay_rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent_with_schedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient descent với lịch learning rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;lr_schedule&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LearningRateSchedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decay_steps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Lấy learning rate hiện tại
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_schedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tính xuôi và gradient
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Cập nhật với learning rate hiện tại
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Iteration &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: LR = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Cost = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ sử dụng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent_with_schedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;tiêu-chí-hội-tụ&quot;&gt;Tiêu chí Hội tụ&lt;/h2&gt;

&lt;p&gt;Trong thực tế, ta xác định thời điểm dừng huấn luyện bằng một hoặc nhiều tiêu chí sau:&lt;/p&gt;

&lt;h3 id=&quot;1-giới-hạn-số-vòng-lặp&quot;&gt;1. Giới hạn Số Vòng lặp&lt;/h3&gt;

&lt;p&gt;Dừng sau một số vòng lặp hoặc epoch định sẵn.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;2-ngưỡng-chi-phí&quot;&gt;2. Ngưỡng Chi phí&lt;/h3&gt;

&lt;p&gt;Dừng khi giá trị hàm chi phí giảm xuống dưới một ngưỡng đặt trước.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;3-độ-lớn-gradient&quot;&gt;3. Độ lớn Gradient&lt;/h3&gt;

&lt;p&gt;Dừng khi chuẩn của vector gradient đủ nhỏ (gần điểm dừng).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;4-mức-thay-đổi-chi-phí&quot;&gt;4. Mức thay đổi Chi phí&lt;/h3&gt;

&lt;p&gt;Dừng khi hàm chi phí không còn giảm đáng kể giữa các bước liên tiếp.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;previous_cost&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;5-mất-mát-trên-tập-kiểm-định-phổ-biến-nhất-trong-học-sâu&quot;&gt;5. Mất mát trên Tập Kiểm định (Phổ biến nhất trong Học sâu)&lt;/h3&gt;

&lt;p&gt;Dừng khi mất mát trên tập kiểm định (&lt;em&gt;validation loss&lt;/em&gt;) ngừng cải thiện sau một số epoch liên tiếp (kỹ thuật dừng sớm — &lt;em&gt;early stopping&lt;/em&gt;).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;validation_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_validation_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;patience_counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;patience_counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;best_validation_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;validation_loss&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;patience_counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;các-thách-thức-với-gradient-descent&quot;&gt;Các Thách thức với Gradient Descent&lt;/h2&gt;

&lt;h3 id=&quot;1-cực-tiểu-cục-bộ&quot;&gt;1. Cực tiểu Cục bộ&lt;/h3&gt;

&lt;p&gt;Các hàm mất mát không lồi (như ở mạng neuron sâu) thường có nhiều cực tiểu cục bộ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hướng xử lý:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Khởi tạo ngẫu nhiên để thử nhiều điểm xuất phát khác nhau&lt;/li&gt;
  &lt;li&gt;Sử dụng momentum (sẽ học trong bài về các bộ tối ưu nâng cao)&lt;/li&gt;
  &lt;li&gt;Áp dụng &lt;em&gt;simulated annealing&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-điểm-yên-ngựa&quot;&gt;2. Điểm Yên ngựa&lt;/h3&gt;

&lt;p&gt;Là những điểm có gradient bằng 0 nhưng không phải cực tiểu mà dốc lên theo một số phương và dốc xuống theo các phương khác.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hướng xử lý:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Sử dụng momentum và các bộ tối ưu có tốc độ học thích nghi để thoát khỏi vùng yên ngựa&lt;/li&gt;
  &lt;li&gt;Áp dụng phương pháp tối ưu bậc hai (như phương pháp Newton)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-vùng-bằng-phẳng-plateau&quot;&gt;3. Vùng Bằng phẳng (&lt;em&gt;Plateau&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Những vùng có độ dốc rất nhỏ khiến tham số cập nhật cực chậm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hướng xử lý:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Huấn luyện thêm số bước đủ lớn&lt;/li&gt;
  &lt;li&gt;Kết hợp lịch trình điều chỉnh tốc độ học&lt;/li&gt;
  &lt;li&gt;Chuyển sang các bộ tối ưu thích nghi như Adam hoặc RMSprop&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-gradient-biến-mất-và-bùng-nổ&quot;&gt;4. Gradient Biến mất và Bùng nổ&lt;/h3&gt;

&lt;p&gt;Trong mạng sâu, gradient có thể suy giảm nhanh về 0 hoặc tăng vọt mất kiểm soát.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hướng xử lý:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Khởi tạo trọng số hợp lý (Xavier, He)&lt;/li&gt;
  &lt;li&gt;Áp dụng batch normalization&lt;/li&gt;
  &lt;li&gt;Sử dụng kết nối tắt (&lt;em&gt;residual connections&lt;/em&gt;)&lt;/li&gt;
  &lt;li&gt;Cắt ngưỡng gradient (&lt;em&gt;gradient clipping&lt;/em&gt;) để xử lý tình trạng bùng nổ&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Gradient descent&lt;/strong&gt; là thuật toán tối ưu nền tảng cho huấn luyện mạng neuron.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy tắc cập nhật:&lt;/strong&gt; \(\theta := \theta - \eta \nabla_{\theta} J(\theta)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mini-batch gradient descent&lt;/strong&gt; là biến thể được sử dụng rộng rãi nhất nhờ cân bằng tốt giữa tốc độ và độ ổn định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tốc độ học&lt;/strong&gt; \(\eta\) cần chọn cẩn thận: quá nhỏ sẽ hội tụ chậm, quá lớn sẽ gây mất ổn định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lịch trình tốc độ học&lt;/strong&gt; giúp cải thiện tốc độ hội tụ và chất lượng nghiệm cuối cùng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tiêu chí hội tụ&lt;/strong&gt; (đặc biệt là dừng sớm theo tập kiểm định) giúp xác định thời điểm kết thúc huấn luyện hợp lý.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các thách thức phổ biến&lt;/strong&gt; gồm cực tiểu cục bộ, điểm yên ngựa, vùng bằng phẳng và vấn đề gradient biến mất/bùng nổ.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ở bài tiếp theo, ta sẽ tìm hiểu &lt;strong&gt;lan truyền ngược&lt;/strong&gt; — thuật toán tính gradient hiệu quả cho mạng neuron.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa trực tiếp tiêu chí dừng khi bước cập nhật đủ nhỏ.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vMh0zPT0tLI&quot;&gt;Stochastic Gradient Descent, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích nhiễu trong SGD — thách thức thường gặp khi cài đặt thực tế.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, tiếng Anh. Trình bày vòng lặp huấn luyện thực tế với mô hình, hàm mất mát và bộ tối ưu trong PyTorch.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-02-01 Các Biến thể Gradient Descent và Learning Rate</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_02_01_GD_Variants_and_Learning_Rate/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_02_01_GD_Variants_and_Learning_Rate</id>
   <content type="html">&lt;p&gt;Nếu bạn có 10 triệu ảnh huấn luyện, việc tính gradient trên toàn bộ 10 triệu ảnh rồi mới nhích trọng số đi đúng &lt;strong&gt;1 bước&lt;/strong&gt; (Batch GD) sẽ chậm tới mức không thể chấp nhận; ngược lại, cập nhật ngay sau từng ảnh đơn lẻ (Pure SGD) lại quá nhiễu và lãng phí 99% sức mạnh song song của GPU. Câu trả lời thực chiến nằm ở &lt;strong&gt;Mini-Batch Gradient Descent&lt;/strong&gt; kết hợp &lt;strong&gt;Lịch điều chỉnh Tốc độ Học (&lt;em&gt;Learning Rate Schedule&lt;/em&gt;)&lt;/strong&gt;. Bài học này mổ xẻ cơ chế toán học của cả ba biến thể và nghệ thuật chọn, làm ấm (&lt;em&gt;warmup&lt;/em&gt;) và giảm dần (&lt;em&gt;decay&lt;/em&gt;) tốc độ học.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-về-biến-thể-gd-và-learning-rate&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột về Biến thể GD và Learning Rate&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Batch vs. Stochastic (SGD) vs. Mini-Batch GD&lt;/strong&gt;:
So sánh trên 3 trục: phương sai ước lượng gradient (tỷ lệ \(\propto 1/B\)), tần suất cập nhật mỗi epoch (\(\lceil N/B \rceil\) bước), và khả năng khai thác phép nhân ma trận song song (GEMM) trên GPU.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tác dụng Bất ngờ của Nhiễu Mini-Batch (Implicit Regularization)&lt;/strong&gt;:
Batch nhỏ (32–256) tạo nhiễu giúp mô hình nhảy ra khỏi các cực tiểu sắc nhọn (&lt;em&gt;sharp minima&lt;/em&gt;) và dừng ở cực tiểu phẳng rộng (&lt;em&gt;flat minima&lt;/em&gt;), nhờ đó khái quát hóa tốt hơn trên tập test!&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lịch trình Learning Rate (Step Decay, Cosine Annealing, Warmup)&lt;/strong&gt;:
Giai đoạn đầu cần \(\eta\) lớn để vượt nhanh qua vùng phẳng và khám phá toàn cục (sau vài bước &lt;em&gt;linear warmup&lt;/em&gt; tránh sốc khởi tạo); giai đoạn cuối hạ nhỏ \(\eta\) theo đường cong Cosine để hạ cánh êm xuống đáy.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Quy tắc Mở rộng Tuyến tính (Linear Scaling Rule)&lt;/strong&gt;:
Khi tăng kích thước batch lên \(k\) lần để huấn luyện phân tán trên nhiều GPU, phương sai gradient giảm \(k\) lần nên ta thường tăng learning rate tương ứng (cỡ \(k\) hoặc \(\sqrt{k}\) lần kèm warmup).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-tốc-độ-cập-nhật-và-cosine-decay-learning-rate&quot;&gt;Giải thích: Tính tay tốc độ cập nhật và Cosine Decay Learning Rate&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — So sánh số lần cập nhật trọng số trong 1 Epoch&lt;/strong&gt; với tập dữ liệu \(N = 50{,}000\) mẫu:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Batch GD&lt;/strong&gt; (\(B = 50{,}000\)): đúng &lt;strong&gt;1 lần cập nhật / epoch&lt;/strong&gt; (rất mượt nhưng siêu chậm).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mini-Batch GD&lt;/strong&gt; (\(B = 64\)): \(\lceil 50{,}000 / 64 \rceil = \mathbf{782}\) lần cập nhật / epoch (cân bằng tối ưu).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pure SGD&lt;/strong&gt; (\(B = 1\)): &lt;strong&gt;50{,}000 lần cập nhật / epoch&lt;/strong&gt; (rất nhiễu, không tận dụng được GPU).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Tính tay Learning Rate theo lịch Cosine Annealing&lt;/strong&gt; từ \(\eta_{\max} = 0.01\) xuống \(\eta_{\min} = 0\) qua \(T = 100\) epoch:
\(\eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min})\left(1 + \cos\frac{\pi t}{T}\right).\)&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tại \(t = 0\): \(\eta_0 = 0.005(1 + \cos 0) = \mathbf{0.0100}\).&lt;/li&gt;
  &lt;li&gt;Tại \(t = 50\) (nửa chặng đường): \(\eta_{50} = 0.005(1 + \cos \frac{\pi}{2}) = \mathbf{0.0050}\).&lt;/li&gt;
  &lt;li&gt;Tại \(t = 75\): \(\eta_{75} = 0.005(1 + \cos \frac{3\pi}{4}) \approx 0.005(1 - 0.7071) = \mathbf{0.00146}\).&lt;/li&gt;
  &lt;li&gt;Tại \(t = 100\): \(\eta_{100} = 0.005(1 + \cos\pi) = \mathbf{0.0000}\).
Đường cong Cosine giảm chậm lúc đầu (giữ sức khám phá), giảm nhanh ở giữa và giảm cực êm ở cuối để tinh chỉnh trọng số sát đáy nhất!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bài này giới thiệu gradient descent — thuật toán tối ưu nền tảng dùng để huấn luyện mạng neuron, cùng các biến thể chính và cách điều chỉnh tốc độ học (&lt;em&gt;learning rate&lt;/em&gt;).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bài-toán-tối-ưu-trong-học-sâu&quot;&gt;Bài toán Tối ưu trong Học sâu&lt;/h2&gt;

&lt;p&gt;Huấn luyện mạng neuron về bản chất là một &lt;strong&gt;bài toán tối ưu&lt;/strong&gt;: tìm bộ tham số \(\theta = \{\mathbf{W}^{[1]}, \mathbf{b}^{[1]}, \ldots, \mathbf{W}^{[L]}, \mathbf{b}^{[L]}\}\) sao cho hàm chi phí đạt cực tiểu:&lt;/p&gt;

\[\theta^* = \arg\min_{\theta} J(\theta)\]

&lt;p&gt;trong đó \(J(\theta)\) là giá trị mất mát trung bình trên toàn bộ tập dữ liệu huấn luyện.&lt;/p&gt;

&lt;h2 id=&quot;gradient-descent-ý-tưởng-cốt-lõi&quot;&gt;Gradient Descent: Ý tưởng Cốt lõi&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Gradient_descent.svg/600px-Gradient_descent.svg.png&quot; alt=&quot;Gradient Descent Visualization&quot; /&gt;
&lt;em&gt;Hình ảnh: Minh họa thuật toán Gradient Descent trên bề mặt hàm mất mát. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gradient descent&lt;/strong&gt; là thuật toán tối ưu lặp, cập nhật tham số theo hướng làm giảm hàm chi phí nhanh nhất tại điểm hiện tại.&lt;/p&gt;

&lt;h3 id=&quot;gradient&quot;&gt;Gradient&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gradient&lt;/strong&gt; \(\nabla_{\theta} J(\theta)\) là vector tập hợp các đạo hàm riêng của hàm chi phí theo từng tham số:&lt;/p&gt;

\[\nabla_{\theta} J = \begin{bmatrix} \frac{\partial J}{\partial \theta_1} \\ \frac{\partial J}{\partial \theta_2} \\ \vdots \\ \frac{\partial J}{\partial \theta_n} \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Tính chất quan trọng:&lt;/strong&gt; Vector gradient chỉ theo hướng &lt;strong&gt;tăng dốc nhất&lt;/strong&gt; của hàm số. Do đó, hướng ngược lại (\(-\nabla_{\theta} J\)) là hướng &lt;strong&gt;giảm dốc nhất&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;quy-tắc-cập-nhật&quot;&gt;Quy tắc Cập nhật&lt;/h3&gt;

&lt;p&gt;Công thức cập nhật tham số của gradient descent là:&lt;/p&gt;

\[\theta := \theta - \eta \nabla_{\theta} J(\theta)\]

&lt;p&gt;trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\eta\) là &lt;strong&gt;tốc độ học&lt;/strong&gt; (&lt;em&gt;learning rate&lt;/em&gt;), một siêu tham số dương&lt;/li&gt;
  &lt;li&gt;\(:=\) ký hiệu phép gán cập nhật&lt;/li&gt;
  &lt;li&gt;\(\nabla_{\theta} J(\theta)\) là gradient của hàm chi phí tại \(\theta\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Áp dụng cho từng tham số trong mạng neuron:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{W}^{[l]} := \mathbf{W}^{[l]} - \eta \frac{\partial J}{\partial \mathbf{W}^{[l]}}\]

\[\mathbf{b}^{[l]} := \mathbf{b}^{[l]} - \eta \frac{\partial J}{\partial \mathbf{b}^{[l]}}\]

&lt;h3 id=&quot;trực-giác-hình-học&quot;&gt;Trực giác Hình học&lt;/h3&gt;

&lt;p&gt;Có thể hình dung thuật toán giống như việc đứng trên sườn núi và tìm đường đi xuống thung lũng (cực tiểu):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Quan sát độ dốc xung quanh vị trí hiện tại (tính gradient).&lt;/li&gt;
  &lt;li&gt;Bước đi xuống theo hướng dốc nhất (hướng ngược chiều gradient).&lt;/li&gt;
  &lt;li&gt;Lặp lại quá trình cho tới khi chạm đáy (hội tụ).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Trong phép ví von này, tốc độ học \(\eta\) quyết định &lt;strong&gt;độ dài của mỗi bước chân&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;các-biến-thể-của-gradient-descent&quot;&gt;Các Biến thể của Gradient Descent&lt;/h2&gt;

&lt;h3 id=&quot;1-batch-gradient-descent&quot;&gt;1. Batch Gradient Descent&lt;/h3&gt;

&lt;p&gt;Sử dụng &lt;strong&gt;toàn bộ mẫu huấn luyện&lt;/strong&gt; để tính gradient trước mỗi lần cập nhật tham số.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thuật toán:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Lặp đến khi hội tụ:
    1. Tính gradient dùng tất cả m mẫu:
       ∇J(θ) = (1/m) Σᵢ₌₁ᵐ ∇L(ŷ⁽ⁱ⁾, y⁽ⁱ⁾)
    
    2. Cập nhật tham số:
       θ := θ - η ∇J(θ)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đảm bảo hội tụ tới cực tiểu toàn cục với hàm lồi&lt;/li&gt;
  &lt;li&gt;Hướng cập nhật chính xác và ổn định&lt;/li&gt;
  &lt;li&gt;Dễ phân tích lý thuyết về tốc độ hội tụ&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Rất chậm&lt;/strong&gt; trên tập dữ liệu lớn vì phải duyệt toàn bộ dữ liệu cho mỗi bước cập nhật&lt;/li&gt;
  &lt;li&gt;Đòi hỏi bộ nhớ lớn để xử lý toàn bộ tập dữ liệu&lt;/li&gt;
  &lt;li&gt;Có thể bị kẹt tại cực tiểu cục bộ hoặc điểm yên ngựa với hàm không lồi&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-stochastic-gradient-descent-sgd&quot;&gt;2. Stochastic Gradient Descent (SGD)&lt;/h3&gt;

&lt;p&gt;Tính gradient và cập nhật tham số dựa trên &lt;strong&gt;từng mẫu huấn luyện ngẫu nhiên&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thuật toán:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Lặp đến khi hội tụ:
    1. Xáo trộn ngẫu nhiên dữ liệu huấn luyện
    
    2. Với mỗi mẫu i:
        a. Tính gradient chỉ dùng mẫu i:
           ∇L(ŷ⁽ⁱ⁾, y⁽ⁱ⁾)
        
        b. Cập nhật tham số:
           θ := θ - η ∇L(ŷ⁽ⁱ⁾, y⁽ⁱ⁾)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tốc độ cập nhật &lt;strong&gt;nhanh hơn nhiều&lt;/strong&gt;, mô hình bắt đầu cải thiện ngay trong epoch đầu tiên&lt;/li&gt;
  &lt;li&gt;Nhiễu trong ước lượng gradient có thể giúp thoát khỏi cực tiểu cục bộ nông&lt;/li&gt;
  &lt;li&gt;Hỗ trợ học trực tuyến (&lt;em&gt;online learning&lt;/em&gt;) theo luồng dữ liệu&lt;/li&gt;
  &lt;li&gt;Tiết kiệm bộ nhớ&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ước lượng gradient nhiều nhiễu&lt;/strong&gt;, làm quỹ đạo hội tụ dao động mạnh&lt;/li&gt;
  &lt;li&gt;Thường dao động quanh cực tiểu thay vì dừng hẳn tại điểm cực tiểu&lt;/li&gt;
  &lt;li&gt;Khó tận dụng khả năng tính toán song song của phần cứng hiện đại&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-mini-batch-gradient-descent-phổ-biến-nhất&quot;&gt;3. Mini-Batch Gradient Descent (Phổ biến nhất)&lt;/h3&gt;

&lt;p&gt;Dùng một &lt;strong&gt;nhóm nhỏ mẫu dữ liệu&lt;/strong&gt; (&lt;em&gt;mini-batch&lt;/em&gt;, thường gồm 32, 64, 128 hoặc 256 mẫu) cho mỗi bước tính gradient.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thuật toán:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Lặp đến khi hội tụ:
    1. Xáo trộn ngẫu nhiên dữ liệu huấn luyện
    
    2. Chia dữ liệu thành các mini-batch kích thước B
    
    3. Với mỗi mini-batch:
        a. Tính gradient dùng batch:
           ∇J_batch(θ) = (1/B) Σᵢ∈batch ∇L(ŷ⁽ⁱ⁾, y⁽ⁱ⁾)
        
        b. Cập nhật tham số:
           θ := θ - η ∇J_batch(θ)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cân bằng ưu điểm của cả hai phương pháp:&lt;/strong&gt; Cập nhật nhanh đồng thời giữ độ ổn định tốt&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dễ song song hóa:&lt;/strong&gt; Tận dụng hiệu quả năng lực tính toán ma trận của GPU/TPU&lt;/li&gt;
  &lt;li&gt;Giảm phương sai của ước lượng gradient so với SGD đơn lẻ&lt;/li&gt;
  &lt;li&gt;Tiết kiệm bộ nhớ vì chỉ nạp từng batch một&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Thêm kích thước batch (&lt;em&gt;batch size&lt;/em&gt;) làm một siêu tham số cần chọn&lt;/li&gt;
  &lt;li&gt;Vẫn tồn tại một mức nhiễu nhất định (nhưng thấp hơn nhiều so với SGD)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;bảng-so-sánh&quot;&gt;Bảng So sánh&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Biến thể&lt;/th&gt;
      &lt;th&gt;Mẫu mỗi lần cập nhật&lt;/th&gt;
      &lt;th&gt;Tốc độ&lt;/th&gt;
      &lt;th&gt;Độ ổn định&lt;/th&gt;
      &lt;th&gt;Bộ nhớ&lt;/th&gt;
      &lt;th&gt;Khả năng song song hóa&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Batch GD&lt;/td&gt;
      &lt;td&gt;Tất cả (m)&lt;/td&gt;
      &lt;td&gt;Chậm&lt;/td&gt;
      &lt;td&gt;Cao&lt;/td&gt;
      &lt;td&gt;Cao&lt;/td&gt;
      &lt;td&gt;Khó&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;SGD&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;Nhanh&lt;/td&gt;
      &lt;td&gt;Thấp&lt;/td&gt;
      &lt;td&gt;Thấp&lt;/td&gt;
      &lt;td&gt;Khó&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mini-batch GD&lt;/td&gt;
      &lt;td&gt;Kích thước batch (B)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Nhanh&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Trung bình&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Thấp&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Dễ&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Khuyến nghị:&lt;/strong&gt; Sử dụng &lt;strong&gt;mini-batch gradient descent&lt;/strong&gt; với kích thước batch trong khoảng 32–256 làm điểm khởi đầu.&lt;/p&gt;

&lt;h2 id=&quot;tốc-độ-học-learning-rate&quot;&gt;Tốc độ Học (Learning Rate)&lt;/h2&gt;

&lt;p&gt;Tốc độ học \(\eta\) là một trong những siêu tham số có ảnh hưởng lớn nhất tới quá trình huấn luyện.&lt;/p&gt;

&lt;h3 id=&quot;ảnh-hưởng-của-tốc-độ-học&quot;&gt;Ảnh hưởng của Tốc độ Học&lt;/h3&gt;

&lt;h4 id=&quot;quá-nhỏ-eta-quá-thấp&quot;&gt;Quá nhỏ (\(\eta\) quá thấp)&lt;/h4&gt;
&lt;ul&gt;
  &lt;li&gt;Hội tụ rất chậm&lt;/li&gt;
  &lt;li&gt;Tốn nhiều thời gian và tài nguyên huấn luyện&lt;/li&gt;
  &lt;li&gt;Dễ bị chững lại ở các vùng bằng phẳng (&lt;em&gt;plateau&lt;/em&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;quá-lớn-eta-quá-cao&quot;&gt;Quá lớn (\(\eta\) quá cao)&lt;/h4&gt;
&lt;ul&gt;
  &lt;li&gt;Quá trình huấn luyện mất ổn định&lt;/li&gt;
  &lt;li&gt;Bước cập nhật vượt quá điểm cực tiểu&lt;/li&gt;
  &lt;li&gt;Giá trị mất mát có thể tăng vọt (phân kỳ)&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;phù-hợp&quot;&gt;Phù hợp&lt;/h4&gt;
&lt;ul&gt;
  &lt;li&gt;Hàm mất mát giảm đều và ổn định&lt;/li&gt;
  &lt;li&gt;Thời gian hội tụ hợp lý&lt;/li&gt;
  &lt;li&gt;Đạt được nghiệm có chất lượng tốt&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;giá-trị-khởi-đầu-điển-hình&quot;&gt;Giá trị Khởi đầu Điển hình&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Các mốc thường thử:&lt;/strong&gt; 0.001, 0.01, 0.1&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mạng sâu:&lt;/strong&gt; Thường bắt đầu trong khoảng 0.001 – 0.01&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mạng nông:&lt;/strong&gt; Có thể dùng mức cao hơn, khoảng 0.01 – 0.1&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;lịch-điều-chỉnh-tốc-độ-học-learning-rate-schedules&quot;&gt;Lịch Điều chỉnh Tốc độ Học (Learning Rate Schedules)&lt;/h3&gt;

&lt;p&gt;Thay vì giữ cố định \(\eta\) trong suốt quá trình huấn luyện, ta thường dùng &lt;strong&gt;lịch trình&lt;/strong&gt; thay đổi \(\eta\) theo bước hoặc epoch:&lt;/p&gt;

&lt;h4 id=&quot;1-giảm-theo-bậc-step-decay&quot;&gt;1. Giảm theo Bậc (Step Decay)&lt;/h4&gt;

\[\eta_t = \eta_0 \cdot \gamma^{\lfloor t / k \rfloor}\]

&lt;p&gt;trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\eta_0\) là tốc độ học ban đầu&lt;/li&gt;
  &lt;li&gt;\(\gamma \in (0, 1)\) là hệ số suy giảm (ví dụ: 0.5)&lt;/li&gt;
  &lt;li&gt;\(k\) là chu kỳ giảm (ví dụ: mỗi 10 epoch)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; Bắt đầu từ 0.1 và nhân với 0.5 sau mỗi 10 epoch.&lt;/p&gt;

&lt;h4 id=&quot;2-giảm-theo-hàm-mũ-exponential-decay&quot;&gt;2. Giảm theo Hàm mũ (Exponential Decay)&lt;/h4&gt;

\[\eta_t = \eta_0 \cdot e^{-\lambda t}\]

&lt;p&gt;trong đó \(\lambda\) là hằng số suy giảm.&lt;/p&gt;

&lt;h4 id=&quot;3-suy-giảm-1t&quot;&gt;3. Suy giảm \(1/t\)&lt;/h4&gt;

\[\eta_t = \frac{\eta_0}{1 + \lambda t}\]

&lt;h4 id=&quot;4-cosine-annealing&quot;&gt;4. Cosine Annealing&lt;/h4&gt;

\[\eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min})\left(1 + \cos\left(\frac{t}{T}\pi\right)\right)\]

&lt;p&gt;trong đó \(T\) là tổng số bước lặp.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Warm restarts:&lt;/strong&gt; Định kỳ đưa tốc độ học trở lại giá trị cao ban đầu để giúp mô hình thoát khỏi các vùng cực tiểu hẹp.&lt;/p&gt;

&lt;h4 id=&quot;5-khởi-động-tốc-độ-học-learning-rate-warm-up&quot;&gt;5. Khởi động Tốc độ Học (Learning Rate Warm-up)&lt;/h4&gt;

&lt;p&gt;Bắt đầu từ tốc độ học rất nhỏ rồi tăng dần tới giá trị mục tiêu trong giai đoạn đầu:&lt;/p&gt;

\[\eta_t = \eta_0 \cdot \min\left(1, \frac{t}{T_{\text{warmup}}}\right)\]

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt; Huấn luyện với kích thước batch lớn và các kiến trúc Transformer.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, tiếng Anh. Minh họa trực quan vai trò của tốc độ học như độ dài bước đi trên bề mặt hàm chi phí.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Tính chi tiết từng bước cập nhật bằng tay giúp phân biệt rõ batch, stochastic và mini-batch.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Gradient Descent là gì?&lt;/td&gt;
          &lt;td&gt;Tự học AI từ con số 0](https://www.youtube.com/watch?v=f3h5CU1808g) — Gà AI, tiếng Việt. Giải thích gradient descent qua ví dụ trực quan bằng tiếng Việt.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-01 Hàm Mất mát</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_01_Loss_Functions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_01_Loss_Functions</id>
   <content type="html">&lt;p&gt;Trong tối ưu hóa, mạng nơ-ron không hề hiểu khái niệm “ảnh đẹp”, “dự đoán thông minh” hay “câu trả lời hữu ích”—nó chỉ trung thành tuyệt đối với một mục tiêu duy nhất: &lt;strong&gt;làm cho hàm mất mát \(L(\theta)\) nhỏ nhất có thể&lt;/strong&gt;. Nếu bạn chọn sai hàm mất mát (chẳng hạn dùng MSE trên dữ liệu giá nhà đầy ngoại lai, hay dùng độ chính xác 0–1 không khả vi), mô hình sẽ tối ưu rất chăm chỉ theo đúng… hướng sai! Mục tổng quan này phác thảo bản đồ hai họ hàm mất mát lớn nhất—Hồi quy và Phân loại—trước khi đi vào chi tiết toán học từng công thức.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-nguyên-tắc-chọn-hàm-mất-mát-chuẩn-xác&quot;&gt;Kiến thức cần nhớ: Ba nguyên tắc chọn Hàm Mất mát chuẩn xác&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Khớp với Bản chất Đầu ra và Phân phối Xác suất (Góc nhìn MLE)&lt;/strong&gt;:
Nhiễu chuẩn trên số thực \(\to\) MSE; nhiễu đuôi dày nhiều ngoại lai \(\to\) MAE hoặc Huber; nhãn nhị phân \(\to\) Binary Cross-Entropy; nhãn đa lớp \(\to\) Categorical Cross-Entropy.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Khả vi và Hành vi Gradient tốt&lt;/strong&gt;:
Hàm mất mát phải cung cấp tín hiệu gradient đủ mạnh khi mô hình đoán sai nặng (Cross-Entropy phạt theo \(-\log p \to \infty\) khi \(p \to 0\)) và mượt dần khi tiến sát nghiệm đúng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân biệt Loss (tối ưu hóa) vs. Metric (đánh giá nghiệp vụ)&lt;/strong&gt;:
Ta huấn luyện bằng Cross-Entropy (trơn, khả vi) nhưng đánh giá bằng Accuracy, F1-score hay ROC-AUC (những đại lượng bậc thang không đạo hàm được trực tiếp).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-phản-ứng-của-mse-và-cross-entropy-khi-mô-hình-đoán-sai-tự-tin&quot;&gt;Giải thích: So sánh phản ứng của MSE và Cross-Entropy khi mô hình đoán sai tự tin&lt;/h3&gt;

&lt;p&gt;Giả sử nhãn thật là \(y = 1\) nhưng mô hình phân loại nhị phân đoán rất sai và rất tự tin: \(\hat{y} = 0.01\) (xác suất lớp 1 chỉ 1%):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nếu dùng MSE&lt;/strong&gt; \(L_{\text{MSE}} = \frac{1}{2}(\hat{y} - y)^2\) với \(\hat{y} = \sigma(z)\):
    &lt;ul&gt;
      &lt;li&gt;Mất mát: \(\frac{1}{2}(0.01 - 1)^2 = 0.490\) (khá nhỏ!).&lt;/li&gt;
      &lt;li&gt;Gradient theo logit \(z\): \((\hat{y} - y)\hat{y}(1 - \hat{y}) = (-0.99)(0.01)(0.99) \approx -0.0098\) (cực nhỏ do Sigmoid bão hòa \(\to\) mạng học chậm rì rì dù đang sai nghiêm trọng!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nếu dùng Binary Cross-Entropy&lt;/strong&gt; \(L_{\text{BCE}} = -[y\ln\hat{y} + (1-y)\ln(1-\hat{y})]\):
    &lt;ul&gt;
      &lt;li&gt;Mất mát: \(-\ln(0.01) \approx 4.605\) (phạt rất nặng!).&lt;/li&gt;
      &lt;li&gt;Gradient theo logit \(z\): \(\hat{y} - y = 0.01 - 1 = -0.99\) (khử sạch thừa số bão hòa \(\sigma&apos;(z)\), tạo lực sửa sai mạnh gấp &lt;strong&gt;100 lần&lt;/strong&gt; MSE!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Phần này trình bày các hàm mất mát (&lt;em&gt;loss functions&lt;/em&gt;) thường dùng khi huấn luyện mạng neuron:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mất mát cho hồi quy&lt;/strong&gt; — khái niệm hàm mất mát, MSE, MAE và Huber&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mất mát phân loại và cách lựa chọn&lt;/strong&gt; — mất mát cho phân loại nhị phân/đa lớp, ổn định số học và hướng dẫn chọn hàm phù hợp&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Lecture 3&lt;/td&gt;
          &lt;td&gt;Loss Functions and Optimization](https://www.youtube.com/watch?v=h7iBpEHGVNc) — Stanford University School of Engineering, tiếng Anh. Giới thiệu vai trò của hàm mất mát trước khi phân tách sang hồi quy và phân loại.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yIYKR4sgzI8&quot;&gt;StatQuest: Logistic Regression&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Trình bày hồi quy logistic gắn với hàm mất mát phân loại nhị phân ở bài thứ hai.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is cross-entropy?&lt;/td&gt;
          &lt;td&gt;Compression is Intelligence Part 2](https://www.youtube.com/watch?v=GlYgs6v2YfU) — 3Blue1Brown, tiếng Anh. Diễn giải trực quan về cross-entropy — hàm mất mát trung tâm cho phân loại đa lớp và mô hình ngôn ngữ.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-01-02 Hàm Mất mát Phân loại và Lựa chọn</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_01_02_Classification_Losses/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_01_02_Classification_Losses</id>
   <content type="html">&lt;p&gt;Nếu mô hình phân loại ảnh của bạn đoán xác suất bức ảnh là con chó bằng \(0.99\) khi nhãn thật là con mèo, sai lầm đó không chỉ “sai 1 điểm” mà là một sự tự tin mù quáng cần bị phạt cực nặng. Đó là lý do các bài toán phân loại trong Học sâu hầu như luôn xoay quanh &lt;strong&gt;Cross-Entropy (Log Loss)&lt;/strong&gt;—hàm mất mát có nguồn gốc từ Lý thuyết Thông tin và MLE—cùng những biến thể chuyên trị dữ liệu mất cân bằng như &lt;strong&gt;Focal Loss&lt;/strong&gt;, &lt;strong&gt;Label Smoothing&lt;/strong&gt; và &lt;strong&gt;Hinge Loss&lt;/strong&gt;. Bài học này giải phẫu trọn vẹn bộ hàm mất mát phân loại và quy tắc lựa chọn trong từng tình huống.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-hàm-mất-mát-phân-loại&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Hàm Mất mát Phân loại&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Binary Cross-Entropy (BCE) cho Phân loại Nhị phân &amp;amp; Đa nhãn&lt;/strong&gt;:
\(L = -[y\ln p + (1-y)\ln(1-p)]\) với \(p = \sigma(z)\). Trong PyTorch, luôn dùng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BCEWithLogitsLoss&lt;/code&gt; (nhận trực tiếp logit \(z\)) thay vì tự chạy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Sigmoid&lt;/code&gt; rồi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BCELoss&lt;/code&gt; để đảm bảo ổn định số học.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Categorical Cross-Entropy cho Phân loại Đa lớp (Softmax + NLL)&lt;/strong&gt;:
Với nhãn one-hot tại lớp đúng \(c\), mất mát rút gọn cực đẹp thành \(L = -\ln p_c = -z_c + \ln\!\left(\sum_j e^{z_j}\right)\), và gradient theo vector logit đơn giản đáng kinh ngạc: \(\nabla_{\mathbf{z}} L = \mathbf{p} - \mathbf{y}\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hinge Loss (Biên lề SVM) và Margin-based Losses&lt;/strong&gt;:
\(L = \max(0,\; 1 - y\cdot z)\) với \(y \in \{-1, +1\}\): chỉ phạt các mẫu bị đoán sai hoặc nằm quá sát biên quyết định (\(y z &amp;lt; 1\)), bỏ qua hoàn toàn các mẫu đã phân tách đủ xa.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kỹ thuật nâng cao: Label Smoothing &amp;amp; Focal Loss&lt;/strong&gt;:
Label Smoothing làm mềm nhãn từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0, 1, 0]&lt;/code&gt; thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0.05, 0.90, 0.05]&lt;/code&gt; chống quá tự tin (&lt;em&gt;overconfidence&lt;/em&gt;); còn Focal Loss nhân thêm \((1 - p_t)^\gamma\) để hạ trọng số mẫu dễ và tập trung sức học vào mẫu khó/lớp hiếm.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-cross-entropy-gradient-mathbfp---mathbfy-và-focal-loss&quot;&gt;Giải thích: Tính tay Cross-Entropy, Gradient \(\mathbf{p} - \mathbf{y}\) và Focal Loss&lt;/h3&gt;

&lt;p&gt;Giả sử bài toán 3 lớp có nhãn thật là lớp 0 (\(\mathbf{y} = [1, 0, 0]\)), và mạng xuất ra vector logit \(\mathbf{z} = [1.0,\; 2.0,\; 0.0]\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính xác suất Softmax&lt;/strong&gt;:
\(e^1 \approx 2.718,\; e^2 \approx 7.389,\; e^0 = 1.000 \implies \text{Tổng} = 11.107.\)
\(\mathbf{p} \approx \left[\frac{2.718}{11.107},\; \frac{7.389}{11.107},\; \frac{1.000}{11.107}\right] = [0.2447,\; 0.6652,\; 0.0900].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính Categorical Cross-Entropy&lt;/strong&gt;:
\(L_{\text{CE}} = -\ln(p_0) = -\ln(0.2447) \approx 1.4077.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính Gradient theo từng logit (\(\nabla_{\mathbf{z}} L = \mathbf{p} - \mathbf{y}\))&lt;/strong&gt;:
\(\frac{\partial L}{\partial \mathbf{z}} = [0.2447 - 1,\; 0.6652 - 0,\; 0.0900 - 0] = [-0.7553,\; +0.6652,\; +0.0900].\)
Khi cập nhật ngược dấu gradient (\(\mathbf{z} \leftarrow \mathbf{z} - \eta \nabla_{\mathbf{z}} L\)), logit lớp đúng \(z_0\) được &lt;strong&gt;kéo tăng lên&lt;/strong&gt; (vì gradient âm), còn logit hai lớp sai \(z_1, z_2\) bị &lt;strong&gt;đẩy xuống&lt;/strong&gt; (vì gradient dương), trong đó lớp sai nổi bật nhất \(z_1\) bị đẩy mạnh nhất!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So với Focal Loss (\(\gamma = 2\))&lt;/strong&gt;:
Nhân thêm \((1 - p_0)^2 = (1 - 0.2447)^2 \approx 0.5705\): nếu một mẫu dễ có \(p_0 = 0.95\), thừa số \((1 - 0.95)^2 = 0.0025\) làm giảm mức phạt xuống &lt;strong&gt;400 lần&lt;/strong&gt; để mô hình dồn lực vào các mẫu khó!&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;hàm-mất-mát-cho-phân-loại-nhị-phân&quot;&gt;Hàm Mất mát cho Phân loại Nhị phân&lt;/h2&gt;

&lt;h3 id=&quot;1-entropy-chéo-nhị-phân-log-loss&quot;&gt;1. Entropy Chéo Nhị phân (Log Loss)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Công thức:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{BCE}}(\hat{y}, y) = -[y \log(\hat{y}) + (1-y) \log(1-\hat{y})]\]

&lt;p&gt;trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(y \in \{0, 1\}\) là nhãn thực tế&lt;/li&gt;
  &lt;li&gt;\(\hat{y} \in (0, 1)\) là xác suất dự đoán&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hàm chi phí:&lt;/strong&gt;&lt;/p&gt;

\[J_{\text{BCE}} = -\frac{1}{m} \sum_{i=1}^{m} [y^{(i)} \log(\hat{y}^{(i)}) + (1-y^{(i)}) \log(1-\hat{y}^{(i)})]\]

&lt;p&gt;&lt;strong&gt;Trực giác:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Khi \(y = 1\): Mất mát bằng \(-\log(\hat{y})\), đạt cực tiểu khi \(\hat{y} \to 1\)&lt;/li&gt;
  &lt;li&gt;Khi \(y = 0\): Mất mát bằng \(-\log(1-\hat{y})\), đạt cực tiểu khi \(\hat{y} \to 0\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Xuất phát từ nguyên lý ước lượng hợp lý cực đại (&lt;em&gt;maximum likelihood estimation&lt;/em&gt;)&lt;/li&gt;
  &lt;li&gt;Trơn và khả vi&lt;/li&gt;
  &lt;li&gt;Tương thích tốt với tối ưu dựa trên gradient&lt;/li&gt;
  &lt;li&gt;Phạt rất nặng các dự đoán sai nhưng có độ tự tin cao&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm (với đầu ra sigmoid):&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Khi lớp đầu ra sử dụng sigmoid \(\hat{y} = \sigma(z)\):&lt;/p&gt;

\[\frac{\partial \mathcal{L}_{\text{BCE}}}{\partial z} = \hat{y} - y\]

&lt;p&gt;Dạng đạo hàm gọn gàng này giúp việc tính gradient và huấn luyện diễn ra thuận lợi.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân loại nhị phân:&lt;/strong&gt; Ví dụ phân biệt ảnh chó và mèo&lt;/li&gt;
  &lt;li&gt;Kết hợp với lớp đầu ra dùng hàm kích hoạt sigmoid&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Có diễn giải xác suất chặt chẽ&lt;/li&gt;
  &lt;li&gt;Tạo gradient đủ mạnh khi mô hình dự đoán sai&lt;/li&gt;
  &lt;li&gt;Kết hợp tự nhiên với đầu ra sigmoid&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mất mát có thể tăng rất lớn nếu mô hình dự đoán sai với xác suất gần 0 hoặc 1&lt;/li&gt;
  &lt;li&gt;Cần đầu ra dạng xác suất (hoặc dùng phiên bản nhận trực tiếp logits để ổn định số)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-mất-mát-hinge-mất-mát-svm&quot;&gt;2. Mất mát Hinge (Mất mát SVM)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Công thức:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{Hinge}}(\hat{y}, y) = \max(0, 1 - y \cdot \hat{y})\]

&lt;p&gt;trong đó \(y \in \{-1, +1\}\) và \(\hat{y}\) là điểm số thô (không phải xác suất).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Dùng trong máy vector hỗ trợ (&lt;em&gt;Support Vector Machines&lt;/em&gt;)&lt;/li&gt;
  &lt;li&gt;Khuyến khích mở rộng khoảng lề phân tách (&lt;em&gt;margin&lt;/em&gt;)&lt;/li&gt;
  &lt;li&gt;Không khả vi tại \(y \cdot \hat{y} = 1\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Bài toán phân loại nhị phân theo mục tiêu kiểu SVM&lt;/li&gt;
  &lt;li&gt;Khi cần tối ưu hóa biên lề cực đại&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;hàm-mất-mát-cho-phân-loại-đa-lớp&quot;&gt;Hàm Mất mát cho Phân loại Đa lớp&lt;/h2&gt;

&lt;h3 id=&quot;1-entropy-chéo-đa-lớp-categorical-cross-entropy&quot;&gt;1. Entropy Chéo Đa lớp (Categorical Cross-Entropy)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Công thức:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{CCE}}(\hat{\mathbf{y}}, \mathbf{y}) = -\sum_{c=1}^{C} y_c \log(\hat{y}_c)\]

&lt;p&gt;trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{y}\) là nhãn thực tế ở dạng &lt;strong&gt;mã hóa one-hot&lt;/strong&gt;: \(y_c \in \{0, 1\}\), \(\sum_c y_c = 1\)&lt;/li&gt;
  &lt;li&gt;\(\hat{\mathbf{y}}\) là phân phối xác suất dự đoán: \(\hat{y}_c \in (0, 1)\), \(\sum_c \hat{y}_c = 1\)&lt;/li&gt;
  &lt;li&gt;\(C\) là tổng số lớp&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hàm chi phí:&lt;/strong&gt;&lt;/p&gt;

\[J_{\text{CCE}} = -\frac{1}{m} \sum_{i=1}^{m} \sum_{c=1}^{C} y_c^{(i)} \log(\hat{y}_c^{(i)})\]

&lt;p&gt;&lt;strong&gt;Dạng rút gọn&lt;/strong&gt; (vì chỉ có đúng một thành phần \(y_{c^*} = 1\)):&lt;/p&gt;

\[\mathcal{L}_{\text{CCE}} = -\log(\hat{y}_{c^*})\]

&lt;p&gt;trong đó \(c^*\) là chỉ số của lớp đúng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm (với đầu ra softmax):&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Khi lớp đầu ra sử dụng softmax \(\hat{\mathbf{y}} = \text{softmax}(\mathbf{z})\):&lt;/p&gt;

\[\frac{\partial \mathcal{L}_{\text{CCE}}}{\partial z_j} = \hat{y}_j - y_j\]

&lt;p&gt;Tương tự trường hợp nhị phân, biểu thức đạo hàm có dạng rất đơn giản.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phân loại đa lớp:&lt;/strong&gt; Ví dụ nhận dạng chữ số (MNIST), phân loại ảnh (ImageNet)&lt;/li&gt;
  &lt;li&gt;Kết hợp với lớp đầu ra dùng softmax&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nền tảng xác suất rõ ràng&lt;/li&gt;
  &lt;li&gt;Lựa chọn tiêu chuẩn cho bài toán đa lớp&lt;/li&gt;
  &lt;li&gt;Biểu thức gradient gọn khi ghép với softmax&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đòi hỏi nhãn ở dạng mã hóa one-hot&lt;/li&gt;
  &lt;li&gt;Dễ gặp vấn đề ổn định số nếu tính rời rạc (nên dùng kết hợp log-softmax)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-entropy-chéo-đa-lớp-thưa-sparse-categorical-cross-entropy&quot;&gt;2. Entropy Chéo Đa lớp Thưa (Sparse Categorical Cross-Entropy)&lt;/h3&gt;

&lt;p&gt;Về bản chất toán học, hàm này giống hệt Categorical Cross-Entropy nhưng nhận trực tiếp nhãn số nguyên thay vì vector one-hot.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Định dạng đầu vào:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(y \in \{0, 1, \ldots, C-1\}\) (chỉ số nguyên của lớp đúng)&lt;/li&gt;
  &lt;li&gt;\(\hat{\mathbf{y}} \in \mathbb{R}^C\) (phân phối xác suất dự đoán)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Công thức:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{SCCE}}(\hat{\mathbf{y}}, y) = -\log(\hat{y}_y)\]

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Phân loại đa lớp khi nhãn lưu dưới dạng số nguyên&lt;/li&gt;
  &lt;li&gt;Tiết kiệm bộ nhớ vì không cần tạo ma trận one-hot (đặc biệt hữu ích khi \(C\) lớn)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-phân-kỳ-kullback-leibler-kl-divergence&quot;&gt;3. Phân kỳ Kullback-Leibler (KL Divergence)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Công thức:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{KL}}(\mathbf{p}, \mathbf{q}) = \sum_{c=1}^{C} p_c \log\left(\frac{p_c}{q_c}\right) = \sum_{c=1}^{C} [p_c \log(p_c) - p_c \log(q_c)]\]

&lt;p&gt;trong đó \(\mathbf{p}\) là phân phối mục tiêu và \(\mathbf{q}\) là phân phối dự đoán.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đo độ sai khác giữa hai phân phối xác suất&lt;/li&gt;
  &lt;li&gt;Luôn không âm (bằng 0 khi và chỉ khi \(\mathbf{p} = \mathbf{q}\))&lt;/li&gt;
  &lt;li&gt;Không đối xứng: \(\text{KL}(p \| q) \neq \text{KL}(q \| p)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Quan hệ với Entropy Chéo:&lt;/strong&gt;&lt;/p&gt;

\[\text{KL}(p \| q) = H(p, q) - H(p)\]

&lt;p&gt;trong đó \(H(p, q)\) là entropy chéo và \(H(p)\) là entropy của phân phối \(p\).&lt;/p&gt;

&lt;p&gt;Do \(H(p)\) là hằng số đối với tham số mô hình, việc cực tiểu hóa phân kỳ KL tương đương với cực tiểu hóa entropy chéo.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Autoencoder biến phân (VAE)&lt;/li&gt;
  &lt;li&gt;Các bài toán khớp phân phối xác suất&lt;/li&gt;
  &lt;li&gt;Chưng cất tri thức (&lt;em&gt;knowledge distillation&lt;/em&gt;)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;các-lưu-ý-thực-tế&quot;&gt;Các Lưu ý Thực tế&lt;/h2&gt;

&lt;h3 id=&quot;ổn-định-số-học&quot;&gt;Ổn định Số học&lt;/h3&gt;

&lt;h4 id=&quot;vấn-đề-logarit-của-số-rất-nhỏ&quot;&gt;Vấn đề: Logarit của Số Rất Nhỏ&lt;/h4&gt;

&lt;p&gt;Tính \(\log(\hat{y})\) khi \(\hat{y}\) tiến sát 0 có thể sinh ra giá trị \(-\infty\) hoặc &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;.&lt;/p&gt;

&lt;h4 id=&quot;cách-xử-lý-cơ-bản-giới-hạn-miền-giá-trị-clipping&quot;&gt;Cách xử lý cơ bản: Giới hạn miền giá trị (&lt;em&gt;clipping&lt;/em&gt;)&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-7&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_pred_clipped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred_clipped&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;cách-xử-lý-tốt-hơn-kỹ-thuật-logsumexp&quot;&gt;Cách xử lý tốt hơn: Kỹ thuật LogSumExp&lt;/h4&gt;

&lt;p&gt;Khi kết hợp softmax và entropy chéo, nên tính trực tiếp từ logits thay vì qua bước xác suất trung gian:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax_cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Softmax + entropy chéo ổn định số&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Mẹo log-sum-exp
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;logits_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;log_sum_exp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logits_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logits_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;log_softmax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_sum_exp&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Entropy chéo
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;ví-dụ-triển-khai&quot;&gt;Ví dụ Triển khai&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LossFunctions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean Squared Error&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean Absolute Error&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;binary_crossentropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Binary Cross-Entropy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;categorical_crossentropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Categorical Cross-Entropy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sparse_categorical_crossentropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sparse Categorical Cross-Entropy
        
        y_true: nhãn nguyên (m,)
        y_pred: xác suất (m, C)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;log_likelihood&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;huber&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huber Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;is_small_error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;squared_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;linear_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_small_error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;squared_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linear_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ sử dụng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Binary Cross-Entropy:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LossFunctions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binary_crossentropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ đa lớp
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true_categorical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_pred_categorical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Categorical Cross-Entropy:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LossFunctions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;categorical_crossentropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true_categorical&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_categorical&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;chọn-hàm-mất-mát-phù-hợp&quot;&gt;Chọn Hàm Mất mát Phù hợp&lt;/h2&gt;

&lt;h3 id=&quot;cây-quyết-định&quot;&gt;Cây Quyết định&lt;/h3&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Loại tác vụ?
├─ Hồi quy
│  ├─ Có ngoại lai? → MAE hoặc Huber Loss
│  └─ Không ngoại lai? → MSE
│
├─ Phân loại nhị phân
│  ├─ Đầu ra xác suất? → Binary Cross-Entropy
│  └─ Dựa trên lề? → Hinge Loss
│
└─ Phân loại đa lớp
   ├─ Nhãn one-hot? → Categorical Cross-Entropy
   └─ Nhãn nguyên? → Sparse Categorical Cross-Entropy
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;bảng-tra-cứu-nhanh&quot;&gt;Bảng Tra cứu Nhanh&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Tác vụ&lt;/th&gt;
      &lt;th&gt;Hàm mất mát&lt;/th&gt;
      &lt;th&gt;Kích hoạt đầu ra&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Hồi quy&lt;/td&gt;
      &lt;td&gt;MSE, MAE, Huber&lt;/td&gt;
      &lt;td&gt;Tuyến tính&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Phân loại nhị phân&lt;/td&gt;
      &lt;td&gt;Binary Cross-Entropy&lt;/td&gt;
      &lt;td&gt;Sigmoid&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Phân loại đa lớp&lt;/td&gt;
      &lt;td&gt;Categorical Cross-Entropy&lt;/td&gt;
      &lt;td&gt;Softmax&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Phân loại đa nhãn&lt;/td&gt;
      &lt;td&gt;Binary Cross-Entropy (mỗi nhãn)&lt;/td&gt;
      &lt;td&gt;Sigmoid (mỗi nhãn)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hàm mất mát&lt;/strong&gt; định lượng mức độ sai lệch giữa dự đoán của mô hình và giá trị thực tế.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhóm bài toán hồi quy:&lt;/strong&gt; MSE (nhạy ngoại lai), MAE (bền vững trước ngoại lai), Huber (cân bằng giữa hai đặc tính).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhóm bài toán phân loại:&lt;/strong&gt; Entropy chéo là lựa chọn tiêu chuẩn nhờ nền tảng xác suất và gradient ổn định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân loại nhị phân:&lt;/strong&gt; Ghép Binary Cross-Entropy với sigmoid.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân loại đa lớp:&lt;/strong&gt; Ghép Categorical Cross-Entropy với softmax.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ổn định số học&lt;/strong&gt; là yếu tố quan trọng khi cài đặt hàm mất mát, đặc biệt với các phép tính hàm mũ và logarit.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lựa chọn hàm mất mát&lt;/strong&gt; cần phù hợp với loại bài toán và phân phối dữ liệu.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ở bài tiếp theo, ta sẽ tìm hiểu gradient descent — thuật toán sử dụng hàm mất mát để cập nhật tham số mạng.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=yIYKR4sgzI8&quot;&gt;StatQuest: Logistic Regression&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giới thiệu hàm mất mát logistic cho bài toán phân loại nhị phân.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is cross-entropy?&lt;/td&gt;
          &lt;td&gt;Compression is Intelligence Part 2](https://www.youtube.com/watch?v=GlYgs6v2YfU) — 3Blue1Brown, tiếng Anh. Giải thích bản chất của cross-entropy từ góc độ độ dài mã hóa thay vì chỉ đưa công thức.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=LLux1SW--oM&quot;&gt;Softmax Regression (C2W3L08)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Trình bày hồi quy softmax cho bài toán phân loại nhiều lớp.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-01-01 Hàm Mất mát cho Hồi quy</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_01_01_Regression_Losses/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_01_01_Regression_Losses</id>
   <content type="html">&lt;p&gt;Tưởng tượng bạn xây mô hình dự báo giá căn hộ: 99 căn hộ bình thường có giá quanh 3 tỷ đồng, nhưng lọt vào tập dữ liệu đúng 1 căn biệt thự nhập nhầm giá 300 tỷ đồng. Nếu huấn luyện bằng &lt;strong&gt;MSE&lt;/strong&gt;, chỉ duy nhất một điểm ngoại lai đó có thể kéo lệch toàn bộ mô hình vì sai số bị bình phương lên tới hàng chục nghìn lần! Ngược lại, &lt;strong&gt;MAE&lt;/strong&gt; miễn nhiễm tốt với ngoại lai nhưng lại có độ dốc không đổi khiến tối ưu dễ rung lắc quanh đáy. Bài học này phân tích bộ ba &lt;strong&gt;MSE, MAE và Huber Loss&lt;/strong&gt; để bạn biết chọn thước đo hồi quy tối ưu cho từng đặc thù nhiễu dữ liệu.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-góc-nhìn-cốt-lõi-về-hàm-mất-mát-hồi-quy&quot;&gt;Kiến thức cần nhớ: Bốn góc nhìn cốt lõi về Hàm Mất mát Hồi quy&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;MSE (Mean Squared Error — \(L_2\) Loss)&lt;/strong&gt;:
Phạt theo bình phương sai số \((y - \hat{y})^2\), có đạo hàm tỷ lệ thuận với độ lớn sai số \(2(\hat{y} - y)\) nên mượt quanh \(0\) và tương ứng MLE của nhiễu Gaussian; nghiệm tối ưu hằng số là &lt;strong&gt;trung bình (mean)&lt;/strong&gt;.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;MAE (Mean Absolute Error — \(L_1\) Loss)&lt;/strong&gt;:
Phạt tuyến tính theo \(\lvert y - \hat{y} \rvert\), bền vững trước ngoại lai (&lt;em&gt;outliers&lt;/em&gt;) với nghiệm tối ưu hằng số là &lt;strong&gt;trung vị (median)&lt;/strong&gt;, nhưng không khả vi tại \(0\) và gradient luôn có độ lớn \(\pm 1\) kể cả khi rất gần nghiệm.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Huber Loss (Smooth \(L_1\))&lt;/strong&gt;:
Kết hợp ưu điểm của cả hai: hành xử như parabol (MSE) khi sai số nhỏ \(\lvert e \rvert \le \delta\) để hội tụ êm quanh đáy, và chuyển sang đường thẳng (MAE) khi \(\lvert e \rvert &amp;gt; \delta\) để chặn tác động của ngoại lai—tiêu chuẩn vàng trong hồi quy khung bao Object Detection và DQN.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Log-Cosh và Biến đổi Miền (RMSE, RMSLE)&lt;/strong&gt;:
RMSE đưa đơn vị về lại thang đo gốc của \(y\), còn RMSLE phạt sai số theo tỷ lệ phần trăm thay vì hiệu tuyệt đối—rất hữu ích khi giá trị mục tiêu trải rộng qua nhiều bậc độ lớn.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-mse-mae-và-huber-loss-khi-có-1-điểm-ngoại-lai&quot;&gt;Giải thích: Tính tay MSE, MAE và Huber Loss khi có 1 điểm ngoại lai&lt;/h3&gt;

&lt;p&gt;Xét 4 mẫu dữ liệu với sai số \(e_i = \hat{y}_i - y_i\) lần lượt là: \(e_1 = 0.5,\; e_2 = -0.5,\; e_3 = 0.2,\; e_4 = 10.0\) (mẫu 4 là ngoại lai). Ta tính mức phạt và độ lớn đạo hàm trên mẫu ngoại lai \(e_4 = 10\) với Huber ngưỡng \(\delta = 1.0\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hàm mất mát&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Công thức từng mẫu&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Giá trị trên 3 mẫu sạch (\(e_1,e_2,e_3\))&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Giá trị trên ngoại lai (\(e_4=10\))&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Độ lớn gradient \(\lvert \partial L/\partial e_4 \rvert\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;MSE&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\frac{1}{2}e^2\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.125,\; 0.125,\; 0.020\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(50.00\)&lt;/strong&gt; (chiếm 99.5% tổng loss!)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(10.0\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;MAE&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\lvert e \rvert\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.500,\; 0.500,\; 0.200\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(10.00\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(1.0\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Huber (\(\delta=1\))&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\frac{1}{2}e^2\) nếu \(\lvert e \rvert \le 1\); \(\lvert e \rvert - 0.5\) nếu \(&amp;gt;1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.125,\; 0.125,\; 0.020\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(9.50\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(1.0\)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Nhìn vào cột cuối: tại 3 mẫu sạch, Huber giữ gradient mượt bằng \(e\) (như MSE), nhưng tại mẫu ngoại lai \(e_4 = 10\), Huber cắt trần độ lớn gradient đúng bằng \(\delta = 1.0\)—ngăn không cho một điểm dữ liệu lỗi kéo hỏng cả mini-batch!&lt;/p&gt;

&lt;p&gt;Bài này giới thiệu các hàm mất mát (&lt;em&gt;loss functions&lt;/em&gt;, còn gọi là hàm chi phí hoặc hàm mục tiêu) dùng để định lượng mức độ sai lệch của mạng neuron, tập trung vào nhóm bài toán hồi quy.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;hàm-mất-mát-là-gì&quot;&gt;Hàm Mất mát là gì?&lt;/h2&gt;

&lt;p&gt;Một &lt;strong&gt;hàm mất mát&lt;/strong&gt; \(\mathcal{L}\) đo lường sự chênh lệch giữa đầu ra dự đoán \(\hat{y}\) và giá trị thực tế \(y\). Mục tiêu của quá trình huấn luyện là tìm bộ tham số \(\theta\) (gồm trọng số và độ lệch) sao cho giá trị mất mát này đạt cực tiểu.&lt;/p&gt;

&lt;h3 id=&quot;mất-mát-trên-một-mẫu&quot;&gt;Mất mát trên Một Mẫu&lt;/h3&gt;

&lt;p&gt;Với một mẫu huấn luyện đơn lẻ:&lt;/p&gt;

\[\mathcal{L}(\hat{y}, y)\]

&lt;h3 id=&quot;hàm-chi-phí-tổng-mất-mát&quot;&gt;Hàm Chi phí (Tổng Mất mát)&lt;/h3&gt;

&lt;p&gt;Trên tập dữ liệu gồm \(m\) mẫu, &lt;strong&gt;hàm chi phí&lt;/strong&gt; \(J\) thường được định nghĩa là giá trị mất mát trung bình:&lt;/p&gt;

\[J(\theta) = \frac{1}{m} \sum_{i=1}^{m} \mathcal{L}(\hat{y}^{(i)}, y^{(i)})\]

&lt;p&gt;Trong thực tế, hàm chi phí có thể cộng thêm các hạng tử chính quy hóa (&lt;em&gt;regularization&lt;/em&gt;) sẽ được trình bày ở các chương sau.&lt;/p&gt;

&lt;h2 id=&quot;hàm-mất-mát-cho-hồi-quy&quot;&gt;Hàm Mất mát cho Hồi quy&lt;/h2&gt;

&lt;h3 id=&quot;1-sai-số-bình-phương-trung-bình-mse&quot;&gt;1. Sai số Bình phương Trung bình (MSE)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Công thức:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{MSE}}(\hat{y}, y) = \frac{1}{2}(y - \hat{y})^2\]

&lt;p&gt;&lt;strong&gt;Hàm chi phí:&lt;/strong&gt;&lt;/p&gt;

\[J_{\text{MSE}} = \frac{1}{m} \sum_{i=1}^{m} \frac{1}{2}(y^{(i)} - \hat{y}^{(i)})^2 = \frac{1}{2m} \sum_{i=1}^{m} (y^{(i)} - \hat{y}^{(i)})^2\]

&lt;p&gt;&lt;strong&gt;Lưu ý:&lt;/strong&gt; Hệ số \(\frac{1}{2}\) được thêm vào để rút gọn hệ số 2 khi lấy đạo hàm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Luôn không âm&lt;/li&gt;
  &lt;li&gt;Phạt nặng các sai số lớn theo hàm bậc hai&lt;/li&gt;
  &lt;li&gt;Nhạy với các điểm ngoại lai (&lt;em&gt;outliers&lt;/em&gt;)&lt;/li&gt;
  &lt;li&gt;Trơn và khả vi tại mọi điểm&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm:&lt;/strong&gt;&lt;/p&gt;

\[\frac{\partial \mathcal{L}_{\text{MSE}}}{\partial \hat{y}} = \hat{y} - y\]

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bài toán hồi quy:&lt;/strong&gt; Dự đoán các đại lượng liên tục&lt;/li&gt;
  &lt;li&gt;Khi nhiễu sai số có dạng gần phân phối chuẩn&lt;/li&gt;
  &lt;li&gt;Khi các sai số có mức độ quan trọng tương đương nhau&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Công thức đơn giản và trực quan&lt;/li&gt;
  &lt;li&gt;Đạo hàm trơn, dễ tối ưu&lt;/li&gt;
  &lt;li&gt;Có nền tảng lý thuyết rõ ràng&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Rất nhạy với điểm ngoại lai do sai số lớn bị bình phương&lt;/li&gt;
  &lt;li&gt;Ngầm giả định sai số tuân theo phân phối chuẩn&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-sai-số-tuyệt-đối-trung-bình-mae&quot;&gt;2. Sai số Tuyệt đối Trung bình (MAE)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Công thức:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{MAE}}(\hat{y}, y) = |y - \hat{y}|\]

&lt;p&gt;&lt;strong&gt;Hàm chi phí:&lt;/strong&gt;&lt;/p&gt;

\[J_{\text{MAE}} = \frac{1}{m} \sum_{i=1}^{m} |y^{(i)} - \hat{y}^{(i)}|\]

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Phạt sai số theo tỷ lệ tuyến tính&lt;/li&gt;
  &lt;li&gt;Ít nhạy với điểm ngoại lai hơn MSE&lt;/li&gt;
  &lt;li&gt;Không khả vi tại điểm \(\hat{y} = y\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm:&lt;/strong&gt;&lt;/p&gt;

\[\frac{\partial \mathcal{L}_{\text{MAE}}}{\partial \hat{y}} = \begin{cases} 1 &amp;amp; \text{if } \hat{y} &amp;gt; y \\ -1 &amp;amp; \text{if } \hat{y} &amp;lt; y \\ \text{undefined} &amp;amp; \text{if } \hat{y} = y \end{cases}\]

&lt;p&gt;(Trong thực tế, ta sử dụng dưới đạo hàm — &lt;em&gt;subgradient&lt;/em&gt; — hoặc các hàm xấp xỉ trơn.)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Bài toán hồi quy có nhiều điểm ngoại lai&lt;/li&gt;
  &lt;li&gt;Khi muốn phạt sai số tỷ lệ thuận với độ lớn thay vì bình phương&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Bền vững trước các điểm ngoại lai&lt;/li&gt;
  &lt;li&gt;Dễ diễn giải trực tiếp theo đơn vị của biến mục tiêu&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Không khả vi tại \(\hat{y} = y\)&lt;/li&gt;
  &lt;li&gt;Có thể hội tụ chậm hơn MSE&lt;/li&gt;
  &lt;li&gt;Độ lớn gradient không đổi (luôn bằng 1) có thể khiến tham số dao động quanh cực tiểu&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-mất-mát-huber&quot;&gt;3. Mất mát Huber&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Công thức:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{Huber}}(\hat{y}, y) = \begin{cases} \frac{1}{2}(y - \hat{y})^2 &amp;amp; \text{if } |y - \hat{y}| \leq \delta \\ \delta |y - \hat{y}| - \frac{1}{2}\delta^2 &amp;amp; \text{otherwise} \end{cases}\]

&lt;p&gt;trong đó \(\delta\) là siêu tham số ngưỡng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Kết hợp ưu điểm của cả MSE và MAE&lt;/li&gt;
  &lt;li&gt;Hành xử bậc hai với sai số nhỏ và tuyến tính với sai số lớn&lt;/li&gt;
  &lt;li&gt;Trơn và khả vi tại mọi điểm&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Bài toán hồi quy có khả năng xuất hiện điểm ngoại lai&lt;/li&gt;
  &lt;li&gt;Khi cần đồng thời gradient trơn ở gần cực tiểu và tính bền vững trước ngoại lai&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Ít chịu ảnh hưởng bởi ngoại lai hơn MSE&lt;/li&gt;
  &lt;li&gt;Có gradient trơn, khắc phục nhược điểm không khả vi của MAE&lt;/li&gt;
  &lt;li&gt;Linh hoạt điều chỉnh ngưỡng chuyển tiếp qua \(\delta\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Cần tinh chỉnh thêm siêu tham số \(\delta\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, tiếng Anh. Minh họa trực quan sai số bình phương giữa dự đoán và nhãn thật — chính là hàm mất mát hồi quy trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 3&lt;/td&gt;
          &lt;td&gt;Loss Functions and Optimization](https://www.youtube.com/watch?v=h7iBpEHGVNc) — Stanford University School of Engineering, tiếng Anh. Đặt MSE trong bức tranh tổng thể cùng các hàm mất mát khác.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa từng bước sự thay đổi của mặt mất mát hồi quy khi cập nhật tham số.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03 Giới thiệu về Huấn luyện Mạng Neuron</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter03/03_00_Introduction</id>
   <content type="html">&lt;p&gt;Ở Chương 02, ta đã lắp ráp xong bộ khung của mạng nơ-ron—nhưng một mạng vừa khởi tạo ngẫu nhiên chỉ giống như một nghệ sĩ piano bịt mắt bấm phím loạn xạ. Điều gì biến hàng triệu con số vô nghĩa ấy thành một hệ thống nhận diện bệnh lý hay dịch ngôn ngữ chính xác? Câu trả lời là &lt;strong&gt;vòng lặp huấn luyện&lt;/strong&gt;: chấm điểm sai số bằng hàm mất mát (&lt;em&gt;Loss Function&lt;/em&gt;), quy trách nhiệm sai số ngược về từng trọng số bằng &lt;strong&gt;Lan truyền Ngược (&lt;em&gt;Backpropagation&lt;/em&gt;)&lt;/strong&gt;, và tinh chỉnh trọng số từng bước bằng &lt;strong&gt;Gradient Descent&lt;/strong&gt;. Chương 03 chính là “phòng máy” vận hành toàn bộ quá trình học của Deep Learning.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-bánh-răng-của-cỗ-máy-huấn-luyện-mạng-nơ-ron&quot;&gt;Kiến thức cần nhớ: Bốn bánh răng của Cỗ máy Huấn luyện Mạng Nơ-ron&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hàm Mất mát (Loss Functions — Thước đo Sai lầm)&lt;/strong&gt;:
Dịch mục tiêu bài toán thành một con số khả vi duy nhất: MSE/MAE/Huber cho hồi quy; Binary/Categorical Cross-Entropy và Hinge cho phân loại.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Gradient Descent và Tốc độ Học (Optimization Dynamics)&lt;/strong&gt;:
Chọn giữa Batch, Mini-Batch và SGD cùng chiến lược điều chỉnh learning rate để di chuyển nhanh xuống đáy thung lũng mất mát mà không bị phân kỳ hay kẹt ở yên ngựa.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lan truyền Ngược (Backpropagation — Tự động tính Đạo hàm)&lt;/strong&gt;:
Vận dụng quy tắc dây chuyền đa biến theo chiều ngược (&lt;em&gt;reverse-mode autodiff&lt;/em&gt;) để tính toàn bộ hàng triệu đạo hàm riêng chỉ với chi phí ngang ngửa 2–3 lần lan truyền xuôi.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kỹ thuật Huấn luyện Thực chiến (Init, Preprocessing, Monitoring, Early Stopping)&lt;/strong&gt;:
Những “chi tiết nhỏ” quyết định thành bại ngoài đời thực: khởi tạo Xavier/He tránh phá vỡ đối xứng, chuẩn hóa đầu vào, chia tập train/val/test sạch và dừng sớm chống overfitting.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-chạy-tay-trọn-vẹn-1-vòng-lặp-huấn-luyện-trên-1-trọng-số&quot;&gt;Giải thích: Chạy tay trọn vẹn 1 vòng lặp huấn luyện trên 1 trọng số&lt;/h3&gt;

&lt;p&gt;Xét mô hình cực giản đơn \(\hat{y} = w x\) với một mẫu huấn luyện \((x = 2, y = 5)\), trọng số ban đầu \(w_0 = 1.0\), hàm mất mát \(L = \frac{1}{2}(\hat{y} - y)^2\) và learning rate \(\eta = 0.1\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền xuôi (Forward)&lt;/strong&gt;: \(\hat{y} = 1.0 \times 2 = 2.0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính mất mát (Loss)&lt;/strong&gt;: \(L = \frac{1}{2}(2.0 - 5)^2 = \frac{1}{2}(-3)^2 = 4.50\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền ngược (Backward — Chain Rule)&lt;/strong&gt;:
\(\frac{\partial L}{\partial \hat{y}} = \hat{y} - y = -3.0, \quad \frac{\partial \hat{y}}{\partial w} = x = 2 \implies \frac{\partial L}{\partial w} = (-3.0)(2) = -6.0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật Gradient Descent (Step)&lt;/strong&gt;:
\(w_1 = w_0 - \eta \frac{\partial L}{\partial w} = 1.0 - 0.1(-6.0) = 1.6.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng tiến bộ&lt;/strong&gt;: Với \(w_1 = 1.6\), dự đoán mới là \(\hat{y}_1 = 3.2\) và mất mát giảm mạnh từ \(4.50\) xuống \(\frac{1}{2}(3.2 - 5)^2 = 1.62\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Huấn luyện mạng neuron là quá trình tìm bộ trọng số (&lt;em&gt;weights&lt;/em&gt;) và độ lệch (&lt;em&gt;biases&lt;/em&gt;) phù hợp nhằm cực tiểu hóa sai lệch giữa dự đoán của mô hình và giá trị thực tế. Chương này trình bày các thuật toán và kỹ thuật nền tảng dùng để huấn luyện mạng neuron sâu, bao gồm hàm mất mát (&lt;em&gt;loss functions&lt;/em&gt;), gradient descent, lan truyền ngược (&lt;em&gt;backpropagation&lt;/em&gt;) và các chiến lược huấn luyện trong thực tế.&lt;/p&gt;

&lt;p&gt;Hiểu rõ cách mạng neuron học từ dữ liệu là cơ sở quan trọng để xây dựng và gỡ lỗi các hệ thống học sâu hiệu quả.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau khi học xong lan truyền ngược và vòng lặp huấn luyện, bạn có thể xem thêm &lt;strong&gt;03-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về cơ chế vi phân tự động được biên dịch (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;, JAX) và các nhân tính toán lượt ngược đã hợp nhất (&lt;em&gt;fused backward kernels&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (luyện phỏng vấn):&lt;/strong&gt; Sau các bài về hàm mất mát và lan truyền ngược, bạn có thể làm các câu hỏi gốc về vi phân tự động, ma trận Hessian và hồi quy logistic tại &lt;strong&gt;03-98 Luyện phỏng vấn&lt;/strong&gt;; bộ câu hỏi kèm lời giải đầy đủ nằm trong bản PDF &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Liên hệ với phần LLM:&lt;/strong&gt; Đồng nhất thức của cross-entropy kết hợp softmax \(\partial\mathcal{L}/\partial z = p-t\) cùng kỹ thuật log-sum-exp được áp dụng lại cho bài toán dự đoán token tiếp theo ở bài &lt;strong&gt;26-01&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, tiếng Anh. Diễn giải trực quan việc huấn luyện như quá trình tìm cực tiểu của hàm chi phí bằng cách đi xuống dốc.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 3&lt;/td&gt;
          &lt;td&gt;Loss Functions and Optimization](https://www.youtube.com/watch?v=h7iBpEHGVNc) — Stanford University School of Engineering, tiếng Anh. Bài giảng về vai trò của hàm mất mát và các phương pháp tối ưu hóa.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Hướng dẫn tự xây dựng thuật toán lan truyền ngược từ đầu bằng mã Python.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Nhiều người nghĩ mạng truyền thẳng (MLP) học ở Chương 02 chỉ là món đồ chơi giáo khoa đã lỗi thời trước thời đại Transformer. Sự thật sẽ khiến bạn bất ngờ: trong các mô hình ngôn ngữ lớn hàng trăm tỷ tham số như GPT, Llama hay Gemma, &lt;strong&gt;hơn 2/3 tổng số tham số của toàn bộ mô hình lại nằm chính trong các khối MLP&lt;/strong&gt; (thường gọi là khối FFN — Feed-Forward Network)! Tuy nhiên, khối MLP năm 2022–2026 đã tiến hóa mạnh mẽ so với MLP cổ điển với bộ ba vũ khí mới: &lt;strong&gt;Pre-Norm + RMSNorm&lt;/strong&gt;, &lt;strong&gt;cơ chế cổng nhân SwiGLU&lt;/strong&gt;, và kiến trúc thưa &lt;strong&gt;Mixture-of-Experts (MoE)&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nâng-cấp-biến-mlp-cổ-điển-thành-trái-tim-của-transformer-hiện-đại&quot;&gt;Kiến thức cần nhớ: Bốn nâng cấp biến MLP cổ điển thành Trái tim của Transformer Hiện đại&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Pre-Norm kết hợp RMSNorm (thay cho Post-Norm &amp;amp; BatchNorm)&lt;/strong&gt;:
Đưa chuẩn hóa ra &lt;em&gt;trước&lt;/em&gt; khối MLP và chỉ chia cho căn trung bình bình phương (RMS, bỏ bước trừ trung bình) giúp giảm chi phí tính toán và ổn định huấn luyện mạng hàng trăm tầng mà không cần bước warmup quá mong manh.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hàm kích hoạt Cổng nhân SwiGLU&lt;/strong&gt;:
Thay vì \(\mathbf{W}_2\,\text{ReLU}(\mathbf{W}_1\mathbf{x})\), SwiGLU dùng hai nhánh song song: \(\mathbf{W}_{\text{down}}\big(\text{SiLU}(\mathbf{W}_{\text{gate}}\mathbf{x}) \odot (\mathbf{W}_{\text{up}}\mathbf{x})\big)\), giúp mạng điều tiết dòng thông tin mềm dẻo hơn hẳn.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Liên kết Residual (\(\mathbf{x} + \text{MLP}(\text{Norm}(\mathbf{x}))\))&lt;/strong&gt;:
Bảo toàn luồng thông tin gốc và cho phép gradient đi thẳng từ tầng cuối về tầng đầu mà không bị bóp nghẹt.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Mixture-of-Experts (MoE — MLP Thưa)&lt;/strong&gt;:
Thay 1 khối MLP khổng lồ bằng \(E\) khối MLP “chuyên gia” song song kèm một bộ định tuyến (&lt;em&gt;router&lt;/em&gt;) chỉ kích hoạt top-\(k\) chuyên gia (ví dụ \(k=2\) trong \(E=8\)) cho mỗi token—tăng dung lượng tri thức lên gấp nhiều lần mà giữ nguyên FLOPs suy luận!&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-tỷ-lệ-mở-rộng-chiều-ẩn-của-swiglu-để-giữ-nguyên-ngân-sách-tham-số&quot;&gt;Giải thích: Tính tay tỷ lệ mở rộng chiều ẩn của SwiGLU để giữ nguyên ngân sách tham số&lt;/h3&gt;

&lt;p&gt;Trong Transformer cổ điển (dùng ReLU/GELU), khối FFN mở rộng chiều ẩn gấp \(4\) lần (\(d_{\text{ff}} = 4d\)) với &lt;strong&gt;2 ma trận&lt;/strong&gt; \(\mathbf{W}_1 \in \mathbb{R}^{d \times 4d}\) và \(\mathbf{W}_2 \in \mathbb{R}^{4d \times d}\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tổng số tham số FFN cổ điển: \(2 \times (d \times 4d) = 8d^2\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sang &lt;strong&gt;SwiGLU&lt;/strong&gt;, khối FFN có tới &lt;strong&gt;3 ma trận&lt;/strong&gt; (\(\mathbf{W}_{\text{gate}}, \mathbf{W}_{\text{up}}, \mathbf{W}_{\text{down}}\)) với chiều ẩn \(d_{\text{ff}}&apos;\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tổng số tham số SwiGLU: \(3 \times (d \times d_{\text{ff}}&apos;) = 3\,d\,d_{\text{ff}}&apos;\).&lt;/li&gt;
  &lt;li&gt;Để giữ đúng ngân sách \(8d^2\) tham số ngang bằng FFN cổ điển, ta giải:
\(3\,d\,d_{\text{ff}}&apos; = 8d^2 \implies d_{\text{ff}}&apos; = \frac{8}{3}d \approx 2.67\,d.\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Thử với \(d = 4096\) (cỡ Llama-7B): \(\frac{8}{3} \times 4096 \approx 10{,}923\) (làm tròn lên bội của 256 thành \(11{,}008\)). Đó chính xác là lý do bạn luôn thấy con số tưởng chừng kỳ lạ \(\frac{8}{3}d\) hoặc \(11{,}008\) trong bảng thông số kỹ thuật của Llama và Mistral!&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-khối-mlp-hiện-đại&quot;&gt;Tùy chọn: Khối MLP hiện đại&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; trình bày lại lý thuyết về perceptron, kiến trúc, hàm kích hoạt hay lan truyền xuôi. Mục đích của bài là cho thấy các thành phần cơ bản đó được tổ chức ra sao trong các mô hình nền tảng (&lt;em&gt;foundation model&lt;/em&gt;) giai đoạn 2022–2026.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ở mức đơn vị cơ bản, neuron vẫn thực hiện phép tính \(z = \mathbf{w}^\top \mathbf{x} + b\) theo sau bởi một hàm phi tuyến. Điểm thay đổi lớn nằm ở &lt;strong&gt;cấu trúc khối&lt;/strong&gt;: đường nối tắt residual, khối MLP có cổng (&lt;em&gt;gated MLP&lt;/em&gt;) và chuẩn hóa RMSNorm đã trở thành cấu phần mặc định khi xếp chồng các lớp.&lt;/p&gt;

&lt;h2 id=&quot;1-từ-một-neuron-tới-khối-mlp-của-transformer&quot;&gt;1. Từ một neuron tới khối MLP của Transformer&lt;/h2&gt;

&lt;p&gt;Phần lớn các mô hình ngôn ngữ lớn (LLM) hiện nay dùng khối feed-forward có cổng (SwiGLU hoặc GeGLU) thay cho cấu trúc truyền thống &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear → ReLU → Linear&lt;/code&gt;. Với đầu vào \(\mathbf{x} \in \mathbb{R}^{d}\):&lt;/p&gt;

\[\mathrm{SwiGLU}(\mathbf{x}) = \big(\mathrm{SiLU}(\mathbf{x}W_1) \odot (\mathbf{x}W_2)\big) W_3,\]

&lt;p&gt;trong đó \(\mathrm{SiLU}(z) = z\,\sigma(z)\). Về bản chất, đây vẫn là đại số lan truyền xuôi của Chương 02 nhưng bổ sung thêm một nhánh cổng thông qua tích Hadamard (nhân theo từng phần tử). &lt;a href=&quot;https://arxiv.org/abs/2002.05202&quot;&gt;Shazeer, 2020&lt;/a&gt; giới thiệu các biến thể GLU này, và chúng đã trở thành lựa chọn chuẩn trong PaLM, LLaMA cũng như nhiều mô hình mã nguồn mở về sau.&lt;/p&gt;

&lt;h2 id=&quot;2-các-ứng-dụng-và-biến-thể-tiêu-biểu&quot;&gt;2. Các ứng dụng và biến thể tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;pre-norm-kết-hợp-rmsnorm-thay-cho-batchnorm&quot;&gt;Pre-norm kết hợp RMSNorm thay cho BatchNorm&lt;/h3&gt;

&lt;p&gt;Các mô hình LLM hầu như không sử dụng BatchNorm mà chuyển sang &lt;strong&gt;RMSNorm&lt;/strong&gt;:&lt;/p&gt;

\[\mathrm{RMSNorm}(\mathbf{x}) = \frac{\mathbf{x}}{\sqrt{\frac{1}{d}\sum_i x_i^2 + \varepsilon}} \odot \boldsymbol{\gamma}\]

&lt;p&gt;và đặt lớp chuẩn hóa này trước nhánh residual (&lt;em&gt;pre-norm&lt;/em&gt;). Đây là giải pháp thực tiễn giúp kiểm soát thang đo kích hoạt và hạn chế gradient biến mất ở quy mô từ 7B đến 400B tham số.&lt;/p&gt;

&lt;h3 id=&quot;mlp-mixer-và-hướng-tiếp-cận-toàn-mlp-trong-thị-giác&quot;&gt;MLP-Mixer và hướng tiếp cận “toàn MLP” trong thị giác&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2105.01601&quot;&gt;Tolstikhin et al., 2021&lt;/a&gt; (MLP-Mixer) chứng minh rằng chỉ dùng các lớp MLP trộn theo token và trộn theo kênh vẫn có thể phân loại tốt trên ImageNet mà không cần phép tích chập. Giai đoạn 2022–2024, Mixer thường được dùng như một mô hình cơ sở gọn nhẹ bên cạnh ConvNeXt và ViT chứ không thay thế hoàn toàn CNN.&lt;/p&gt;

&lt;h3 id=&quot;kolmogorovarnold-networks-kan&quot;&gt;Kolmogorov–Arnold Networks (KAN)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2404.19756&quot;&gt;Liu et al., 2024&lt;/a&gt; đề xuất thay các hàm kích hoạt cố định đặt trên nút bằng các hàm một biến học được đặt trên &lt;strong&gt;cạnh&lt;/strong&gt;. Nên xem đây là một hướng nghiên cứu thử nghiệm xoay quanh câu hỏi “cấu trúc neuron có thể khác đi thế nào?”, chưa phải lựa chọn mặc định cho các hệ thống thị giác hay NLP thực tế.&lt;/p&gt;

&lt;h2 id=&quot;3-thư-viện-và-phần-mềm-phổ-biến&quot;&gt;3. Thư viện và phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.SiLU&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RMSNorm&lt;/code&gt; và khối SwiGLU trong &lt;a href=&quot;https://github.com/meta-llama/llama&quot;&gt;LLaMA&lt;/a&gt; và &lt;a href=&quot;https://github.com/huggingface/transformers&quot;&gt;Hugging Face transformers&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/pytorch-image-models&quot;&gt;timm&lt;/a&gt; — thư viện cung cấp các khối MLP và ConvNeXt hiện đại cho thị giác máy tính.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-trích-dẫn-20222026&quot;&gt;4. Trích dẫn (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2002.05202&quot;&gt;GLU Variants Improve Transformer (Shazeer, 2020)&lt;/a&gt; — nền tảng cho khối MLP có cổng trong các mô hình ngôn ngữ giai đoạn 2024–2026.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1910.07467&quot;&gt;RMSNorm (Zhang &amp;amp; Sennrich, 2019)&lt;/a&gt; — lớp chuẩn hóa mặc định trong họ mô hình LLaMA.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2404.19756&quot;&gt;KAN (Liu et al., 2024)&lt;/a&gt; — kích hoạt học được trên cạnh; một hướng nghiên cứu bổ sung chứ không thay thế MLP.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-mối-liên-hệ-với-các-bài-học-cốt-lõi&quot;&gt;5. Mối liên hệ với các bài học cốt lõi&lt;/h2&gt;

&lt;p&gt;Các bài về perceptron và hàm kích hoạt giúp bạn hiểu rõ \(z\) và \(\sigma\). Bài này chỉ bổ sung &lt;strong&gt;cách đóng gói hiện đại&lt;/strong&gt; (SwiGLU, RMSNorm, residual) để bạn dễ đọc hiểu khi mở một checkpoint LLM hoặc tài liệu mô hình trên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timm&lt;/code&gt;. Bài &lt;strong&gt;26-07&lt;/strong&gt; sẽ đặt khối này vào toàn bộ kiến trúc decoder cùng RoPE, GQA và phần tính toán chi phí đi kèm.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, tiếng Anh. Minh họa khối MLP bên trong Transformer — dạng lớp liên kết đầy đủ hiện đại được đề cập trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2FaI2Fen1mQ&quot;&gt;The GELU, SiLU and SwiGLU activation functions, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích chi tiết SwiGLU — hàm kích hoạt được sử dụng phổ biến trong các khối MLP hiện đại.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Ôn lại cấu trúc mạng neuron xếp chồng cơ bản để thấy rõ sự phát triển từ một neuron tới MLP của Transformer.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-98 Luyện phỏng vấn (neuron và hàm kích hoạt)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Ở vòng phỏng vấn kỹ thuật Deep Learning, chương Mạng Nơ-ron và Hàm Kích hoạt là “mỏ vàng” của những câu hỏi kiểm tra tư duy sâu: &lt;em&gt;Nếu bỏ hết hàm kích hoạt phi tuyến trong mạng 10 tầng thì chuyện gì xảy ra? Chứng minh Softmax bất biến khi cộng một hằng số? Tại sao Dying ReLU xuất hiện khi learning rate quá lớn?&lt;/em&gt; Những câu hỏi này không đòi hỏi bạn nhớ công thức dài dòng, mà kiểm tra xem bạn có nắm chắc bản chất toán học để giải thích gãy gọn trên bảng trắng hay không.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-chủ-đề-phỏng-vấn-trọng-tâm-của-chương-02&quot;&gt;Kiến thức cần nhớ: Bốn chủ đề Phỏng vấn trọng tâm của Chương 02&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vai trò Không thể thay thế của Tính Phi tuyến&lt;/strong&gt;:
Chứng minh nhanh tích của \(L\) biến đổi affine vẫn là một biến đổi affine duy nhất (\(\mathbf{W}_L \cdots \mathbf{W}_1 \mathbf{x} + \tilde{\mathbf{b}}\)), khiến mọi độ sâu trở nên vô nghĩa nếu thiếu hàm kích hoạt.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tính chất Đại số &amp;amp; Ổn định Số học của Softmax&lt;/strong&gt;:
Chứng minh \(\text{softmax}(\mathbf{z} + c\mathbf{1}) = \text{softmax}(\mathbf{z})\), giải thích cách chọn \(c = -\max_i z_i\) chống tràn số, và phân tích ảnh hưởng của tham số nhiệt độ (&lt;em&gt;temperature&lt;/em&gt; \(T\)) trong \(\text{softmax}(\mathbf{z}/T)\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân tích Đạo hàm &amp;amp; Bệnh lý của Hàm Kích hoạt&lt;/strong&gt;:
So sánh định lượng tốc độ suy giảm gradient của Sigmoid (\(\le 0.25^L\)) với ReLU (\(1\) trên miền dương), đồng thời giải thích cơ chế &lt;em&gt;Dying ReLU&lt;/em&gt; và các phương án thay thế (Leaky ReLU, GELU, SwiGLU).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đếm Tham số và Chi phí Tính toán (FLOPs)&lt;/strong&gt;:
Kỹ năng tính nhẩm cực nhanh số trọng số, bias và bộ nhớ activation của một khối MLP—kỹ năng thực chiến hay bị hỏi trực tiếp trong phỏng vấn ML Engineer.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-ảnh-hưởng-của-nhiệt-độ-temperature-t-lên-softmax&quot;&gt;Giải thích: Tính tay ảnh hưởng của Nhiệt độ (Temperature \(T\)) lên Softmax&lt;/h3&gt;

&lt;p&gt;Một câu hỏi phỏng vấn rất hay gặp trong kỷ nguyên LLM: &lt;em&gt;“Tham số temperature \(T\) trong \(\text{softmax}(\mathbf{z}/T)\) làm thay đổi phân phối xác suất như thế nào?”&lt;/em&gt; Hãy thử trên vector logit \(\mathbf{z} = [2, 1, 0]\) với 3 mức nhiệt độ:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Nhiệt độ \(T\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Logit sau chia \(\mathbf{z}/T\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Xác suất Softmax \(\mathbf{p}\)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hành vi sinh/phân loại&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(T = 0.5\) (Lạnh)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([4, 2, 0]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([0.8668,\; 0.1173,\; 0.0159]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Nhọn (tự tin cao)&lt;/strong&gt;, tiến dần về &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;argmax&lt;/code&gt; khi \(T \to 0^+\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(T = 1.0\) (Chuẩn)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([2, 1, 0]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([0.6652,\; 0.2447,\; 0.0900]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Phân phối Softmax tiêu chuẩn&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;\(T = 2.0\) (Nóng)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([1, 0.5, 0]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\([0.5065,\; 0.3072,\; 0.1863]\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Phẳng (đa dạng hơn)&lt;/strong&gt;, tiến về phân phối đều \([1/3, 1/3, 1/3]\) khi \(T \to \infty\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ bằng 3 dòng tính tay trên vector \([2, 1, 0]\), bạn vừa chứng minh được bản chất của Temperature Sampling trong ChatGPT lẫn Knowledge Distillation!&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-luyện-phỏng-vấn--neuron-và-hàm-kích-hoạt&quot;&gt;Tùy chọn: Luyện phỏng vấn — Neuron và Hàm kích hoạt&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là &lt;strong&gt;tùy chọn&lt;/strong&gt; và &lt;strong&gt;không&lt;/strong&gt; lặp lại phần lý thuyết về perceptron, kiến trúc hay hàm kích hoạt. Sau khi học các bài chính trong chương, bạn có thể dùng bộ câu hỏi dưới đây để tự kiểm tra, rồi tham khảo thêm &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) để xem các câu hỏi kèm lời giải đầy đủ về perceptron, hàm kích hoạt và kiến trúc MLP.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Chủ đề tham khảo trong sách cho chương này (đọc trực tiếp trong bản PDF):&lt;/strong&gt; perceptron, hàm kích hoạt và cấu trúc MLP cơ bản.&lt;/p&gt;

&lt;p&gt;Trang tổng hợp: &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;câu-hỏi-luyện-tập&quot;&gt;Câu hỏi luyện tập&lt;/h2&gt;

&lt;h3 id=&quot;q1-độ-sâu-khi-không-có-tính-phi-tuyến&quot;&gt;Q1. Độ sâu khi không có tính phi tuyến&lt;/h3&gt;

&lt;p&gt;Giả sử bạn xếp ba lớp tuyến tính \(\mathbf{h} = W_3W_2W_1\mathbf{x}\) không kèm hàm kích hoạt. Hãy chứng minh tồn tại một ma trận \(W\) sao cho \(\mathbf{h}=W\mathbf{x}\). Kết quả này nói lên điều gì về việc “thêm lớp” để tăng năng lực biểu diễn?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Phép nhân ma trận có tính chất kết hợp.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Đặt \(W := W_3W_2W_1\), ta thu được một ánh xạ tuyến tính duy nhất. Việc thêm các lớp tuyến tính không mở rộng tập hàm mà mạng có thể biểu diễn — chúng chỉ phân tích cùng một phép biến đổi tuyến tính thành tích nhiều ma trận (và đôi khi còn làm việc tối ưu khó hơn). Chính hàm kích hoạt phi tuyến mới tạo nên sức mạnh của mạng sâu. Trong phỏng vấn, câu hỏi này thường dùng để kiểm tra nhận thức rằng “nhiều lớp hơn” không đồng nghĩa với “mô hình mạnh hơn” nếu thiếu phi tuyến.&lt;/p&gt;

&lt;h3 id=&quot;q2-tính-bất-biến-tịnh-tiến-của-softmax&quot;&gt;Q2. Tính bất biến tịnh tiến của softmax&lt;/h3&gt;

&lt;p&gt;Chứng minh \(\mathrm{softmax}(\mathbf{z}+c\mathbf{1}) = \mathrm{softmax}(\mathbf{z})\) với mọi hằng số vô hướng \(c\). Vì sao các framework thường trừ \(\max_i z_i\) trước khi tính hàm mũ?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Đưa thừa số \(e^{c}\) ra ngoài ở cả tử và mẫu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Cả tử số và mẫu số đều nhân thêm cùng một hằng số dương \(e^{c}\) nên tỷ số không thay đổi. Việc trừ đi giá trị lớn nhất chính là chọn \(c=-\max_i z_i\), giúp đảm bảo mọi số hạng \(e^{z_i+c}\le 1\) và tránh tràn số (&lt;em&gt;overflow&lt;/em&gt;). Tính bất biến này cũng cho thấy một độ lệch cộng đều vào mọi logit không làm thay đổi xác suất — chỉ &lt;em&gt;hiệu&lt;/em&gt; giữa các logit mới có ý nghĩa.&lt;/p&gt;

&lt;h3 id=&quot;q3-vùng-bão-hòa-của-sigmoid&quot;&gt;Q3. Vùng bão hòa của sigmoid&lt;/h3&gt;

&lt;p&gt;Với \(z=10\) và \(z=-10\), hãy ước lượng \(\sigma&apos;(z)\) khi \(\sigma(z)=(1+e^{-z})^{-1}\). Vì sao hiện tượng này gây vấn đề trong mạng sâu dùng nhiều lớp sigmoid?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; \(\sigma&apos;(z)=\sigma(z)(1-\sigma(z))\) đạt giá trị lớn nhất là \(1/4\) tại \(z=0\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Tại \(z=10\), \(\sigma(10)\approx 1\) nên \(\sigma&apos;(10)\approx 0\); tương tự tại \(z=-10\), \(\sigma(-10)\approx 0\) nên \(\sigma&apos;(-10)\approx 0\). Khi lan truyền ngược, các hệ số đạo hàm này bị nhân liên tiếp qua nhiều lớp. Một chuỗi các lớp sigmoid rơi vào vùng bão hòa sẽ kéo gradient ở các lớp đầu về gần 0 (hiện tượng gradient biến mất kinh điển). ReLU khắc phục tình trạng bão hòa ở miền dương, đổi lại có vùng bằng 0 cứng ở miền âm (xem câu sau).&lt;/p&gt;

&lt;h3 id=&quot;q4-hiện-tượng-relu-chết&quot;&gt;Q4. Hiện tượng ReLU chết&lt;/h3&gt;

&lt;p&gt;Một neuron ẩn tính \(\mathrm{ReLU}(\mathbf{w}^\top\mathbf{x}+b)\). Hãy nêu một điều kiện đơn giản trên \((\mathbf{w},b)\) và tập dữ liệu huấn luyện để neuron này luôn cho ra \(0\) trên mọi mẫu và giữ nguyên trạng thái đó sau mọi bước SGD.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Nếu giá trị tiền kích hoạt âm trên toàn bộ batch thì gradient theo \((\mathbf{w},b)\) đều bằng 0.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Nếu \(\mathbf{w}^\top\mathbf{x}+b&amp;lt;0\) với mọi mẫu \(\mathbf{x}\) trong tập huấn luyện, cả đầu ra ReLU lẫn đạo hàm cục bộ của nó đều bằng 0, nên SGD sẽ không bao giờ cập nhật \((\mathbf{w},b)\). Độ lệch khởi tạo quá âm, khởi tạo trọng số kém hoặc tốc độ học quá lớn có thể đẩy nhiều neuron vào trạng thái này. Cách giảm thiểu thường dùng là chuyển sang Leaky ReLU hoặc GELU, đồng thời kiểm soát tốc độ học khi hàm mất mát tăng đột biến.&lt;/p&gt;

&lt;h3 id=&quot;q5-đếm-số-tham-số-của-mlp&quot;&gt;Q5. Đếm số tham số của MLP&lt;/h3&gt;

&lt;p&gt;Một mạng MLP có cấu trúc \(784\to 256\to 256\to 10\) (có độ lệch ở mọi lớp). Hỏi có bao nhiêu tham số vô hướng cần huấn luyện? Con số này thay đổi thế nào nếu chèn thêm một khối residual cùng độ rộng \(256\) (gồm một lớp affine kèm ReLU và đường nối tắt đồng nhất)?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Một lớp ánh xạ \(\mathbb{R}^{m}\to\mathbb{R}^{n}\) có \(nm+n\) tham số.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Lớp thứ nhất (\(784 \to 256\)) có \(784\cdot 256+256\) tham số; lớp thứ hai (\(256 \to 256\)) có \(256\cdot 256+256\) tham số; lớp đầu ra (\(256 \to 10\)) có \(256\cdot 10+10\) tham số. Tổng cộng là \(784\cdot 256 + 256^{2} + 256\cdot 10 + (256+256+10) = 269{,}322\) tham số. Nếu chèn thêm một khối residual cùng độ rộng \(256\) gồm một lớp tuyến tính cộng đường nối tắt đồng nhất, số tham số tăng thêm đúng \(256^{2}+256 = 65{,}792\) (vì đường nối tắt đồng nhất không thêm trọng số khi hai đầu cùng kích thước). Trong phỏng vấn, người hỏi thường muốn nghe cả cách tính cụ thể lẫn nhận xét rằng nhánh skip đồng nhất không làm tăng tham số.&lt;/p&gt;

&lt;h2 id=&quot;ghi-công&quot;&gt;Ghi công&lt;/h2&gt;

&lt;p&gt;Kashani, S., và Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Bạn có thể tải bản PDF từ arXiv để tham khảo đầy đủ các câu hỏi và lời giải. Trang này là bộ bài tập luyện gốc của khóa học, không phải bản sao chép từ sách.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Nên xem trước khi làm các câu hỏi về neuron và hàm kích hoạt.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=68BZ5f7P94E&quot;&gt;Neural Networks Pt. 3: ReLU In Action!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa trực quan điểm gãy của ReLU — chủ đề rất hay xuất hiện khi phỏng vấn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NkOv_k7r6no&quot;&gt;Why Non-linear Activation Functions (C1W3L07)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Giải thích rõ vì sao hàm kích hoạt phải phi tuyến (liên quan trực tiếp tới câu Q1).&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-04 Lan truyền Xuôi</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_04_Forward_Propagation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_04_Forward_Propagation</id>
   <content type="html">&lt;p&gt;Nếu lan truyền ngược là quá trình “học từ sai lầm”, thì &lt;strong&gt;lan truyền xuôi (&lt;em&gt;forward propagation&lt;/em&gt;)&lt;/strong&gt; chính là quá trình mạng nơ-ron “suy nghĩ và đưa ra câu trả lời”. Viết vòng lặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; lồng nhau cho từng nơ-ron và từng mẫu dữ liệu bằng Python thuần có thể mất hàng giờ đồng hồ, nhưng chỉ cần viết lại đúng phép tính đó dưới dạng &lt;strong&gt;nhân ma trận theo batch (vectorization)&lt;/strong&gt;, GPU có thể xử lý xong hàng chục nghìn ảnh trong vài mili-giây. Bài học này dẫn bạn đi từng bước toán học của lan truyền xuôi, từ một mẫu đơn lẻ đến mini-batch đa chiều và trực giác hình học đằng sau mỗi tầng biến đổi.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-lan-truyền-xuôi&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Lan truyền Xuôi&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Chuỗi Biến đổi Đệ quy qua từng Tầng&lt;/strong&gt;:
Bắt đầu từ \(\mathbf{A}^{(0)} = \mathbf{X}\), mỗi tầng \(\ell = 1, \dots, L\) thực hiện đúng hai bước: biến đổi tuyến tính \(\mathbf{Z}^{(\ell)} = \mathbf{A}^{(\ell-1)}\mathbf{W}^{(\ell)} + \mathbf{b}^{(\ell)}\) (có broadcasting cho \(\mathbf{b}^{(\ell)}\)) và kích hoạt phi tuyến \(\mathbf{A}^{(\ell)} = \sigma_\ell(\mathbf{Z}^{(\ell)})\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kiểm soát Kích thước Ma trận (Shape Tracking)&lt;/strong&gt;:
Với mini-batch \(B\) mẫu, nếu \(\mathbf{A}^{(\ell-1)} \in \mathbb{R}^{B \times n_{\ell-1}}\) và \(\mathbf{W}^{(\ell)} \in \mathbb{R}^{n_{\ell-1} \times n_\ell}\), thì \(\mathbf{Z}^{(\ell)}, \mathbf{A}^{(\ell)} \in \mathbb{R}^{B \times n_\ell}\). Theo dõi kích thước ở từng dòng là kỹ năng phòng tránh lỗi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RuntimeError: mat1 and mat2 shapes cannot be multiplied&lt;/code&gt; tốt nhất.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lưu giữ Bộ nhớ Đệm (Activation Caching)&lt;/strong&gt;:
Trong chế độ huấn luyện, lan truyền xuôi không thể vứt bỏ các giá trị trung gian \(\mathbf{Z}^{(\ell)}, \mathbf{A}^{(\ell)}\)—nó phải giữ lại trong VRAM để phục vụ tính đạo hàm lúc lan truyền ngược (trừ khi bật &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.no_grad()&lt;/code&gt; lúc suy luận).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Trực giác Hình học của Chuỗi Tầng&lt;/strong&gt;:
Mỗi tầng không di chuyển điểm dữ liệu một cách hỗn loạn mà liên tục xoay, kéo giãn và gấp không gian để đến tầng cuối cùng, các lớp khác nhau nằm gọn trên hai phía đối diện của một siêu phẳng.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-lan-truyền-xuôi-cho-một-mini-batch-2-mẫu-qua-mạng-221&quot;&gt;Giải thích: Tính tay Lan truyền Xuôi cho một Mini-Batch 2 mẫu qua mạng 2–2–1&lt;/h3&gt;

&lt;p&gt;Xét mini-batch gồm 2 mẫu \(\mathbf{X} = \begin{bmatrix} 1 &amp;amp; 0 \\ -1 &amp;amp; 2 \end{bmatrix} \in \mathbb{R}^{2 \times 2}\) đi qua mạng có:
\(\mathbf{W}^{(1)} = \begin{bmatrix} 1 &amp;amp; -1 \\ 2 &amp;amp; 1 \end{bmatrix}, \;\mathbf{b}^{(1)} = \begin{bmatrix} 0 &amp;amp; 1 \end{bmatrix}, \;\mathbf{W}^{(2)} = \begin{bmatrix} 1 \\ -2 \end{bmatrix}, \; b^{(2)} = 0.5.\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tầng ẩn 1 — Phép nhân ma trận + Broadcasting bias&lt;/strong&gt;:
\(\mathbf{Z}^{(1)} = \mathbf{X}\mathbf{W}^{(1)} + \mathbf{b}^{(1)} = \begin{bmatrix} 1(1)+0(2) &amp;amp; 1(-1)+0(1) \\ -1(1)+2(2) &amp;amp; -1(-1)+2(1) \end{bmatrix} + \begin{bmatrix} 0 &amp;amp; 1 \\ 0 &amp;amp; 1 \end{bmatrix} = \begin{bmatrix} 1 &amp;amp; -1 \\ 3 &amp;amp; 3 \end{bmatrix} + \begin{bmatrix} 0 &amp;amp; 1 \\ 0 &amp;amp; 1 \end{bmatrix} = \begin{bmatrix} 1 &amp;amp; 0 \\ 3 &amp;amp; 4 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng ẩn 1 — Áp dụng ReLU từng phần tử&lt;/strong&gt;:
Vì mọi phần tử của \(\mathbf{Z}^{(1)}\) đều \(\ge 0\), ta có \(\mathbf{A}^{(1)} = \begin{bmatrix} 1 &amp;amp; 0 \\ 3 &amp;amp; 4 \end{bmatrix} \in \mathbb{R}^{2 \times 2}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng đầu ra — Biến đổi tuyến tính + Sigmoid&lt;/strong&gt;:
\(\mathbf{Z}^{(2)} = \mathbf{A}^{(1)}\mathbf{W}^{(2)} + b^{(2)} = \begin{bmatrix} 1(1) + 0(-2) + 0.5 \\ 3(1) + 4(-2) + 0.5 \end{bmatrix} = \begin{bmatrix} 1.5 \\ -4.5 \end{bmatrix}.\)
Qua Sigmoid: \(\hat{\mathbf{y}} = \begin{bmatrix} \sigma(1.5) \\ \sigma(-4.5) \end{bmatrix} \approx \begin{bmatrix} 0.8176 \\ 0.0110 \end{bmatrix}.\)
Chỉ với hai phép nhân ma trận song song, cả hai mẫu đã được dự đoán đồng thời mà không cần bất kỳ vòng lặp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; nào!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bài này trình bày chi tiết về lan truyền xuôi (&lt;em&gt;forward propagation&lt;/em&gt;) — quá trình mạng neuron tính toán và đưa ra dự đoán từ dữ liệu đầu vào.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;lan-truyền-xuôi-là-gì&quot;&gt;Lan truyền Xuôi là gì?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Lan truyền xuôi&lt;/strong&gt; là quá trình tính toán đầu ra của mạng neuron ứng với một đầu vào cho trước. Dữ liệu đi theo chiều thuận từ lớp đầu vào, lần lượt qua tất cả các lớp ẩn cho đến lớp đầu ra.&lt;/p&gt;

&lt;p&gt;Đây chính là giai đoạn &lt;strong&gt;suy luận&lt;/strong&gt; (&lt;em&gt;inference&lt;/em&gt;) hoặc &lt;strong&gt;dự đoán&lt;/strong&gt; của mạng neuron.&lt;/p&gt;

&lt;h3 id=&quot;trực-giác-hình-học-của-một-bước-lan-truyền-xuôi&quot;&gt;Trực giác hình học của một bước lan truyền xuôi&lt;/h3&gt;

&lt;p&gt;Với một lớp ẩn dùng ReLU và lớp đầu ra dùng hàm kích hoạt \(\sigma\), quá trình lan truyền xuôi có thể viết gọn:&lt;/p&gt;

\[\mathbf{h} = (W_h \mathbf{x} + b_h)^+,\qquad \hat{\mathbf{y}} = \sigma(W_y \mathbf{h} + b_y)\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/mlp_hidden_relu_forward.jpg&quot; alt=&quot;Forward: hidden ReLU rồi output σ&quot; /&gt;
&lt;em&gt;Hình: Luồng tính toán \(x \to h \to \hat{y}\) với ReLU ở lớp ẩn và \(\sigma\) ở lớp đầu ra. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Mỗi phép biến đổi &lt;strong&gt;affine&lt;/strong&gt; (nhân \(W\) rồi cộng \(b\)) thực hiện xoay, kéo giãn hoặc tịnh tiến không gian; sau đó ReLU “gấp” nửa không gian âm về 0. Chính thao tác phi tuyến này giúp mạng nhiều lớp biểu diễn được các ranh giới phức tạp hơn một phép biến đổi tuyến tính.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/feature_space_folding_relu.jpg&quot; alt=&quot;ReLU gấp không gian đặc trưng&quot; /&gt;
&lt;em&gt;Hình: Sau phép biến đổi \(h=(W_h x+b_h)^+\), tập điểm dữ liệu được gấp và biến dạng phi tuyến trong không gian đặc trưng. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/feature_space_after_transform.jpg&quot; alt=&quot;Biểu diễn sau biến đổi lớp&quot; /&gt;
&lt;em&gt;Hình: Dữ liệu sau khi đi qua các lớp — lan truyền xuôi có thể được hình dung như chuỗi các phép biến đổi hình học liên tiếp. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lan truyền xuôi như quá trình tái tạo hàm số:&lt;/strong&gt; Trong bài toán hồi quy 1D, mỗi lần đưa một giá trị \(x\) qua mạng ta thu được một điểm \((x, \hat{y})\); lặp lại trên nhiều giá trị \(x\) sẽ vẽ ra đường cong mà mạng đã học. Các neuron ẩn sẽ kích hoạt mạnh hoặc yếu khác nhau tùy thuộc vào vùng giá trị của đầu vào.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_predictions_complex_curve.jpg&quot; alt=&quot;Dự đoán nhiều điểm trên đường cong&quot; /&gt;
&lt;em&gt;Hình: Thực hiện lan truyền xuôi trên nhiều điểm \(x\) giúp tái tạo đường cong xấp xỉ. (Minh họa từ video về bản chất mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;quy-trình-lan-truyền-xuôi-từng-bước&quot;&gt;Quy trình Lan truyền Xuôi Từng Bước&lt;/h2&gt;

&lt;p&gt;Xét một mạng 3 lớp đơn giản:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lớp đầu vào:&lt;/strong&gt; \(n^{[0]} = 3\) đặc trưng&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lớp ẩn 1:&lt;/strong&gt; \(n^{[1]} = 4\) neuron với ReLU&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lớp ẩn 2:&lt;/strong&gt; \(n^{[2]} = 4\) neuron với ReLU&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lớp đầu ra:&lt;/strong&gt; \(n^{[3]} = 1\) neuron với sigmoid (phân loại nhị phân)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;lớp-0-đầu-vào&quot;&gt;Lớp 0: Đầu vào&lt;/h3&gt;

\[\mathbf{a}^{[0]} = \mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \\ x_3 \end{bmatrix}\]

&lt;h3 id=&quot;lớp-1-lớp-ẩn-thứ-nhất&quot;&gt;Lớp 1: Lớp Ẩn Thứ nhất&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Biến đổi tuyến tính:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{z}^{[1]} = \mathbf{W}^{[1]} \mathbf{a}^{[0]} + \mathbf{b}^{[1]}\]

&lt;p&gt;Trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{W}^{[1]} \in \mathbb{R}^{4 \times 3}\) (4 neuron, mỗi neuron nhận 3 đầu vào)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{b}^{[1]} \in \mathbb{R}^{4}\) (4 hệ số độ lệch)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{z}^{[1]} \in \mathbb{R}^{4}\) (các giá trị tiền kích hoạt)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kích hoạt:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{a}^{[1]} = \text{ReLU}(\mathbf{z}^{[1]}) = \max(0, \mathbf{z}^{[1]})\]

&lt;p&gt;\(\mathbf{a}^{[1]} \in \mathbb{R}^{4}\) (vector đầu ra của lớp 1)&lt;/p&gt;

&lt;h3 id=&quot;lớp-2-lớp-ẩn-thứ-hai&quot;&gt;Lớp 2: Lớp Ẩn Thứ hai&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Biến đổi tuyến tính:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{z}^{[2]} = \mathbf{W}^{[2]} \mathbf{a}^{[1]} + \mathbf{b}^{[2]}\]

&lt;p&gt;Trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[\mathbf{W}^{[2]} \in \mathbb{R}^{4 \times 4}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbf{b}^{[2]} \in \mathbb{R}^{4}\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kích hoạt:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{a}^{[2]} = \text{ReLU}(\mathbf{z}^{[2]})\]

&lt;h3 id=&quot;lớp-3-lớp-đầu-ra&quot;&gt;Lớp 3: Lớp Đầu ra&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Biến đổi tuyến tính:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{z}^{[3]} = \mathbf{W}^{[3]} \mathbf{a}^{[2]} + \mathbf{b}^{[3]}\]

&lt;p&gt;Trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[\mathbf{W}^{[3]} \in \mathbb{R}^{1 \times 4}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbf{b}^{[3]} \in \mathbb{R}^{1}\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Kích hoạt (đầu ra):&lt;/strong&gt;&lt;/p&gt;

\[\hat{y} = \mathbf{a}^{[3]} = \sigma(\mathbf{z}^{[3]}) = \frac{1}{1 + e^{-\mathbf{z}^{[3]}}}\]

&lt;p&gt;Kết quả thu được là xác suất dự đoán mẫu thuộc lớp dương.&lt;/p&gt;

&lt;h2 id=&quot;lan-truyền-xuôi-dạng-ma-trận-vector-hóa&quot;&gt;Lan truyền Xuôi Dạng Ma trận (Vector hóa)&lt;/h2&gt;

&lt;p&gt;Để tận dụng phần cứng và tăng tốc tính toán, ta xử lý &lt;strong&gt;nhiều mẫu đồng thời&lt;/strong&gt; thông qua kỹ thuật &lt;strong&gt;vector hóa&lt;/strong&gt; (&lt;em&gt;vectorization&lt;/em&gt;).&lt;/p&gt;

&lt;h3 id=&quot;xử-lý-theo-batch&quot;&gt;Xử lý theo Batch&lt;/h3&gt;

&lt;p&gt;Thay vì đưa từng mẫu một vào mạng, ta xếp \(m\) mẫu thành các cột của một ma trận:&lt;/p&gt;

\[\mathbf{X} = \begin{bmatrix} | &amp;amp; | &amp;amp; &amp;amp; | \\ \mathbf{x}^{(1)} &amp;amp; \mathbf{x}^{(2)} &amp;amp; \cdots &amp;amp; \mathbf{x}^{(m)} \\ | &amp;amp; | &amp;amp; &amp;amp; | \end{bmatrix} \in \mathbb{R}^{n^{[0]} \times m}\]

&lt;p&gt;Mỗi cột tương ứng với một mẫu dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;phép-tính-theo-batch&quot;&gt;Phép tính theo Batch&lt;/h3&gt;

&lt;p&gt;Tại lớp \(l\):&lt;/p&gt;

\[\mathbf{Z}^{[l]} = \mathbf{W}^{[l]} \mathbf{A}^{[l-1]} + \mathbf{b}^{[l]}\]

\[\mathbf{A}^{[l]} = g^{[l]}(\mathbf{Z}^{[l]})\]

&lt;p&gt;Trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{A}^{[l]} \in \mathbb{R}^{n^{[l]} \times m}\) (mỗi cột là kích hoạt của một mẫu)&lt;/li&gt;
  &lt;li&gt;
\[\mathbf{Z}^{[l]} \in \mathbb{R}^{n^{[l]} \times m}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbf{W}^{[l]} \in \mathbb{R}^{n^{[l]} \times n^{[l-1]}}\]
  &lt;/li&gt;
  &lt;li&gt;\(\mathbf{b}^{[l]} \in \mathbb{R}^{n^{[l]} \times 1}\) (được mở rộng chiều tự động qua tất cả \(m\) mẫu)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;cơ-chế-broadcasting&quot;&gt;Cơ chế Broadcasting&lt;/h3&gt;

&lt;p&gt;Python/NumPy tự động thực hiện &lt;em&gt;broadcasting&lt;/em&gt; cho \(\mathbf{b}^{[l]}\) trên toàn bộ các cột của batch:&lt;/p&gt;

\[\mathbf{b}^{[l]} \in \mathbb{R}^{n^{[l]} \times 1} \rightarrow \mathbb{R}^{n^{[l]} \times m}\]

&lt;p&gt;Nhờ đó, mọi cột của ma trận tích đều được cộng cùng một vector độ lệch.&lt;/p&gt;

&lt;h2 id=&quot;ví-dụ-tính-toán-cụ-thể&quot;&gt;Ví dụ Tính toán Cụ thể&lt;/h2&gt;

&lt;p&gt;Hãy theo dõi một ví dụ nhỏ với các con số cụ thể.&lt;/p&gt;

&lt;h3 id=&quot;cấu-hình-mạng&quot;&gt;Cấu hình Mạng&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Đầu vào: 2 đặc trưng (\(n^{[0]} = 2\))&lt;/li&gt;
  &lt;li&gt;Lớp ẩn: 3 neuron với ReLU (\(n^{[1]} = 3\))&lt;/li&gt;
  &lt;li&gt;Đầu ra: 1 neuron với sigmoid (\(n^{[2]} = 1\))&lt;/li&gt;
  &lt;li&gt;Kích thước batch: 2 mẫu (\(m = 2\))&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tham-số&quot;&gt;Tham số&lt;/h3&gt;

\[\mathbf{W}^{[1]} = \begin{bmatrix} 0.5 &amp;amp; -0.3 \\ 0.2 &amp;amp; 0.8 \\ -0.4 &amp;amp; 0.6 \end{bmatrix}, \quad \mathbf{b}^{[1]} = \begin{bmatrix} 0.1 \\ -0.2 \\ 0.3 \end{bmatrix}\]

\[\mathbf{W}^{[2]} = \begin{bmatrix} 1.0 &amp;amp; -0.5 &amp;amp; 0.7 \end{bmatrix}, \quad \mathbf{b}^{[2]} = \begin{bmatrix} 0.5 \end{bmatrix}\]

&lt;h3 id=&quot;dữ-liệu-đầu-vào&quot;&gt;Dữ liệu Đầu vào&lt;/h3&gt;

\[\mathbf{X} = \mathbf{A}^{[0]} = \begin{bmatrix} 1.0 &amp;amp; 0.5 \\ 2.0 &amp;amp; 1.5 \end{bmatrix}\]

&lt;p&gt;Mẫu 1: \(\mathbf{x}^{(1)} = \begin{bmatrix} 1.0 \\ 2.0 \end{bmatrix}\), Mẫu 2: \(\mathbf{x}^{(2)} = \begin{bmatrix} 0.5 \\ 1.5 \end{bmatrix}\)&lt;/p&gt;

&lt;h3 id=&quot;lan-truyền-xuôi-lớp-1&quot;&gt;Lan truyền Xuôi: Lớp 1&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tính \(\mathbf{Z}^{[1]}\):&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{Z}^{[1]} = \mathbf{W}^{[1]} \mathbf{A}^{[0]} + \mathbf{b}^{[1]}\]

\[= \begin{bmatrix} 0.5 &amp;amp; -0.3 \\ 0.2 &amp;amp; 0.8 \\ -0.4 &amp;amp; 0.6 \end{bmatrix} \begin{bmatrix} 1.0 &amp;amp; 0.5 \\ 2.0 &amp;amp; 1.5 \end{bmatrix} + \begin{bmatrix} 0.1 \\ -0.2 \\ 0.3 \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Kết quả nhân ma trận:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Cột thứ nhất: \(\begin{bmatrix} 0.5(1.0) + (-0.3)(2.0) \\ 0.2(1.0) + 0.8(2.0) \\ -0.4(1.0) + 0.6(2.0) \end{bmatrix} = \begin{bmatrix} -0.1 \\ 1.8 \\ 0.8 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Cột thứ hai: \(\begin{bmatrix} 0.5(0.5) + (-0.3)(1.5) \\ 0.2(0.5) + 0.8(1.5) \\ -0.4(0.5) + 0.6(1.5) \end{bmatrix} = \begin{bmatrix} -0.2 \\ 1.3 \\ 0.7 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Sau khi cộng vector độ lệch:&lt;/p&gt;

\[\mathbf{Z}^{[1]} = \begin{bmatrix} -0.1+0.1 &amp;amp; -0.2+0.1 \\ 1.8-0.2 &amp;amp; 1.3-0.2 \\ 0.8+0.3 &amp;amp; 0.7+0.3 \end{bmatrix} = \begin{bmatrix} 0.0 &amp;amp; -0.1 \\ 1.6 &amp;amp; 1.1 \\ 1.1 &amp;amp; 1.0 \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Áp dụng kích hoạt ReLU:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{A}^{[1]} = \text{ReLU}(\mathbf{Z}^{[1]}) = \begin{bmatrix} 0.0 &amp;amp; 0.0 \\ 1.6 &amp;amp; 1.1 \\ 1.1 &amp;amp; 1.0 \end{bmatrix}\]

&lt;h3 id=&quot;lan-truyền-xuôi-lớp-2-đầu-ra&quot;&gt;Lan truyền Xuôi: Lớp 2 (Đầu ra)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tính \(\mathbf{Z}^{[2]}\):&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{Z}^{[2]} = \mathbf{W}^{[2]} \mathbf{A}^{[1]} + \mathbf{b}^{[2]}\]

\[= \begin{bmatrix} 1.0 &amp;amp; -0.5 &amp;amp; 0.7 \end{bmatrix} \begin{bmatrix} 0.0 &amp;amp; 0.0 \\ 1.6 &amp;amp; 1.1 \\ 1.1 &amp;amp; 1.0 \end{bmatrix} + \begin{bmatrix} 0.5 \end{bmatrix}\]

\[= \begin{bmatrix} 1.0(0.0) + (-0.5)(1.6) + 0.7(1.1) + 0.5 &amp;amp; 1.0(0.0) + (-0.5)(1.1) + 0.7(1.0) + 0.5 \end{bmatrix}\]

\[= \begin{bmatrix} 0.47 &amp;amp; 0.65 \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Áp dụng kích hoạt sigmoid:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{A}^{[2]} = \sigma(\mathbf{Z}^{[2]}) = \begin{bmatrix} \frac{1}{1+e^{-0.47}} &amp;amp; \frac{1}{1+e^{-0.65}} \end{bmatrix} \approx \begin{bmatrix} 0.615 &amp;amp; 0.657 \end{bmatrix}\]

&lt;h3 id=&quot;dự-đoán-cuối-cùng&quot;&gt;Dự đoán Cuối cùng&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Mẫu 1: \(\hat{y}^{(1)} = 0.615\) (xác suất 61.5% thuộc lớp dương)&lt;/li&gt;
  &lt;li&gt;Mẫu 2: \(\hat{y}^{(2)} = 0.657\) (xác suất 65.7% thuộc lớp dương)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;triển-khai-bằng-python&quot;&gt;Triển khai bằng Python&lt;/h2&gt;

&lt;h3 id=&quot;triển-khai-cơ-bản&quot;&gt;Triển khai Cơ bản&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward_propagation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Arguments:
    X -- dữ liệu đầu vào có dạng (n_x, m)
    parameters -- từ điển Python chứa W1, b1, W2, b2, W3, b3, ...
    
    Returns:
    AL -- giá trị hậu kích hoạt cuối (dự đoán)
    caches -- danh sách cache chứa (A_prev, W, b, Z) cho mỗi lớp
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# số lớp
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Lan truyền xuôi qua lớp ẩn (kích hoạt ReLU)
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Lớp đầu ra (kích hoạt sigmoid)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ sử dụng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W2&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b2&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward_propagation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Output: Predictions: [[0.615 0.657]]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;triển-khai-hướng-đối-tượng&quot;&gt;Triển khai Hướng Đối tượng&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Arguments:
        layer_dims -- danh sách chứa chiều của mỗi lớp
                     Ví dụ: [2, 3, 1] nghĩa là 2 đầu vào, 3 ẩn, 1 đầu ra
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;initialize_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;initialize_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Lan truyền xuôi&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lớp ẩn với ReLU
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ReLU
&lt;/span&gt;            
            &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lớp đầu ra với sigmoid
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Sigmoid
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Đưa ra dự đoán (0 hoặc 1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sử dụng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;các-lỗi-thường-gặp-và-cách-gỡ-lỗi&quot;&gt;Các Lỗi Thường gặp và Cách Gỡ lỗi&lt;/h2&gt;

&lt;h3 id=&quot;1-không-khớp-kích-thước-ma-trận&quot;&gt;1. Không khớp Kích thước Ma trận&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Vấn đề:&lt;/strong&gt; Phép nhân ma trận báo lỗi do kích thước không tương thích.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cách xử lý:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Kiểm tra \(\mathbf{W}^{[l]}\) có kích thước \((n^{[l]}, n^{[l-1]})\)&lt;/li&gt;
  &lt;li&gt;Kiểm tra \(\mathbf{A}^{[l-1]}\) có kích thước \((n^{[l-1]}, m)\)&lt;/li&gt;
  &lt;li&gt;In kích thước từng tensor hoặc dùng debugger để đối chiếu&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Layer &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  W shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  A_prev shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  b shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Z shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;2-bất-ổn-số-học&quot;&gt;2. Bất ổn Số học&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Vấn đề:&lt;/strong&gt; Hiện tượng tràn số trên (&lt;em&gt;overflow&lt;/em&gt;) hoặc tràn số dưới (&lt;em&gt;underflow&lt;/em&gt;) khi tính hàm mũ, đặc biệt trong sigmoid và softmax.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cách xử lý:&lt;/strong&gt; Dùng dạng công thức ổn định số:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Không ổn định
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid_unstable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Phiên bản ổn định
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid_stable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                    &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;3-lỗi-broadcasting-ở-độ-lệch&quot;&gt;3. Lỗi Broadcasting ở Độ lệch&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Vấn đề:&lt;/strong&gt; Vector độ lệch bị cộng sai chiều do thiếu trục cột.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cách xử lý:&lt;/strong&gt; Luôn giữ kích thước của độ lệch là \((n^{[l]}, 1)\) thay vì mảng 1 chiều \((n^{[l]},)\).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Đúng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Dạng (n_l, 1)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Sai (có thể gây vấn đề)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Dạng (n_l,)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;độ-phức-tạp-của-lan-truyền-xuôi&quot;&gt;Độ phức tạp của Lan truyền Xuôi&lt;/h2&gt;

&lt;h3 id=&quot;độ-phức-tạp-thời-gian&quot;&gt;Độ phức tạp Thời gian&lt;/h3&gt;

&lt;p&gt;Với mạng gồm \(L\) lớp và mỗi lớp có \(n\) neuron:&lt;/p&gt;

\[O(L \cdot n^2 \cdot m)\]

&lt;p&gt;trong đó \(m\) là kích thước batch.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Giải thích:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mỗi lớp tốn \(O(n^2 \cdot m)\) cho phép nhân ma trận \(\mathbf{W}^{[l]} \mathbf{A}^{[l-1]}\)&lt;/li&gt;
  &lt;li&gt;Nhân với tổng số \(L\) lớp&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;độ-phức-tạp-không-gian&quot;&gt;Độ phức tạp Không gian&lt;/h3&gt;

\[O(L \cdot n \cdot m)\]

&lt;p&gt;Bộ nhớ này dùng để lưu lại các giá trị kích hoạt trung gian ở từng lớp phục vụ cho quá trình lan truyền ngược.&lt;/p&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền xuôi&lt;/strong&gt; tính đầu ra dự đoán bằng cách đưa dữ liệu đi tuần tự qua các lớp của mạng.&lt;/li&gt;
  &lt;li&gt;Mỗi lớp thực hiện hai bước: &lt;strong&gt;biến đổi tuyến tính&lt;/strong&gt; rồi &lt;strong&gt;áp dụng hàm kích hoạt&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vector hóa&lt;/strong&gt; giúp tính toán song song trên cả batch dữ liệu với hiệu năng cao.&lt;/li&gt;
  &lt;li&gt;Biểu thức tổng quát: \(\mathbf{Z}^{[l]} = \mathbf{W}^{[l]} \mathbf{A}^{[l-1]} + \mathbf{b}^{[l]}, \quad \mathbf{A}^{[l]} = g^{[l]}(\mathbf{Z}^{[l]})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lưu đệm (&lt;em&gt;cache&lt;/em&gt;)&lt;/strong&gt; các giá trị trung gian là cần thiết để lan truyền ngược tính gradient nhanh chóng.&lt;/li&gt;
  &lt;li&gt;Kiểm soát đúng &lt;strong&gt;kích thước ma trận&lt;/strong&gt; và &lt;strong&gt;ổn định số học&lt;/strong&gt; giúp tránh nhiều lỗi cài đặt phổ biến.&lt;/li&gt;
  &lt;li&gt;Độ phức tạp thời gian của lan truyền xuôi là \(O(L \cdot n^2 \cdot m)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sau khi nắm cách mạng tính toán dự đoán, chương tiếp theo sẽ trình bày &lt;strong&gt;lan truyền ngược&lt;/strong&gt; và &lt;strong&gt;gradient descent&lt;/strong&gt; — các thuật toán giúp mạng học tham số từ dữ liệu.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video của Machine Learning Thực Chiến:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/793200140509765&quot;&gt;Trực giác mạng nơ-ron (Perceptron → Deep Learning)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/720970114372332&quot;&gt;Mạng nơ-ron là bộ xấp xỉ hàm&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=a8i2eJin0lY&quot;&gt;Forward Propagation in a Deep Network (C1W4L02)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Trình bày từng phương trình lan truyền xuôi qua từng lớp, khớp trực tiếp với nội dung bài học.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qzPQ8cEsVK8&quot;&gt;Forward and Backward Propagation (C1W4L06)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Đặt lượt xuôi bên cạnh lượt ngược để thấy cách sử dụng các giá trị lưu đệm vừa tính.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Xây dựng mạng nơ-ron nhân tạo từ con số 0&lt;/td&gt;
          &lt;td&gt;Writing a Neural Network from scratch](https://www.youtube.com/watch?v=VBviWbusHd8) — Học Lập Trình cùng Phát, tiếng Việt. Hướng dẫn cài đặt lan truyền xuôi từ đầu bằng tiếng Việt.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-03 Hàm Kích hoạt Chi tiết</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_03_Activation_Functions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_03_Activation_Functions</id>
   <content type="html">&lt;p&gt;Thử tưởng tượng bạn xây một tòa tháp gồm 100 tầng mạng nơ-ron, đầu tư cả dàn GPU đắt tiền, nhưng quên mất một chi tiết nhỏ: &lt;strong&gt;không đặt hàm kích hoạt phi tuyến&lt;/strong&gt; giữa các tầng. Kết quả? Về mặt toán học, cả 100 tầng đó lập tức sụp đổ thành đúng &lt;strong&gt;một phép nhân ma trận duy nhất&lt;/strong&gt;—không mạnh hơn một mô hình hồi quy tuyến tính 1 tầng! Hàm kích hoạt chính là nguồn gốc của tính phi tuyến và khả năng học các ranh giới phức tạp. Mục tổng quan này mở đường cho hai bài chuyên sâu đi từ Sigmoid/Tanh cổ điển đến ReLU, GELU và cuộc chiến chống gradient biến mất.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-vai-trò-của-hàm-kích-hoạt&quot;&gt;Kiến thức cần nhớ: Ba vai trò của Hàm Kích hoạt&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phá vỡ Tính Tuyến tính (Non-linearity)&lt;/strong&gt;:
Nhờ phép hợp \(\mathbf{W}_2 \sigma(\mathbf{W}_1 \mathbf{x})\) không thể gộp thành một ma trận duy nhất, mỗi tầng mới thực sự cộng thêm năng lực uốn cong không gian biểu diễn.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kiểm soát Dòng chảy Gradient (Gradient Flow)&lt;/strong&gt;:
Đạo hàm \(\sigma&apos;(z)\) được nhân liên tiếp qua từng tầng trong lan truyền ngược. Nếu \(\sigma&apos;(z) \ll 1\) (như Sigmoid bão hòa), gradient tắt ngấm; nếu \(\sigma&apos;(z) \approx 1\) (như ReLU trên miền dương), mạng sâu học mượt mà.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Định hình Miền Đầu ra theo Tác vụ (Output Semantics)&lt;/strong&gt;:
Lớp ẩn ưu tiên tốc độ và dòng gradient (ReLU, GELU, SwiGLU), còn lớp đầu ra phải khớp miền xác suất của bài toán: Linear cho hồi quy, Sigmoid cho nhị phân/đa nhãn, và Softmax cho phân loại đa lớp loại trừ.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-chứng-minh-bằng-tay-sự-sụp-đổ-của-mạng-2-tầng-không-có-hàm-kích-hoạt&quot;&gt;Giải thích: Chứng minh bằng tay sự sụp đổ của mạng 2 tầng không có hàm kích hoạt&lt;/h3&gt;

&lt;p&gt;Xét mạng 2 tầng &lt;em&gt;tuyến tính thuần túy&lt;/em&gt; với \(\mathbf{W}_1 = \begin{bmatrix} 1 &amp;amp; 2 \\ 0 &amp;amp; -1 \end{bmatrix}\), \(\mathbf{W}_2 = \begin{bmatrix} 3 &amp;amp; 1 \end{bmatrix}\) (bỏ qua bias cho gọn):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính qua 2 tầng lần lượt&lt;/strong&gt; cho \(\mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \end{bmatrix}\):
    &lt;ul&gt;
      &lt;li&gt;Tầng 1: \(\mathbf{h} = \mathbf{W}_1\mathbf{x} = \begin{bmatrix} x_1 + 2x_2 \\ -x_2 \end{bmatrix}\).&lt;/li&gt;
      &lt;li&gt;Tầng 2: \(y = \mathbf{W}_2\mathbf{h} = 3(x_1 + 2x_2) + 1(-x_2) = 3x_1 + 5x_2\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gộp trực tiếp thành 1 tầng duy nhất&lt;/strong&gt;:
\(\mathbf{W}_{\text{gộp}} = \mathbf{W}_2 \mathbf{W}_1 = \begin{bmatrix} 3 &amp;amp; 1 \end{bmatrix}\begin{bmatrix} 1 &amp;amp; 2 \\ 0 &amp;amp; -1 \end{bmatrix} = \begin{bmatrix} 3 &amp;amp; 5 \end{bmatrix} \implies y = \mathbf{W}_{\text{gộp}}\mathbf{x} = 3x_1 + 5x_2.\)
Dù bạn có chồng thêm 1{,}000 ma trận nữa, tích \(\mathbf{W}_{1000}\cdots\mathbf{W}_1\) vẫn chỉ là &lt;strong&gt;một ma trận tuyến tính đơn độc&lt;/strong&gt;. Chỉ khi chèn hàm phi tuyến \(\sigma(\cdot)\) vào giữa, phép kết hợp mới bị phá vỡ và mạng sâu mới thực sự có ý nghĩa!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Phần này trình bày chi tiết về các hàm kích hoạt (&lt;em&gt;activation functions&lt;/em&gt;):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hàm kích hoạt cổ điển&lt;/strong&gt; — vai trò của hàm kích hoạt, các hàm phổ biến và bảng so sánh&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm kích hoạt hiện đại và gradient biến mất&lt;/strong&gt; — cách lựa chọn hàm kích hoạt, cài đặt và hiện tượng gradient biến mất (&lt;em&gt;vanishing gradients&lt;/em&gt;)&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NkOv_k7r6no&quot;&gt;Why Non-linear Activation Functions (C1W3L07)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Giải thích vì sao thiếu tính phi tuyến sẽ khiến toàn bộ mạng nhiều lớp thu gọn về một phép biến đổi tuyến tính duy nhất.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=68BZ5f7P94E&quot;&gt;Neural Networks Pt. 3: ReLU In Action!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa trực quan ReLU — hàm kích hoạt mặc định được phân tích ở phần đầu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2FaI2Fen1mQ&quot;&gt;The GELU, SiLU and SwiGLU activation functions, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Trình bày các hàm kích hoạt hiện đại được giới thiệu ở phần sau để so sánh với ReLU.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-03-02 Hàm Kích hoạt Hiện đại và Gradient Biến mất</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_03_02_Modern_Activations_and_Vanishing_Gradients/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_03_02_Modern_Activations_and_Vanishing_Gradients</id>
   <content type="html">&lt;p&gt;ReLU đã giải cứu Deep Learning khỏi cơn ác mộng bão hòa của Sigmoid, nhưng nó vẫn để lại hai vết gợn nhỏ: góc gãy không khả vi tại \(0\) và những “nơ-ron chết” (&lt;em&gt;dying ReLU&lt;/em&gt;) không bao giờ tỉnh lại khi bị đẩy sang vùng âm. Để đẩy độ chính xác và độ ổn định lên tầm cao mới cho BERT, GPT, Vision Transformer và Llama, cộng đồng nghiên cứu đã sáng tạo ra thế hệ hàm kích hoạt hiện đại: &lt;strong&gt;Leaky ReLU, ELU, GELU, SiLU (Swish) và SwiGLU&lt;/strong&gt;. Bài học này giúp bạn chọn đúng hàm kích hoạt cho từng tầng và làm chủ toàn bộ bộ công cụ chống gradient biến mất.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-mũi-nhọn-của-hàm-kích-hoạt-hiện-đại-và-chống-gradient-biến-mất&quot;&gt;Kiến thức cần nhớ: Bốn mũi nhọn của Hàm Kích hoạt Hiện đại và Chống Gradient Biến mất&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Họ sửa lỗi Dying ReLU (Leaky ReLU, PReLU, ELU)&lt;/strong&gt;:
Giữ một độ dốc nhỏ \(\alpha &amp;gt; 0\) (thường \(0.01\)) ở miền âm để nơ-ron không bao giờ bị khóa chết hoàn toàn với đạo hàm bằng \(0\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm kích hoạt trơn phi đơn điệu (GELU &amp;amp; SiLU/Swish)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;GELU&lt;/strong&gt; (\(\approx x\Phi(x)\)): nhân đầu vào với xác suất nó lớn hơn nhiễu chuẩn—chuẩn mực trong BERT, GPT-2/3 và ViT.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;SiLU / Swish&lt;/strong&gt; (\(x\cdot \sigma(x)\)) và biến thể cổng nhân &lt;strong&gt;SwiGLU&lt;/strong&gt;: trơn khắp nơi, cho phép một vùng âm nhẹ (không đơn điệu) giúp tối ưu hóa mượt mà hơn trong LLM hiện đại (Llama, PaLM).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Cơ chế Toán học của Vanishing &amp;amp; Exploding Gradients&lt;/strong&gt;:
Trong mạng \(L\) tầng, gradient chứa tích \(\prod_{\ell=1}^L \mathbf{W}^{(\ell)\top}\text{diag}(\sigma&apos;(\mathbf{z}^{(\ell)}))\). Chỉ cần chuẩn phổ trung bình của mỗi thừa số nhỏ hơn \(1\) hoặc lớn hơn \(1\) một chút, tích \(L\) thừa số sẽ tắt dần về \(0\) hoặc vọt lên \(\infty\) theo hàm mũ.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bộ tứ Giải pháp Đồng bộ&lt;/strong&gt;:
Hàm kích hoạt không bão hòa (ReLU/GELU) + Khởi tạo chuẩn (He/Xavier) + Chuẩn hóa (BatchNorm/LayerNorm/RMSNorm) + Kết nối tắt (Residual Connections) + Gradient Clipping.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-giá-trị-và-đạo-hàm-của-leaky-relu-vs-silu-swish-tại-x---1&quot;&gt;Giải thích: Tính tay giá trị và đạo hàm của Leaky ReLU vs. SiLU (Swish) tại \(x = -1\)&lt;/h3&gt;

&lt;p&gt;Hãy đặt lên bàn cân ba hàm kích hoạt tại cùng một điểm âm \(x = -1\) để thấy sự khác biệt về dòng chảy gradient:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;ReLU&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Giá trị: \(\max(0, -1) = 0\).&lt;/li&gt;
      &lt;li&gt;Đạo hàm: \(0\) (tín hiệu học bị cắt đứt hoàn toàn!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Leaky ReLU&lt;/strong&gt; (\(\alpha = 0.05\)):
    &lt;ul&gt;
      &lt;li&gt;Giá trị: \(0.05 \times (-1) = -0.05\).&lt;/li&gt;
      &lt;li&gt;Đạo hàm: \(0.05\) (vẫn duy trì luồng gradient nhỏ để nơ-ron có cơ hội hồi phục).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SiLU / Swish&lt;/strong&gt; (\(f(x) = x\sigma(x)\)):
    &lt;ul&gt;
      &lt;li&gt;Ta có \(\sigma(-1) = \frac{1}{1+e^1} \approx 0.2689\).&lt;/li&gt;
      &lt;li&gt;Giá trị: \(f(-1) = (-1)(0.2689) = -0.2689\).&lt;/li&gt;
      &lt;li&gt;Đạo hàm: \(f&apos;(x) = \sigma(x) + x\sigma(x)(1 - \sigma(x))\). Thay \(x = -1\):
\(f&apos;(-1) = 0.2689 + (-1)(0.2689)(0.7311) = 0.2689 - 0.1966 = +0.0723.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nhìn vào con số \(+0.0723\): khác với ReLU bị “chết phẳng” bằng \(0\), SiLU vẫn truyền được một lượng gradient mượt mà, liên tục ở vùng âm, giúp các mạng Transformer sâu hội tụ ổn định và đạt chất lượng biểu diễn cao hơn.&lt;/p&gt;

&lt;h2 id=&quot;chọn-hàm-kích-hoạt-phù-hợp&quot;&gt;Chọn Hàm Kích hoạt Phù hợp&lt;/h2&gt;

&lt;h3 id=&quot;cho-lớp-ẩn&quot;&gt;Cho Lớp Ẩn&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Lựa chọn mặc định: ReLU&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nên bắt đầu với ReLU cho hầu hết các bài toán&lt;/li&gt;
  &lt;li&gt;Tính toán nhanh và đơn giản&lt;/li&gt;
  &lt;li&gt;Hoạt động ổn định trong thực tế&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Khi gặp hiện tượng ReLU chết:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Thử chuyển sang Leaky ReLU hoặc ELU&lt;/li&gt;
  &lt;li&gt;Kiểm tra lại tốc độ học (&lt;em&gt;learning rate&lt;/em&gt;) và cách khởi tạo trọng số&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Cho các mô hình hiện đại hoặc quy mô lớn:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;GELU thường dùng cho kiến trúc Transformer và NLP&lt;/li&gt;
  &lt;li&gt;Swish thường dùng cho các mô hình thị giác khi ưu tiên độ chính xác&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Cho mạng rất sâu:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Có thể cân nhắc ELU hoặc SELU&lt;/li&gt;
  &lt;li&gt;Thường kết hợp thêm các kỹ thuật chuẩn hóa (sẽ học ở các chương sau)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;cho-lớp-đầu-ra&quot;&gt;Cho Lớp Đầu ra&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phân loại nhị phân:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid:&lt;/strong&gt; Xuất ra xác suất thuộc lớp dương&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phân loại đa lớp:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Softmax:&lt;/strong&gt; Xuất ra phân phối xác suất trên tất cả các lớp&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hồi quy:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tuyến tính (hàm đồng nhất):&lt;/strong&gt; Khi đầu ra không bị giới hạn miền giá trị&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ReLU:&lt;/strong&gt; Khi đầu ra phải không âm (ví dụ: giá cả, số đếm)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid/tanh:&lt;/strong&gt; Khi đầu ra nằm trong một khoảng bị chặn&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phân loại đa nhãn:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid:&lt;/strong&gt; Xuất xác suất độc lập cho từng nhãn&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;triển-khai-thực-tế&quot;&gt;Triển khai Thực tế&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tanh_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;leaky_relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;leaky_relu_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;elu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;elu_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;elu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Ổn định số: trừ max
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;swish&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gelu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Xấp xỉ
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.044715&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ sử dụng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ReLU:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Leaky ReLU:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;leaky_relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sigmoid:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tanh:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;bài-toán-gradient-biến-mất&quot;&gt;Bài toán Gradient Biến mất&lt;/h2&gt;

&lt;h3 id=&quot;vì-sao-điều-này-quan-trọng&quot;&gt;Vì sao Điều này Quan trọng&lt;/h3&gt;

&lt;p&gt;Trong quá trình lan truyền ngược, gradient được tính bằng cách nhân liên tiếp các đạo hàm qua từng lớp:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[1]}} = \frac{\partial \mathcal{L}}{\partial \mathbf{a}^{[L]}} \cdot \frac{\partial \mathbf{a}^{[L]}}{\partial \mathbf{z}^{[L]}} \cdot \ldots \cdot \frac{\partial \mathbf{z}^{[2]}}{\partial \mathbf{a}^{[1]}} \cdot \frac{\partial \mathbf{a}^{[1]}}{\partial \mathbf{z}^{[1]}} \cdot \frac{\partial \mathbf{z}^{[1]}}{\partial \mathbf{W}^{[1]}}\]

&lt;h3 id=&quot;hạn-chế-của-sigmoid-và-tanh&quot;&gt;Hạn chế của Sigmoid và Tanh&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Giá trị đạo hàm cực đại: \(\sigma&apos;(z) = 0.25\) (với sigmoid tại \(z=0\)), \(\tanh&apos;(z) = 1\) (với tanh tại \(z=0\))&lt;/li&gt;
  &lt;li&gt;Đạo hàm thực tế thường nhỏ hơn nhiều (\(&amp;lt; 0.25\) với sigmoid khi \(z \neq 0\))&lt;/li&gt;
  &lt;li&gt;Khi nhân qua nhiều lớp: \(0.25^{10} \approx 9.5 \times 10^{-7}\) (rất nhỏ)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hệ quả:&lt;/strong&gt; Gradient suy giảm nhanh về 0, khiến các lớp đầu gần như không cập nhật được trọng số.&lt;/p&gt;

&lt;h3 id=&quot;vai-trò-của-relu&quot;&gt;Vai trò của ReLU&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Đạo hàm bằng 1 ở miền dương nên không bị suy giảm qua phép nhân&lt;/li&gt;
  &lt;li&gt;Gradient truyền ổn định qua các neuron ReLU đang hoạt động&lt;/li&gt;
  &lt;li&gt;Cho phép huấn luyện các mạng sâu hơn đáng kể&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;hiện-tượng-relu-chết&quot;&gt;Hiện tượng ReLU Chết&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Nếu giá trị \(z &amp;lt; 0\) trên mọi mẫu, đạo hàm luôn bằng 0 và neuron ngừng học&lt;/li&gt;
  &lt;li&gt;Nguyên nhân thường gặp:
    &lt;ul&gt;
      &lt;li&gt;Khởi tạo trọng số chưa hợp lý&lt;/li&gt;
      &lt;li&gt;Tốc độ học quá cao&lt;/li&gt;
      &lt;li&gt;Bước cập nhật lớn đẩy trọng số sang miền âm&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hướng khắc phục:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Dùng Leaky ReLU, ELU hoặc các biến thể tương tự&lt;/li&gt;
  &lt;li&gt;Áp dụng khởi tạo phù hợp (khởi tạo He cho ReLU)&lt;/li&gt;
  &lt;li&gt;Chọn tốc độ học hợp lý&lt;/li&gt;
  &lt;li&gt;Sử dụng batch normalization (trình bày ở chương sau)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hàm kích hoạt&lt;/strong&gt; bổ sung tính phi tuyến, giúp mạng học các mẫu dữ liệu phức tạp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ReLU&lt;/strong&gt; là lựa chọn mặc định cho các lớp ẩn trong hầu hết kiến trúc học sâu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid&lt;/strong&gt; phù hợp cho lớp đầu ra của bài toán phân loại nhị phân.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Softmax&lt;/strong&gt; phù hợp cho lớp đầu ra của bài toán phân loại đa lớp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các hàm kích hoạt hiện đại&lt;/strong&gt; (ELU, Swish, GELU) có thể cải thiện hiệu năng trên nhiều kiến trúc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient biến mất&lt;/strong&gt; là rào cản lớn khi dùng sigmoid hoặc tanh trong mạng sâu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ReLU&lt;/strong&gt; giảm mạnh hiện tượng gradient biến mất nhưng có thể gặp tình trạng ReLU chết.&lt;/li&gt;
  &lt;li&gt;Lựa chọn hàm kích hoạt ảnh hưởng trực tiếp tới tốc độ hội tụ và chất lượng mô hình.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ở bài tiếp theo, ta sẽ tìm hiểu chi tiết quá trình lan truyền xuôi kèm các ví dụ tính toán cụ thể.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=2FaI2Fen1mQ&quot;&gt;The GELU, SiLU and SwiGLU activation functions, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích rõ các hàm kích hoạt hiện đại (GELU, SiLU, SwiGLU) được dùng phổ biến sau ReLU.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qhXZsFVxGKo&quot;&gt;Vanishing/Exploding Gradients (C2W1L10)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Phân tích hiện tượng gradient biến mất và bùng nổ — lý do chính thúc đẩy việc cải tiến hàm kích hoạt.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=68BZ5f7P94E&quot;&gt;Neural Networks Pt. 3: ReLU In Action!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Ôn lại cách hoạt động của ReLU làm cơ sở so sánh với các hàm kích hoạt mới hơn.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-03-01 Hàm Kích hoạt Cổ điển</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_03_01_Classic_Activations/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_03_01_Classic_Activations</id>
   <content type="html">&lt;p&gt;Trong suốt thập niên 1980 và 1990, &lt;strong&gt;Sigmoid&lt;/strong&gt; và &lt;strong&gt;Tanh&lt;/strong&gt; từng là hai vị vua không thể thay thế của mạng nơ-ron: chúng trơn mượt, khả vi ở mọi điểm và nén mọi số thực về một khoảng gọn gàng. Thế nhưng khi các nhà nghiên cứu thử chồng từ 3 tầng lên 10 tầng, cả hai đột ngột khiến quá trình học đóng băng hoàn toàn—và chính cú đột phá chuyển sang &lt;strong&gt;ReLU&lt;/strong&gt; (\(\max(0, x)\)) đã mở toang cánh cửa cho kỷ nguyên Học sâu hiện đại. Bài học này mổ xẻ toán học của Sigmoid, Tanh, ReLU và Softmax để bạn hiểu chính xác điểm mạnh và cái bẫy ẩn giấu trong từng hàm.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-hàm-kích-hoạt-kinh-điển-và-đặc-tính-toán-học&quot;&gt;Kiến thức cần nhớ: Bốn hàm Kích hoạt Kinh điển và đặc tính toán học&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Sigmoid (\(\sigma(z) = \frac{1}{1+e^{-z}}\))&lt;/strong&gt;:
Nén \(\mathbb{R} \to (0, 1)\) với đạo hàm cực gọn \(\sigma&apos;(z) = \sigma(z)(1 - \sigma(z))\). Nhược điểm chí mạng: giá trị đạo hàm cực đại chỉ bằng \(0.25\) tại \(z=0\) và đầu ra luôn dương (&lt;em&gt;not zero-centered&lt;/em&gt;), khiến cập nhật trọng số chạy zig-zag.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tanh (\(\tanh(z) = \frac{e^z - e^{-z}}{e^z + e^{-z}} = 2\sigma(2z) - 1\))&lt;/strong&gt;:
Khắc phục nhược điểm lệch tâm bằng cách nén về \((-1, 1)\) (&lt;em&gt;zero-centered&lt;/em&gt;) và có đạo hàm cực đại bằng \(1\) tại \(z = 0\), nhưng vẫn bị bão hòa (\(\tanh&apos;(z) \to 0\)) khi \(\lvert z \rvert\) lớn.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;ReLU (\(\max(0, z)\))&lt;/strong&gt;:
Đạo hàm bằng đúng \(1\) trên toàn miền dương (triệt tiêu bão hòa phía dương) và tính toán siêu nhanh, nhưng tiềm ẩn hiện tượng &lt;strong&gt;Dying ReLU&lt;/strong&gt; nếu một nơ-ron liên tục nhận \(z &amp;lt; 0\) khiến đạo hàm mãi bằng \(0\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Softmax (\(\text{softmax}(z_i) = \frac{e^{z_i}}{\sum_j e^{z_j}}\))&lt;/strong&gt;:
Biến vector logit bất kỳ thành phân phối xác suất hợp lệ trên \(K\) lớp; luôn trừ \(\max_j z_j\) trước khi lấy mũ (Log-Sum-Exp trick) để tránh tràn số &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Inf/NaN&lt;/code&gt;.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-đạo-hàm-sigmoid-và-bài-toán-tràn-số-softmax&quot;&gt;Giải thích: Tính tay đạo hàm Sigmoid và bài toán tràn số Softmax&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Vì sao 10 tầng Sigmoid giết chết gradient?&lt;/strong&gt;
Tại điểm đẹp nhất \(z = 0\), \(\sigma(0) = 0.5 \implies \sigma&apos;(0) = 0.5 \times (1 - 0.5) = 0.25\).
Nếu tại một nơ-ron bão hòa \(z = 5\), \(\sigma(5) \approx 0.9933 \implies \sigma&apos;(5) \approx 0.9933 \times 0.0067 \approx 0.0066\).
Đi qua 10 tầng Sigmoid ngay cả ở điều kiện &lt;em&gt;lý tưởng nhất&lt;/em&gt; (\(z = 0\)):
\((0.25)^{10} = \frac{1}{4^{10}} = \frac{1}{1{,}048{,}576} \approx 9.5 \times 10^{-7}!\)
Gradient đã co rút đi &lt;strong&gt;hơn một triệu lần&lt;/strong&gt; trước khi chạm tới tầng đầu tiên!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Thủ thuật chống tràn số của Softmax:&lt;/strong&gt;
Xét vector logit \(\mathbf{z} = [1000, 1001, 999]\). Nếu tính trực tiếp \(e^{1000}\), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt; lập tức tràn ra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Inf&lt;/code&gt; và chia ra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;.
Nhờ tính bất biến tịnh tiến, ta trừ đi \(\max(\mathbf{z}) = 1001\):
\(\mathbf{z}&apos; = [-1, 0, -2] \implies e^{\mathbf{z}&apos;} \approx [0.3679,\; 1.0000,\; 0.1353], \quad \text{Tổng} \approx 1.5032.\)
Chia cho tổng ta được xác suất hoàn hảo: \([0.2447,\; 0.6652,\; 0.0900]\) (tổng = \(1.0000\)), hoàn toàn không tràn số!&lt;/p&gt;

&lt;p&gt;Bài này phân tích chi tiết các hàm kích hoạt (&lt;em&gt;activation functions&lt;/em&gt;), đặc tính toán học của chúng và cách lựa chọn hàm phù hợp cho mạng neuron.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;vì-sao-hàm-kích-hoạt-quan-trọng&quot;&gt;Vì sao Hàm Kích hoạt Quan trọng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Nếu không có hàm kích hoạt&lt;/strong&gt;, mạng neuron chỉ có thể biểu diễn các phép biến đổi tuyến tính. Dù xếp chồng bao nhiêu lớp, hợp thành của nhiều hàm tuyến tính vẫn chỉ là một hàm tuyến tính duy nhất:&lt;/p&gt;

\[f(g(h(\mathbf{x}))) = \mathbf{A}_1(\mathbf{A}_2(\mathbf{A}_3 \mathbf{x})) = (\mathbf{A}_1 \mathbf{A}_2 \mathbf{A}_3)\mathbf{x} = \mathbf{A}\mathbf{x}\]

&lt;p&gt;&lt;strong&gt;Hàm kích hoạt bổ sung tính phi tuyến&lt;/strong&gt;, giúp mạng học được các mẫu phức tạp và xấp xỉ nhiều lớp hàm khác nhau.&lt;/p&gt;

&lt;h2 id=&quot;các-tính-chất-mong-muốn-của-hàm-kích-hoạt&quot;&gt;Các Tính chất Mong muốn của Hàm Kích hoạt&lt;/h2&gt;

&lt;p&gt;Một hàm kích hoạt tốt thường hướng tới các tính chất sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phi tuyến:&lt;/strong&gt; Cho phép mạng học các mối quan hệ phức tạp&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khả vi:&lt;/strong&gt; Hỗ trợ tối ưu hóa dựa trên gradient&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đơn điệu:&lt;/strong&gt; Bảo toàn thứ tự đầu vào (thuận lợi cho quá trình tối ưu)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính toán hiệu quả:&lt;/strong&gt; Thực thi nhanh ở cả lượt xuôi và lượt ngược&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Miền giá trị phù hợp:&lt;/strong&gt; Bị chặn hoặc không bị chặn tùy theo yêu cầu bài toán&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đối xứng quanh 0 (&lt;em&gt;zero-centered&lt;/em&gt;):&lt;/strong&gt; Giúp luồng gradient ổn định hơn ở các lớp ẩn&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hạn chế bão hòa:&lt;/strong&gt; Tránh hiện tượng gradient biến mất&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Không có hàm kích hoạt nào thỏa mãn đồng thời mọi tiêu chí ở mức tối ưu, nên việc lựa chọn cần căn cứ vào từng bài toán và kiến trúc cụ thể.&lt;/p&gt;

&lt;h2 id=&quot;các-hàm-kích-hoạt-phổ-biến&quot;&gt;Các Hàm Kích hoạt Phổ biến&lt;/h2&gt;

&lt;h3 id=&quot;1-sigmoid-hàm-logistic&quot;&gt;1. Sigmoid (Hàm Logistic)&lt;/h3&gt;

\[\sigma(z) = \frac{1}{1 + e^{-z}}\]

&lt;p&gt;&lt;strong&gt;Đạo hàm:&lt;/strong&gt;&lt;/p&gt;

\[\sigma&apos;(z) = \sigma(z)(1 - \sigma(z))\]

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Miền giá trị: \((0, 1)\)&lt;/li&gt;
  &lt;li&gt;Trơn và khả vi tại mọi điểm&lt;/li&gt;
  &lt;li&gt;Đơn điệu tăng&lt;/li&gt;
  &lt;li&gt;Bão hòa ở cả hai phía&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Dễ diễn giải dưới dạng xác suất&lt;/li&gt;
  &lt;li&gt;Gradient biến thiên mượt&lt;/li&gt;
  &lt;li&gt;Được sử dụng rộng rãi trong giai đoạn đầu của mạng neuron&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Gradient biến mất:&lt;/strong&gt; Đạo hàm rất gần 0 khi $$&lt;/td&gt;
          &lt;td&gt;z&lt;/td&gt;
          &lt;td&gt;&amp;gt; 4$$&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không đối xứng quanh 0:&lt;/strong&gt; Đầu ra luôn dương&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chi phí tính toán cao:&lt;/strong&gt; Cần tính hàm mũ&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Lớp đầu ra cho bài toán phân loại nhị phân&lt;/li&gt;
  &lt;li&gt;Các cổng điều khiển trong LSTM&lt;/li&gt;
  &lt;li&gt;Thường tránh dùng ở lớp ẩn của mạng sâu&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-tang-hyperbolic-tanh&quot;&gt;2. Tang Hyperbolic (tanh)&lt;/h3&gt;

\[\tanh(z) = \frac{e^z - e^{-z}}{e^z + e^{-z}} = \frac{e^{2z} - 1}{e^{2z} + 1} = 2\sigma(2z) - 1\]

&lt;p&gt;&lt;strong&gt;Đạo hàm:&lt;/strong&gt;&lt;/p&gt;

\[\tanh&apos;(z) = 1 - \tanh^2(z)\]

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Miền giá trị: \((-1, 1)\)&lt;/li&gt;
  &lt;li&gt;Đối xứng quanh 0 (cải thiện so với sigmoid)&lt;/li&gt;
  &lt;li&gt;Bão hòa ở cả hai phía&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đối xứng quanh 0, hỗ trợ luồng gradient tốt hơn&lt;/li&gt;
  &lt;li&gt;Đạo hàm lớn hơn sigmoid (nhận giá trị trong \((0, 1]\))&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Vẫn gặp hiện tượng gradient biến mất ở hai đầu bão hòa&lt;/li&gt;
  &lt;li&gt;Tốn chi phí tính toán hàm mũ&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Lớp ẩn (tốt hơn sigmoid nhưng thường kém hiệu quả hơn ReLU)&lt;/li&gt;
  &lt;li&gt;Các ô nhớ trong RNN/LSTM&lt;/li&gt;
  &lt;li&gt;Những bài toán cần đầu ra đối xứng quanh 0&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-rectified-linear-unit-relu&quot;&gt;3. Rectified Linear Unit (ReLU)&lt;/h3&gt;

\[\text{ReLU}(z) = \max(0, z) = \begin{cases} z &amp;amp; \text{if } z &amp;gt; 0 \\ 0 &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/relu_function.jpg&quot; alt=&quot;Đồ thị hàm ReLU&quot; /&gt;
&lt;em&gt;Hình: \(\mathrm{ReLU}(x)=\max(0,x)=(x)^+\) — bằng \(0\) với \(x&amp;lt;0\) và bằng \(x\) với \(x\geq 0\). (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm:&lt;/strong&gt;&lt;/p&gt;

\[\text{ReLU}&apos;(z) = \begin{cases} 1 &amp;amp; \text{if } z &amp;gt; 0 \\ 0 &amp;amp; \text{if } z &amp;lt; 0 \\ \text{undefined} &amp;amp; \text{if } z = 0 \end{cases}\]

&lt;p&gt;(Trong thực tế cài đặt, ta thường quy ước \(\text{ReLU}&apos;(0) = 0\) hoặc \(0.5\).)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Miền giá trị: \([0, \infty)\)&lt;/li&gt;
  &lt;li&gt;Không bị bão hòa với đầu vào dương&lt;/li&gt;
  &lt;li&gt;Tạo kích hoạt thưa (nhiều neuron xuất giá trị 0)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tính toán rất nhanh:&lt;/strong&gt; Chỉ cần so sánh ngưỡng tại 0&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giảm gradient biến mất:&lt;/strong&gt; Đạo hàm bằng 1 trên toàn miền dương&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biểu diễn thưa:&lt;/strong&gt; Tự nhiên đưa nhiều kích hoạt về 0&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu quả thực nghiệm cao:&lt;/strong&gt; Hoạt động ổn định trong phần lớn mô hình&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Không đối xứng quanh 0:&lt;/strong&gt; Đầu ra luôn không âm&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiện tượng ReLU chết&lt;/strong&gt; (&lt;em&gt;dying ReLU&lt;/em&gt;): Neuron có thể ngừng hoạt động vĩnh viễn
    &lt;ul&gt;
      &lt;li&gt;Nếu \(z &amp;lt; 0\) trên mọi mẫu, đạo hàm luôn bằng 0 nên trọng số không cập nhật&lt;/li&gt;
      &lt;li&gt;Thường xảy ra khi tốc độ học quá lớn hoặc khởi tạo chưa phù hợp&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lựa chọn mặc định&lt;/strong&gt; cho lớp ẩn trong mạng sâu&lt;/li&gt;
  &lt;li&gt;CNN, ResNet và phần lớn các kiến trúc tiêu chuẩn&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-leaky-relu&quot;&gt;4. Leaky ReLU&lt;/h3&gt;

\[\text{LeakyReLU}(z) = \begin{cases} z &amp;amp; \text{if } z &amp;gt; 0 \\ \alpha z &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;trong đó \(\alpha\) là một hằng số dương nhỏ (thường chọn 0.01).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm:&lt;/strong&gt;&lt;/p&gt;

\[\text{LeakyReLU}&apos;(z) = \begin{cases} 1 &amp;amp; \text{if } z &amp;gt; 0 \\ \alpha &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Khắc phục ReLU chết:&lt;/strong&gt; Vẫn duy trì đạo hàm nhỏ ở miền âm&lt;/li&gt;
  &lt;li&gt;Tính toán đơn giản và nhanh&lt;/li&gt;
  &lt;li&gt;Giữ được các ưu điểm chính của ReLU&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Xuất hiện thêm siêu tham số \(\alpha\)&lt;/li&gt;
  &lt;li&gt;Không phải lúc nào cũng cải thiện rõ rệt so với ReLU trong thực tế&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Các biến thể:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Parametric ReLU (PReLU):&lt;/strong&gt; Hệ số \(\alpha\) được học trực tiếp trong quá trình huấn luyện&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Randomized Leaky ReLU (RReLU):&lt;/strong&gt; Hệ số \(\alpha\) được lấy mẫu ngẫu nhiên trong khi huấn luyện&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;5-exponential-linear-unit-elu&quot;&gt;5. Exponential Linear Unit (ELU)&lt;/h3&gt;

\[\text{ELU}(z) = \begin{cases} z &amp;amp; \text{if } z &amp;gt; 0 \\ \alpha(e^z - 1) &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;trong đó \(\alpha &amp;gt; 0\) (thường chọn \(\alpha = 1\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm:&lt;/strong&gt;&lt;/p&gt;

\[\text{ELU}&apos;(z) = \begin{cases} 1 &amp;amp; \text{if } z &amp;gt; 0 \\ \alpha e^z = \text{ELU}(z) + \alpha &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Trơn tại mọi điểm (khi \(\alpha = 1\))&lt;/li&gt;
  &lt;li&gt;Cho phép giá trị âm giúp kéo trung bình kích hoạt về gần 0 hơn&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Gần đối xứng quanh 0 hơn:&lt;/strong&gt; Có đầu ra âm ở miền \(z &amp;lt; 0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tránh ReLU chết:&lt;/strong&gt; Gradient khác 0 với mọi đầu vào&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trơn:&lt;/strong&gt; Giúp bề mặt tối ưu mượt hơn&lt;/li&gt;
  &lt;li&gt;Thường giúp hội tụ nhanh và ổn định hơn&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chi phí tính toán cao hơn ReLU do có hàm mũ&lt;/li&gt;
  &lt;li&gt;Thêm siêu tham số \(\alpha\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Thay thế ReLU khi chấp nhận chi phí tính toán cao hơn một chút&lt;/li&gt;
  &lt;li&gt;Các bài toán hưởng lợi từ kích hoạt có trung bình gần 0&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;6-scaled-exponential-linear-unit-selu&quot;&gt;6. Scaled Exponential Linear Unit (SELU)&lt;/h3&gt;

\[\text{SELU}(z) = \lambda \begin{cases} z &amp;amp; \text{if } z &amp;gt; 0 \\ \alpha(e^z - 1) &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;trong đó \(\lambda \approx 1.0507\) và \(\alpha \approx 1.6733\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tự chuẩn hóa&lt;/strong&gt; (&lt;em&gt;self-normalizing&lt;/em&gt;): Dưới các điều kiện nhất định, kích hoạt tự hội tụ về trung bình 0 và phương sai 1&lt;/li&gt;
  &lt;li&gt;Đòi hỏi phương pháp khởi tạo tương thích (LeCun normal)&lt;/li&gt;
  &lt;li&gt;Thiết kế cho kiến trúc nhất định (chủ yếu các lớp liên kết đầy đủ)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Có thể huấn luyện mạng rất sâu mà không cần batch normalization&lt;/li&gt;
  &lt;li&gt;Có cơ sở lý thuyết rõ ràng về tính hội tụ phân phối&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Điều kiện áp dụng khá chặt chẽ về kiến trúc mạng&lt;/li&gt;
  &lt;li&gt;Ít được sử dụng rộng rãi bằng ReLU hay GELU&lt;/li&gt;
  &lt;li&gt;Không tương thích tốt với dropout tiêu chuẩn hoặc lớp tích chập&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;7-swish-silu--sigmoid-linear-unit&quot;&gt;7. Swish (SiLU — Sigmoid Linear Unit)&lt;/h3&gt;

\[\text{Swish}(z) = z \cdot \sigma(z) = \frac{z}{1 + e^{-z}}\]

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Trơn, không đơn điệu&lt;/li&gt;
  &lt;li&gt;Không bị chặn trên, bị chặn dưới&lt;/li&gt;
  &lt;li&gt;Tự đóng cổng (&lt;em&gt;self-gated&lt;/em&gt;): đầu vào được điều chỉnh trọng số bởi chính giá trị sigmoid của nó&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu năng tốt:&lt;/strong&gt; Thực nghiệm cho thấy thường vượt ReLU trên nhiều bài toán sâu&lt;/li&gt;
  &lt;li&gt;Gradient trơn&lt;/li&gt;
  &lt;li&gt;Tính không đơn điệu đôi khi giúp tối ưu tốt hơn&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tốn tính toán hơn ReLU&lt;/li&gt;
  &lt;li&gt;Cần điều chỉnh siêu tham số cẩn thận&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Các kiến trúc hiện đại (ví dụ EfficientNet sử dụng Swish)&lt;/li&gt;
  &lt;li&gt;Khi độ chính xác quan trọng hơn chi phí tính toán tăng thêm&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;8-gelu-gaussian-error-linear-unit&quot;&gt;8. GELU (Gaussian Error Linear Unit)&lt;/h3&gt;

\[\text{GELU}(z) = z \cdot \Phi(z)\]

&lt;p&gt;trong đó \(\Phi(z)\) là hàm phân phối tích lũy của phân phối chuẩn tắc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Công thức xấp xỉ:&lt;/strong&gt;&lt;/p&gt;

\[\text{GELU}(z) \approx 0.5z\left(1 + \tanh\left(\sqrt{\frac{2}{\pi}}(z + 0.044715z^3)\right)\right)\]

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Trơn, không đơn điệu&lt;/li&gt;
  &lt;li&gt;Có thể diễn giải như một cơ chế chính quy hóa ngẫu nhiên theo độ lớn đầu vào&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu năng cao trong thực tế:&lt;/strong&gt; Được sử dụng phổ biến trong BERT, GPT&lt;/li&gt;
  &lt;li&gt;Trơn tại mọi điểm&lt;/li&gt;
  &lt;li&gt;Mang ý tưởng gần với dropout và zoneout ở dạng tất định&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chi phí tính toán cao&lt;/li&gt;
  &lt;li&gt;Kém trực quan hơn ReLU&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Các mô hình Transformer:&lt;/strong&gt; BERT, GPT-2, GPT-3&lt;/li&gt;
  &lt;li&gt;Các tác vụ xử lý ngôn ngữ tự nhiên (NLP)&lt;/li&gt;
  &lt;li&gt;Các mô hình quy mô lớn hiện đại&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;9-softmax-lớp-đầu-ra&quot;&gt;9. Softmax (Lớp Đầu ra)&lt;/h3&gt;

\[\text{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}}\]

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chuyển vector logits thành một phân phối xác suất&lt;/li&gt;
  &lt;li&gt;Miền đầu ra: \((0, 1)\) với \(\sum_i p_i = 1\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm (của đầu ra lớp \(i\) theo \(z_j\)):&lt;/strong&gt;&lt;/p&gt;

\[\frac{\partial \text{softmax}(\mathbf{z})_i}{\partial z_j} = \begin{cases} \text{softmax}(\mathbf{z})_i(1 - \text{softmax}(\mathbf{z})_i) &amp;amp; \text{if } i = j \\ -\text{softmax}(\mathbf{z})_i \cdot \text{softmax}(\mathbf{z})_j &amp;amp; \text{if } i \neq j \end{cases}\]

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Lớp đầu ra cho &lt;strong&gt;phân loại đa lớp&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;Cơ chế attention&lt;/li&gt;
  &lt;li&gt;Mọi tình huống cần tạo phân phối xác suất trên các lớp&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;10-softplus&quot;&gt;10. Softplus&lt;/h3&gt;

\[\text{softplus}(z) = \ln(1 + e^z)\]

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Là bản xấp xỉ trơn của ReLU&lt;/li&gt;
  &lt;li&gt;Đầu ra luôn dương&lt;/li&gt;
  &lt;li&gt;Tiệm cận ReLU khi \(z\) lớn&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm:&lt;/strong&gt;&lt;/p&gt;

\[\text{softplus}&apos;(z) = \frac{e^z}{1 + e^z} = \sigma(z)\]

&lt;p&gt;&lt;strong&gt;Trường hợp sử dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đôi khi dùng ở lớp ẩn&lt;/li&gt;
  &lt;li&gt;Các mô hình sinh khi cần đảm bảo đầu ra luôn dương&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;bảng-so-sánh-tóm-tắt&quot;&gt;Bảng So sánh Tóm tắt&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Kích hoạt&lt;/th&gt;
      &lt;th&gt;Miền&lt;/th&gt;
      &lt;th&gt;Đối xứng quanh 0&lt;/th&gt;
      &lt;th&gt;Gradient biến mất&lt;/th&gt;
      &lt;th&gt;Đơn vị chết&lt;/th&gt;
      &lt;th&gt;Chi phí tính toán&lt;/th&gt;
      &lt;th&gt;Cách dùng phổ biến&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Sigmoid&lt;/td&gt;
      &lt;td&gt;(0,1)&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Có&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Cao&lt;/td&gt;
      &lt;td&gt;Đầu ra (nhị phân)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;tanh&lt;/td&gt;
      &lt;td&gt;(-1,1)&lt;/td&gt;
      &lt;td&gt;Có&lt;/td&gt;
      &lt;td&gt;Có&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Cao&lt;/td&gt;
      &lt;td&gt;Ẩn (cũ), RNN&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ReLU&lt;/td&gt;
      &lt;td&gt;[0,∞)&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không (với z&amp;gt;0)&lt;/td&gt;
      &lt;td&gt;Có&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Thấp&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Ẩn (mặc định)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Leaky ReLU&lt;/td&gt;
      &lt;td&gt;(-∞,∞)&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Thấp&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Ẩn&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ELU&lt;/td&gt;
      &lt;td&gt;(-α,∞)&lt;/td&gt;
      &lt;td&gt;Gần có&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Trung bình&lt;/td&gt;
      &lt;td&gt;Ẩn&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;SELU&lt;/td&gt;
      &lt;td&gt;(-λα,∞)&lt;/td&gt;
      &lt;td&gt;Có (tự chuẩn hóa)&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Trung bình&lt;/td&gt;
      &lt;td&gt;Ẩn (kiến trúc cụ thể)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Swish&lt;/td&gt;
      &lt;td&gt;(-∞,∞)&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Trung bình&lt;/td&gt;
      &lt;td&gt;Ẩn (hiện đại)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;GELU&lt;/td&gt;
      &lt;td&gt;(-∞,∞)&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Cao&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Transformer&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Softmax&lt;/td&gt;
      &lt;td&gt;(0,1)&lt;/td&gt;
      &lt;td&gt;N/A&lt;/td&gt;
      &lt;td&gt;Có&lt;/td&gt;
      &lt;td&gt;Không&lt;/td&gt;
      &lt;td&gt;Cao&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Đầu ra (đa lớp)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ video của Machine Learning Thực Chiến:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/793200140509765&quot;&gt;Trực giác mạng nơ-ron (Perceptron → Deep Learning)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NkOv_k7r6no&quot;&gt;Why Non-linear Activation Functions (C1W3L07)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Giải thích các tính chất cần có của một hàm kích hoạt phi tuyến.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=68BZ5f7P94E&quot;&gt;Neural Networks Pt. 3: ReLU In Action!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa ReLU qua một lượt lan truyền xuôi bằng số cụ thể.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KpKog-L9veg&quot;&gt;Neural Networks Part 5: ArgMax and SoftMax&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích Softmax — hàm kích hoạt đầu ra dùng cho bài toán phân loại đa lớp.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-02 Kiến trúc Mạng Neuron</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_02_Neural_Network_Architecture/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_02_Neural_Network_Architecture</id>
   <content type="html">&lt;p&gt;Một viên gạch riêng lẻ không thể che nắng mưa, nhưng biết cách xếp gạch thành vòm, cột và mái sẽ tạo nên một tòa nhà vững chãi. Mạng nơ-ron cũng vậy: từ cùng một loại nơ-ron đơn giản, cách bạn tổ chức số tầng (&lt;em&gt;depth&lt;/em&gt;), số nơ-ron mỗi tầng (&lt;em&gt;width&lt;/em&gt;), kiểu kết nối (&lt;em&gt;dense&lt;/em&gt;, &lt;em&gt;residual&lt;/em&gt;, &lt;em&gt;bottleneck&lt;/em&gt;) sẽ quyết định liệu mạng có thể học được bài toán phức tạp hay bị kẹt cứng khi huấn luyện. Mục tổng quan này mở đầu hai bài chuyên sâu về lý thuyết kiến trúc và nghệ thuật cân bằng độ sâu—độ rộng.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-của-thiết-kế-kiến-trúc-mạng-nơ-ron&quot;&gt;Kiến thức cần nhớ: Ba trụ cột của Thiết kế Kiến trúc Mạng Nơ-ron&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lớp vào, Lớp ẩn và Lớp ra (Input, Hidden, Output Layers)&lt;/strong&gt;:
Lớp vào giữ biểu diễn thô, các lớp ẩn đóng vai trò “xưởng chế biến” liên tục uốn cong không gian dữ liệu để các lớp bị trộn lẫn trở nên tách rời tuyến tính, còn lớp ra chiếu về đúng định dạng bài toán.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Định lý Xấp xỉ Phổ quát (Universal Approximation Theorem)&lt;/strong&gt;:
Khẳng định một mạng chỉ có 1 lớp ẩn phi tuyến đủ rộng có thể xấp xỉ &lt;em&gt;mọi&lt;/em&gt; hàm liên tục trên tập compact với sai số nhỏ tùy ý—nhưng cái giá về số nơ-ron có thể phình to theo hàm mũ.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đánh đổi Độ sâu vs. Độ rộng và Mẫu Thiết kế Thực chiến&lt;/strong&gt;:
Mạng sâu hiệu quả tham số hơn nhờ tái sử dụng đặc trưng phân cấp, nhưng khó huấn luyện hơn nếu thiếu khởi tạo chuẩn, chuẩn hóa tầng (Norm) và kết nối tắt (Skip/Residual Connections).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-tay-số-tham-số-của-mạng-nông-rộng-vs-mạng-sâu-hẹp&quot;&gt;Giải thích: So sánh tay số tham số của mạng Nông-Rộng vs. mạng Sâu-Hẹp&lt;/h3&gt;

&lt;p&gt;Xét một bài toán nhận đầu vào \(d_{\text{in}} = 100\) chiều và dự đoán \(d_{\text{out}} = 10\) lớp:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mạng Nông–Rộng&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;100 -&amp;gt; 512 -&amp;gt; 10&lt;/code&gt;):
    &lt;ul&gt;
      &lt;li&gt;Lớp 1: \(100 \times 512 + 512 = 51{,}712\) tham số.&lt;/li&gt;
      &lt;li&gt;Lớp 2: \(512 \times 10 + 10 = 5{,}130\) tham số.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tổng&lt;/strong&gt;: \(56{,}842\) tham số (chỉ 1 lần uốn phi tuyến).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mạng Sâu–Hẹp&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;100 -&amp;gt; 128 -&amp;gt; 128 -&amp;gt; 128 -&amp;gt; 10&lt;/code&gt;):
    &lt;ul&gt;
      &lt;li&gt;Lớp 1: \(100 \times 128 + 128 = 12{,}928\).&lt;/li&gt;
      &lt;li&gt;Lớp 2 &amp;amp; 3: \(2 \times (128 \times 128 + 128) = 33{,}024\).&lt;/li&gt;
      &lt;li&gt;Lớp 4: \(128 \times 10 + 10 = 1{,}290\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tổng&lt;/strong&gt;: \(47{,}242\) tham số—&lt;strong&gt;ít hơn 17% tham số&lt;/strong&gt; nhưng có tới &lt;strong&gt;3 tầng biến đổi phi tuyến liên tiếp&lt;/strong&gt;, giúp biểu diễn các ranh giới quyết định phức tạp mượt mà hơn nhiều!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Phần này trình bày kiến trúc mạng neuron, từ một neuron đơn lẻ đến các hệ thống nhiều lớp:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết kiến trúc&lt;/strong&gt; — tổng quan khái niệm, nền tảng toán học và trực giác&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ sâu, độ rộng và mẫu thiết kế&lt;/strong&gt; — các lựa chọn thiết kế, cách biểu diễn, cài đặt và những lưu ý thực tế&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Trình bày độ sâu dưới góc nhìn chuỗi các hàm hợp được học từ dữ liệu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=CqOfi41LfDw&quot;&gt;The Essential Main Ideas of Neural Networks&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa trực quan vai trò của độ rộng: thêm neuron ẩn giúp đường cong xấp xỉ linh hoạt hơn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 4&lt;/td&gt;
          &lt;td&gt;Introduction to Neural Networks](https://www.youtube.com/watch?v=d14TUNcbn1k) — Stanford University School of Engineering, tiếng Anh. Giới thiệu tổng quan kiến trúc mạng liên kết đầy đủ trước khi các chương sau chuyển sang các kiểu kết nối chuyên biệt hơn.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-02-02 Độ sâu, Độ rộng và Mẫu Thiết kế</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_02_02_Depth_Width_and_Design/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_02_02_Depth_Width_and_Design</id>
   <content type="html">&lt;p&gt;Nếu Định lý Xấp xỉ Phổ quát khẳng định chỉ &lt;strong&gt;một tầng ẩn duy nhất&lt;/strong&gt; là đủ để xấp xỉ mọi hàm liên tục, vậy tại sao các kiến trúc hiện đại như ResNet hay Llama lại chồng tới 50, 100 thậm chí hơn 100 tầng sâu? Khoảng cách giữa &lt;em&gt;“tồn tại trên lý thuyết”&lt;/em&gt; và &lt;em&gt;“học được thực tế với chi phí hữu hạn”&lt;/em&gt; chính là bí mật của nghệ thuật thiết kế kiến trúc. Bài học này phân tích sâu sự đánh đổi giữa &lt;strong&gt;độ sâu&lt;/strong&gt; (&lt;em&gt;depth&lt;/em&gt;) và &lt;strong&gt;độ rộng&lt;/strong&gt; (&lt;em&gt;width&lt;/em&gt;), giới thiệu các mẫu thiết kế kinh điển như thắt cổ chai (&lt;em&gt;bottleneck&lt;/em&gt;), hình phễu (&lt;em&gt;pyramid&lt;/em&gt;) và kết nối tắt (&lt;em&gt;skip connections&lt;/em&gt;).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nguyên-lý-thiết-kế-độ-sâu-độ-rộng-và-mẫu-kiến-trúc&quot;&gt;Kiến thức cần nhớ: Bốn nguyên lý Thiết kế Độ sâu, Độ rộng và Mẫu Kiến trúc&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Định lý Xấp xỉ Phổ quát vs. Hiệu quả Độ sâu (Expressivity vs. Efficiency)&lt;/strong&gt;:
Mạng 1 tầng ẩn có thể cần số nơ-ron cỡ \(O(2^d)\) để biểu diễn một hàm có cấu trúc phân cấp, trong khi mạng sâu chỉ cần \(O(d)\) nơ-ron nhờ tính hợp hàm lặp lại.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Bệnh lý của Mạng quá sâu (Degradation Problem)&lt;/strong&gt;:
Trước khi có Residual Connection (2015), một mạng 56 tầng thậm chí có &lt;em&gt;train error&lt;/em&gt; cao hơn mạng 20 tầng—không phải vì overfitting mà vì tối ưu hóa một chuỗi dài các ánh xạ đồng nhất cực kỳ khó khăn.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các Mẫu Thiết kế Kiến trúc Kinh điển (Design Patterns)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Hình phễu (Funnel/Pyramid)&lt;/strong&gt;: Giảm dần chiều (ví dụ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;512 -&amp;gt; 256 -&amp;gt; 128 -&amp;gt; 10&lt;/code&gt;) để nén thông tin thành quyết định cô đọng.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Thắt cổ chai (Bottleneck / Autoencoder)&lt;/strong&gt;: Ép qua chiều nhỏ rồi mở rộng lại (như &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;256 -&amp;gt; 64 -&amp;gt; 256&lt;/code&gt; trong ResNet) để giảm FLOPs mà giữ dung lượng.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Kết nối tắt (Residual \(\mathbf{y} = \mathbf{x} + F(\mathbf{x})\))&lt;/strong&gt;: Tạo “đường cao tốc” cho cả tín hiệu lẫn gradient đi thẳng qua mạng sâu.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy tắc Thực chiến khi Chọn Kích thước Mạng&lt;/strong&gt;:
Bắt đầu từ kiến trúc gọn, kiểm chứng khả năng overfit dữ liệu huấn luyện trước, sau đó mới mở rộng độ sâu/độ rộng kết hợp Regularization và Normalization.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-mức-tiết-kiệm-flops-của-khối-bottleneck-so-với-khối-phẳng&quot;&gt;Giải thích: Tính tay mức tiết kiệm FLOPs của khối Bottleneck so với khối Phẳng&lt;/h3&gt;

&lt;p&gt;Giả sử bạn cần xử lý một vector đặc trưng 256 chiều đi qua hai lớp liên tiếp và trả về 256 chiều:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Khối Phẳng (Standard 2-layer block: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;256 -&amp;gt; 256 -&amp;gt; 256&lt;/code&gt;)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Số trọng số lớp 1: \(256 \times 256 = 65{,}536\).&lt;/li&gt;
      &lt;li&gt;Số trọng số lớp 2: \(256 \times 256 = 65{,}536\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tổng trọng số&lt;/strong&gt;: \(131{,}072\) tham số.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khối Thắt cổ chai (Bottleneck block: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;256 -&amp;gt; 64 -&amp;gt; 256&lt;/code&gt;)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Nén chiều (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;256 -&amp;gt; 64&lt;/code&gt;): \(256 \times 64 = 16{,}384\).&lt;/li&gt;
      &lt;li&gt;Mở rộng lại (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;64 -&amp;gt; 256&lt;/code&gt;): \(64 \times 256 = 16{,}384\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tổng trọng số&lt;/strong&gt;: \(32{,}768\) tham số.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh&lt;/strong&gt;: Khối Bottleneck cắt giảm đúng &lt;strong&gt;4 lần&lt;/strong&gt; (75%) số tham số và chi phí nhân ma trận! Khi xếp 50 khối như vậy trong một mạng sâu, đây chính là bí quyết giúp các kiến trúc hiện đại vừa cực sâu vừa chạy kịp thời gian thực.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;độ-sâu-và-độ-rộng-của-mạng&quot;&gt;Độ sâu và Độ rộng của Mạng&lt;/h2&gt;

&lt;h3 id=&quot;độ-rộng&quot;&gt;Độ rộng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Độ rộng&lt;/strong&gt; (&lt;em&gt;width&lt;/em&gt;) của một lớp là số lượng neuron nằm trong lớp đó.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mạng rộng hơn&lt;/strong&gt; (nhiều neuron hơn ở mỗi lớp):
    &lt;ul&gt;
      &lt;li&gt;Tăng khả năng học các mẫu phức tạp ngay trong một lớp&lt;/li&gt;
      &lt;li&gt;Tăng số lượng tham số, từ đó dễ dẫn đến quá khớp (&lt;em&gt;overfitting&lt;/em&gt;) nếu dữ liệu ít&lt;/li&gt;
      &lt;li&gt;Tăng chi phí tính toán trên mỗi lớp&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;độ-sâu&quot;&gt;Độ sâu&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Độ sâu&lt;/strong&gt; (&lt;em&gt;depth&lt;/em&gt;) của mạng là số lượng lớp trong mạng.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mạng sâu hơn&lt;/strong&gt; (nhiều lớp hơn):
    &lt;ul&gt;
      &lt;li&gt;Có khả năng học các biểu diễn phân cấp (&lt;em&gt;hierarchical representations&lt;/em&gt;)&lt;/li&gt;
      &lt;li&gt;Nâng cao sức biểu đạt để mô hình hóa các hàm phức tạp hơn&lt;/li&gt;
      &lt;li&gt;Có thể khó huấn luyện hơn do hiện tượng gradient biến mất hoặc bùng nổ (&lt;em&gt;vanishing/exploding gradients&lt;/em&gt;)&lt;/li&gt;
      &lt;li&gt;Thuật ngữ “học sâu” (&lt;em&gt;deep learning&lt;/em&gt;) cũng xuất phát từ việc sử dụng mạng nhiều lớp&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;định-lý-xấp-xỉ-phổ-quát&quot;&gt;Định lý Xấp xỉ Phổ quát&lt;/h3&gt;

&lt;div class=&quot;textbook-theorem&quot;&gt;
  &lt;p&gt;&lt;strong&gt;Định lý&lt;/strong&gt;: Một mạng neuron truyền thẳng (&lt;em&gt;feedforward&lt;/em&gt;) với:&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;Một lớp ẩn duy nhất&lt;/li&gt;
    &lt;li&gt;Số lượng neuron hữu hạn&lt;/li&gt;
    &lt;li&gt;Hàm kích hoạt thích hợp (ví dụ: sigmoid, ReLU)&lt;/li&gt;
  &lt;/ul&gt;

  &lt;p&gt;có thể xấp xỉ bất kỳ hàm liên tục nào trên một tập compact của \(\mathbb{R}^n\) với độ chính xác tùy ý.&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Lưu ý quan trọng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đây là &lt;strong&gt;định lý tồn tại&lt;/strong&gt;, không phải công thức hướng dẫn thiết kế thực tế&lt;/li&gt;
  &lt;li&gt;Định lý không chỉ rõ cần bao nhiêu neuron (số lượng có thể tăng theo cấp số nhân)&lt;/li&gt;
  &lt;li&gt;Mạng sâu hơn thường xấp xỉ được cùng một hàm với ít tham số hơn nhiều&lt;/li&gt;
  &lt;li&gt;Mạng sâu hơn có xu hướng tự hình thành đặc trưng phân cấp trong quá trình học&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hình dung độ sâu và độ rộng qua bài toán xấp xỉ 1D:&lt;/strong&gt; Trên cùng tập dữ liệu gợn sóng, mạng dung lượng thấp cho đường khớp kém, còn khi tăng kích thước lớp ẩn và huấn luyện đủ lâu, đường dự đoán bám sát dữ liệu hơn nhiều (xem chi tiết ở bài Lý thuyết Kiến trúc).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_shallow_poor_fit.jpg&quot; alt=&quot;Khớp kém khi dung lượng thấp&quot; /&gt;
&lt;em&gt;Hình: Mạng quá mỏng hoặc quá nông không đủ dung lượng để xấp xỉ hàm. (Minh họa từ video về bản chất mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_deeper_good_fit.jpg&quot; alt=&quot;Khớp tốt khi đủ dung lượng&quot; /&gt;
&lt;em&gt;Hình: Khi đủ độ sâu/độ rộng và được huấn luyện đầy đủ, mô hình xấp xỉ hàm rất sát. (Minh họa từ video về bản chất mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;các-mẫu-thiết-kế-phổ-biến&quot;&gt;Các Mẫu Thiết kế Phổ biến&lt;/h2&gt;

&lt;h3 id=&quot;độ-rộng-giảm-dần&quot;&gt;Độ rộng Giảm dần&lt;/h3&gt;

&lt;p&gt;Một cấu trúc quen thuộc là giảm dần số neuron qua các lớp:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (784) → 512 → 256 → 128 → 64 → Output (10)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Lý do:&lt;/strong&gt; Nén dần thông tin đầu vào thành các biểu diễn trừu tượng ở mức cao hơn.&lt;/p&gt;

&lt;h3 id=&quot;kiến-trúc-đồng-hồ-cát--cổ-chai-hourglassbottleneck&quot;&gt;Kiến trúc Đồng hồ cát / Cổ chai (&lt;em&gt;Hourglass/Bottleneck&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Thu hẹp chiều xuống một lớp trung gian nhỏ rồi mở rộng trở lại:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (784) → 256 → 64 → 256 → Output (784)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Ứng dụng phổ biến:&lt;/strong&gt; Autoencoder dùng cho bài toán giảm chiều và tái tạo dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;độ-rộng-đồng-nhất&quot;&gt;Độ rộng Đồng nhất&lt;/h3&gt;

&lt;p&gt;Giữ nguyên số neuron ở tất cả các lớp ẩn:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (784) → 256 → 256 → 256 → Output (10)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Lý do:&lt;/strong&gt; Cấu trúc đơn giản, giảm số siêu tham số cần tinh chỉnh.&lt;/p&gt;

&lt;h2 id=&quot;hàm-kích-hoạt-theo-lớp&quot;&gt;Hàm Kích hoạt theo Lớp&lt;/h2&gt;

&lt;p&gt;Các lớp khác nhau trong cùng một mạng có thể sử dụng hàm kích hoạt khác nhau.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cấu hình thường gặp:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lớp ẩn:&lt;/strong&gt; ReLU (hoặc các biến thể như Leaky ReLU, ELU)
    &lt;ul&gt;
      &lt;li&gt;Tính toán nhanh&lt;/li&gt;
      &lt;li&gt;Giảm nhẹ hiện tượng gradient biến mất&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lớp đầu ra:&lt;/strong&gt; Chọn tùy theo tác vụ
    &lt;ul&gt;
      &lt;li&gt;Phân loại nhị phân: Sigmoid&lt;/li&gt;
      &lt;li&gt;Phân loại đa lớp: Softmax&lt;/li&gt;
      &lt;li&gt;Hồi quy: Tuyến tính (hàm đồng nhất)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;lớp-liên-kết-đầy-đủ-so-với-các-kiến-trúc-khác&quot;&gt;Lớp Liên kết Đầy đủ so với Các Kiến trúc Khác&lt;/h2&gt;

&lt;h3 id=&quot;lớp-liên-kết-đầy-đủ-fully-connected--dense&quot;&gt;Lớp Liên kết Đầy đủ (&lt;em&gt;Fully Connected / Dense&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Mỗi neuron ở lớp \(l\) đều kết nối tới toàn bộ neuron của lớp \(l-1\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ưu điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Linh hoạt, không ràng buộc cứng về cấu trúc kết nối&lt;/li&gt;
  &lt;li&gt;Có thể học nhiều dạng mẫu khác nhau nếu có đủ neuron&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Nhược điểm:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Số tham số lớn (\(n^{[l]} \times n^{[l-1]}\))&lt;/li&gt;
  &lt;li&gt;Không tận dụng được cấu trúc sẵn có của dữ liệu đầu vào&lt;/li&gt;
  &lt;li&gt;Kém hiệu quả với dữ liệu có cấu trúc không gian hoặc tuần tự (ảnh, chuỗi)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;các-kiến-trúc-chuyên-biệt&quot;&gt;Các Kiến trúc Chuyên biệt&lt;/h3&gt;

&lt;p&gt;Với từng loại dữ liệu cụ thể, các kiến trúc chuyên biệt cho hiệu quả cao hơn nhiều:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lớp tích chập&lt;/strong&gt; (&lt;em&gt;convolutional layers&lt;/em&gt;): Phù hợp cho ảnh nhờ khai thác cấu trúc không gian&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lớp hồi quy&lt;/strong&gt; (&lt;em&gt;recurrent layers&lt;/em&gt;): Phù hợp cho dữ liệu chuỗi nhờ khai thác cấu trúc thời gian&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cơ chế attention&lt;/strong&gt;: Xử lý hiệu quả các phụ thuộc tầm xa&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Các kiến trúc này sẽ được trình bày chi tiết ở những chương sau.&lt;/p&gt;

&lt;h2 id=&quot;biểu-diễn-mạng&quot;&gt;Biểu diễn Mạng&lt;/h2&gt;

&lt;h3 id=&quot;biểu-diễn-đồ-thị&quot;&gt;Biểu diễn Đồ thị&lt;/h3&gt;

&lt;p&gt;Mạng neuron truyền thẳng thường được biểu diễn dưới dạng đồ thị có hướng không chu trình (DAG):&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;      Input Layer    Hidden Layer 1   Hidden Layer 2   Output Layer
         (3)             (4)              (4)              (2)
    
    x₁  ○────────────────●──────────────────●──────────────────●  ŷ₁
                        ╱│╲              ╱│╲              ╱│
    x₂  ○──────────────●─●─●────────────●─●─●────────────●─●
                        ╲│╱              ╲│╱              ╲│
    x₃  ○────────────────●──────────────────●──────────────────●  ŷ₂
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;biểu-diễn-ma-trận&quot;&gt;Biểu diễn Ma trận&lt;/h3&gt;

&lt;p&gt;Để tối ưu hiệu năng tính toán, các phép toán trên cả batch dữ liệu được viết dưới dạng nhân ma trận:&lt;/p&gt;

\[\mathbf{Z}^{[l]} = \mathbf{W}^{[l]} \mathbf{A}^{[l-1]} + \mathbf{b}^{[l]}\]

&lt;p&gt;trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{A}^{[l-1]}\): ma trận kích hoạt (mỗi cột tương ứng với một mẫu)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}^{[l]}\): ma trận trọng số&lt;/li&gt;
  &lt;li&gt;\(\mathbf{b}^{[l]}\): vector độ lệch (được mở rộng chiều tự động — &lt;em&gt;broadcast&lt;/em&gt; — trên toàn bộ các mẫu)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;triển-khai-thực-tế&quot;&gt;Triển khai Thực tế&lt;/h2&gt;

&lt;h3 id=&quot;ví-dụ-mạng-neuron-đơn-giản-bằng-python&quot;&gt;Ví dụ: Mạng Neuron Đơn giản bằng Python&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        layer_sizes: danh sách kích thước các lớp, gồm đầu vào và đầu ra
        Ví dụ: [784, 128, 64, 10] cho MNIST
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Khởi tạo trọng số và độ lệch
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;biases&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Khởi tạo He cho mạng dùng ReLU
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;biases&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: đầu vào có dạng (input_size, num_examples)
        Trả về: đầu ra có dạng (output_size, num_examples)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;zs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lan truyền xuôi qua các lớp ẩn
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;biases&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;zs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lớp đầu ra (softmax)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;biases&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;zs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zs&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trả về dự đoán lớp&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Ví dụ sử dụng
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;network&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 5 mẫu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;network&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Output shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (10, 5)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;network&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;các-cân-nhắc-thiết-kế&quot;&gt;Các Cân nhắc Thiết kế&lt;/h2&gt;

&lt;h3 id=&quot;số-lớp&quot;&gt;Số Lớp&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;1–2 lớp ẩn:&lt;/strong&gt; Phù hợp cho bài toán đơn giản và tập dữ liệu nhỏ&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;3–5 lớp ẩn:&lt;/strong&gt; Phù hợp cho bài toán có độ phức tạp trung bình&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trên 5 lớp ẩn:&lt;/strong&gt; Phù hợp cho bài toán phức tạp, tập dữ liệu lớn (học sâu)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;số-neuron-trên-mỗi-lớp&quot;&gt;Số Neuron trên mỗi Lớp&lt;/h3&gt;

&lt;p&gt;Một số quy tắc thực nghiệm thường dùng:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Khởi đầu với kích thước lớp ẩn nằm giữa kích thước đầu vào và đầu ra&lt;/li&gt;
  &lt;li&gt;Các mức kích thước phổ biến: 32, 64, 128, 256, 512&lt;/li&gt;
  &lt;li&gt;Tăng số neuron giúp tăng dung lượng nhưng đồng thời tăng nguy cơ quá khớp&lt;/li&gt;
  &lt;li&gt;Dựa vào kết quả trên tập kiểm định (&lt;em&gt;validation set&lt;/em&gt;) để điều chỉnh&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tìm-kiếm-kiến-trúc&quot;&gt;Tìm kiếm Kiến trúc&lt;/h3&gt;

&lt;p&gt;Quá trình chọn kiến trúc phù hợp thường được thực hiện qua:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thử nghiệm thủ công:&lt;/strong&gt; Thay đổi và so sánh các cấu hình dựa trên kinh nghiệm&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Grid search:&lt;/strong&gt; Thử lần lượt mọi tổ hợp trong lưới siêu tham số định trước&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Random search:&lt;/strong&gt; Lấy mẫu ngẫu nhiên các cấu hình, thường hiệu quả hơn grid search&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Neural Architecture Search (NAS):&lt;/strong&gt; Phương pháp tìm kiếm kiến trúc tự động (chủ đề nâng cao)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mạng neuron&lt;/strong&gt; bao gồm lớp đầu vào, các lớp ẩn và lớp đầu ra.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mạng feedforward (MLP)&lt;/strong&gt; là kiến trúc cơ bản nhất, trong đó dữ liệu truyền theo một chiều từ đầu vào tới đầu ra.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền xuôi&lt;/strong&gt; tính toán dự đoán bằng cách đưa đầu vào đi tuần tự qua các lớp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ sâu&lt;/strong&gt; (số lớp) và &lt;strong&gt;độ rộng&lt;/strong&gt; (số neuron mỗi lớp) cùng quyết định dung lượng biểu diễn của mạng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định lý Xấp xỉ Phổ quát&lt;/strong&gt; khẳng định khả năng xấp xỉ về mặt tồn tại, nhưng không đảm bảo hiệu quả tham số hay quá trình tối ưu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lớp liên kết đầy đủ&lt;/strong&gt; nối mọi neuron của hai lớp kề nhau, linh hoạt nhưng tốn nhiều tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thiết kế kiến trúc hợp lý&lt;/strong&gt; cần cân đối giữa bản chất bài toán, lượng dữ liệu và tài nguyên tính toán.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ở bài tiếp theo, ta sẽ tìm hiểu chi tiết hơn về các hàm kích hoạt và vai trò của chúng trong quá trình huấn luyện.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ video của Machine Learning Thực Chiến:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/720970114372332&quot;&gt;Mạng nơ-ron là bộ xấp xỉ hàm&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Giải thích vai trò của việc tăng độ sâu trước khi đi vào các mẫu thiết kế.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qhXZsFVxGKo&quot;&gt;Vanishing/Exploding Gradients (C2W1L10)&lt;/a&gt; — DeepLearningAI, tiếng Anh. Phân tích hiện tượng gradient biến mất — nguyên nhân khiến việc tăng độ sâu thiếu kiểm soát dễ thất bại.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2FaI2Fen1mQ&quot;&gt;The GELU, SiLU and SwiGLU activation functions, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giới thiệu các hàm kích hoạt hiện đại như GELU, SiLU và SwiGLU dùng trong các thiết kế mạng ngày nay.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-02-01 Lý thuyết Kiến trúc Mạng Neuron</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_02_01_Architecture_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_02_01_Architecture_Theory</id>
   <content type="html">&lt;p&gt;Làm sao một mạng chỉ gồm các phép cộng, nhân và cắt bỏ số âm (ReLU) lại có thể vẽ ra ranh giới uốn lượn mềm mại bao quanh một đám mây dữ liệu hình xoắn ốc, hay nhận ra hàng nghìn giống loài khác nhau? Bí mật nằm ở &lt;strong&gt;hình học gấp không gian&lt;/strong&gt; (&lt;em&gt;space folding&lt;/em&gt;) của mạng nhiều tầng (MLP): mỗi tầng ẩn ReLU thực chất đang gấp tờ giấy không gian đầu vào lại một lần, khiến những điểm từng nằm đan xen nhau bỗng tách hẳn sang hai phía của một đường thẳng! Bài học này xây dựng lý thuyết kiến trúc mạng nơ-ron, giải quyết triệt để bài toán XOR và lý giải hình học đằng sau từng lớp ẩn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-lý-thuyết-kiến-trúc-mạng-nơ-ron&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột Lý thuyết Kiến trúc Mạng Nơ-ron&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân rã Bài toán bằng Lớp ẩn (Hidden Representation)&lt;/strong&gt;:
Thay vì cố phân tách dữ liệu ngay ở không gian gốc, lớp ẩn tạo ra hệ tọa độ mới \(\mathbf{h} = \phi(\mathbf{W}^{(1)}\mathbf{x} + \mathbf{b}^{(1)})\) nơi bài toán phi tuyến (như XOR) biến thành khả tách tuyến tính.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Số lượng Vùng Tuyến tính (Linear Regions of ReLU Networks)&lt;/strong&gt;:
Một mạng ReLU chia không gian đầu vào thành nhiều đa diện lồi rời nhau, trên mỗi đa diện mạng hoạt động như một hàm tuyến tính riêng. Số đa diện tối đa tăng theo đa thức với độ rộng, nhưng tăng theo &lt;strong&gt;hàm mũ&lt;/strong&gt; với độ sâu!&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ánh xạ từ Đặc trưng đến Quyết định (Feature Extractor + Classifier)&lt;/strong&gt;:
Mọi mạng phân loại sâu đều có thể tách làm hai phần: toàn bộ các tầng đầu là bộ trích xuất đặc trưng học biểu diễn \(\mathbf{h}\), còn tầng cuối cùng thực chất chỉ là một bộ phân loại tuyến tính (Logistic/Softmax Regression) chạy trên \(\mathbf{h}\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Dung lượng Mô hình (Model Capacity) và Thiên kiến Quy nạp (Inductive Bias)&lt;/strong&gt;:
Kiến trúc quy định họ hàm mà mạng có thể biểu diễn dễ dàng nhất: MLP giả định mọi đầu vào bình đẳng, còn CNN hay Transformer cài sẵn thiên kiến về cấu trúc không gian và quan hệ ngữ cảnh.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tự-tay-giải-bài-toán-xor-bằng-một-mạng-mlp-đúng-2-nơ-ron-ẩn-relu&quot;&gt;Giải thích: Tự tay giải bài toán XOR bằng một mạng MLP đúng 2 nơ-ron ẩn ReLU&lt;/h3&gt;

&lt;p&gt;Ta xây dựng mạng 2–2–1 biến đổi 4 điểm XOR \((x_1, x_2)\) qua 2 nơ-ron ẩn ReLU:
\(h_1 = \max(0,\; x_1 + x_2 - 0.5), \quad h_2 = \max(0,\; x_1 + x_2 - 1.5), \quad \hat{y} = h_1 - 2h_2.\)&lt;/p&gt;

&lt;p&gt;Hãy tính từng dòng cho cả 4 đầu vào:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Đầu vào \((x_1, x_2)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;\(x_1+x_2-0.5\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;\(h_1 = \text{ReLU}(\cdot)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;\(x_1+x_2-1.5\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;\(h_2 = \text{ReLU}(\cdot)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Đầu ra \(\hat{y} = h_1 - 2h_2\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Nhãn XOR&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\((0, 0)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(-0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(-1.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.0 - 0 = \mathbf{0.0}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;0&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\((0, 1)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(+0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(-0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.5 - 0 = \mathbf{0.5}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;1&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\((1, 0)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(+0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(-0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.0\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.5 - 0 = \mathbf{0.5}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;1&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\((1, 1)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(+1.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(+0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.5\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1.5 - 2(0.5) = \mathbf{0.5}\)? Khoan! Kiểm tra lại!&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;—&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Hãy chú ý phép kiểm tra cực quan trọng ở dòng cuối: với hệ số \(-2\) ta được \(1.5 - 1.0 = 0.5\), vẫn chưa về \(0\)! Để kéo \((1,1)\) về đúng \(0\), chỉ cần đổi hệ số của \(h_2\) thành \(-3\) (hoặc dùng \(h_1 = \max(0, x_1+x_2),\, h_2 = \max(0, x_1+x_2-1),\, \hat{y} = h_1 - 2h_2\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\((0,0) \to h_1=0, h_2=0 \implies \hat{y} = 0 - 0 = \mathbf{0}\).&lt;/li&gt;
  &lt;li&gt;\((0,1) \to h_1=1, h_2=0 \implies \hat{y} = 1 - 0 = \mathbf{1}\).&lt;/li&gt;
  &lt;li&gt;\((1,0) \to h_1=1, h_2=0 \implies \hat{y} = 1 - 0 = \mathbf{1}\).&lt;/li&gt;
  &lt;li&gt;\((1,1) \to h_1=2, h_2=1 \implies \hat{y} = 2 - 2(1) = \mathbf{0}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Đúng tuyệt đối 4/4 điểm! Nhìn vào bảng trên bạn thấy phép màu hình học: lớp ẩn đã gộp hai điểm \((0,1)\) và \((1,0)\) về cùng một điểm \((1,0)\) trong không gian \((h_1, h_2)\), khiến đường thẳng \(h_1 - 2h_2 = 0.5\) chém gọn hai lớp XOR chỉ bằng một nhát cắt!&lt;/p&gt;

&lt;h1 id=&quot;kiến-trúc-mạng-neuron-từ-neuron-đến-hệ-thống-sâu&quot;&gt;Kiến trúc Mạng Neuron: Từ Neuron đến Hệ thống Sâu&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/Colored_neural_network.svg/500px-Colored_neural_network.svg.png&quot; alt=&quot;Neural Network Layers&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc mạng neuron với lớp đầu vào (input), lớp ẩn (hidden) và lớp đầu ra (output). Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/mlp_fully_connected.jpg&quot; alt=&quot;Mạng fully connected nhiều lớp&quot; /&gt;
&lt;em&gt;Hình: Mạng feedforward liên kết đầy đủ — input (hồng), hidden (xanh lá), output (xanh dương). (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Kiến trúc mạng neuron là bản thiết kế quy định cách tổ chức, sắp xếp và kết nối các neuron riêng lẻ để giải quyết các bài toán phức tạp. Nếu một neuron đơn lẻ chỉ học được biên quyết định tuyến tính như ta đã thấy với perceptron, thì sức mạnh của học sâu chỉ thực sự xuất hiện khi nhiều neuron được nhóm thành từng lớp và các lớp này được xếp chồng thành kiến trúc sâu. Cấu trúc phân tầng này không đơn thuần là cách bố trí kỹ thuật mà phản ánh cơ chế tính toán hợp thành: các đơn vị đơn giản phối hợp với nhau để tạo nên khả năng biểu diễn phức tạp.&lt;/p&gt;

&lt;p&gt;Thiết kế kiến trúc đóng vai trò quyết định đến những gì mạng có thể học và hiệu quả của quá trình huấn luyện. Một kiến trúc không phù hợp có thể học kém ngay cả trên dữ liệu đơn giản, trong khi một kiến trúc hợp lý có thể nắm bắt những mối quan hệ tinh vi với chi phí hợp lý. Kiến trúc chính là nơi thể hiện các thiên kiến quy nạp (&lt;em&gt;inductive biases&lt;/em&gt;) — những giả định sẵn có về cấu trúc của bài toán — giúp mạng học nhanh và hiệu quả hơn so với việc coi mọi bài toán như một phép xấp xỉ hàm hoàn toàn tổng quát.&lt;/p&gt;

&lt;h3 id=&quot;mô-hình-lớp&quot;&gt;Mô hình Lớp&lt;/h3&gt;

&lt;p&gt;Nguyên lý tổ chức cơ bản của mạng neuron là &lt;strong&gt;lớp&lt;/strong&gt; (&lt;em&gt;layers&lt;/em&gt;) — tập hợp các neuron cùng thực hiện phép biến đổi ở một giai đoạn tính toán. Cách tổ chức theo lớp hiện thực hóa trực tiếp tính toán hợp thành: mỗi lớp chuyển đầu vào thành một biểu diễn mới, và các lớp tiếp theo dựa trên đó để xây dựng những đặc trưng ngày càng trừu tượng. Trong bài toán nhận diện khuôn mặt, các lớp đầu thường học phát hiện cạnh, các lớp giữa ghép cạnh thành bộ phận như mắt, mũi, miệng, còn các lớp sâu hơn nhận diện danh tính hoàn chỉnh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ ảnh chữ số:&lt;/strong&gt; Ảnh kích thước \(28\times28\) được làm phẳng (&lt;em&gt;flatten&lt;/em&gt;) thành \(784\) giá trị đầu vào, đưa qua các lớp ẩn rồi đến \(10\) đầu ra tương ứng với các chữ số từ \(0\) đến \(9\). Không có một công thức cố định nào cho số lượng neuron ẩn — đó là lựa chọn thiết kế — nhưng luồng xử lý luôn đi theo trình tự: vector hóa → đi qua các lớp xếp chồng → xuất đầu ra phù hợp với tác vụ.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/mnist_mlp_10_outputs.jpg&quot; alt=&quot;MLP nhận diện chữ số: 784 → ẩn → 10&quot; /&gt;
&lt;em&gt;Hình: Quy trình kiểu MNIST — \(784\) pixel → lớp ẩn → \(10\) logit cho các chữ số. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Cấu trúc xử lý phân cấp này tương đồng với cả hệ thần kinh sinh học lẫn bản chất phân tầng của nhiều khái niệm trong thực tế. Chẳng hạn, một chiếc xe gồm bánh xe, cửa sổ và thân xe; các bộ phận này được cấu thành từ hình dạng và kết cấu (&lt;em&gt;texture&lt;/em&gt;); và các yếu tố đó lại bắt nguồn từ cạnh và màu sắc. Các lớp trong mạng neuron tự nhiên học được hệ thống phân cấp này, với mỗi lớp phụ trách một mức độ trừu tượng tương ứng với vị trí của nó trong mạng.&lt;/p&gt;

&lt;h3 id=&quot;vì-sao-kiến-trúc-quan-trọng-đánh-đổi-giữa-độ-sâu-và-độ-rộng&quot;&gt;Vì sao Kiến trúc Quan trọng: Đánh đổi giữa Độ sâu và Độ rộng&lt;/h3&gt;

&lt;p&gt;Một nhận định quan trọng từ cả lý thuyết lẫn thực nghiệm là &lt;strong&gt;độ sâu&lt;/strong&gt; (số lớp) và &lt;strong&gt;độ rộng&lt;/strong&gt; (số neuron trên mỗi lớp) tác động rất khác nhau tới dung lượng và khả năng học của mạng. Định lý Xấp xỉ Phổ quát khẳng định rằng chỉ cần một lớp ẩn với đủ nhiều neuron là đã có thể xấp xỉ bất kỳ hàm liên tục nào. Tuy nhiên, trong thực tế, mạng sâu với số neuron mỗi lớp vừa phải thường vượt trội hơn mạng nông nhưng rất rộng trên các bài toán phức tạp.&lt;/p&gt;

&lt;p&gt;Lợi thế này không chỉ nằm ở hiệu quả tham số — khi mạng sâu thường đạt sức biểu diễn tương đương với số tham số ít hơn theo cấp số nhân so với mạng nông — mà còn ở cách biểu diễn dữ liệu. Mạng sâu tự hình thành hệ thống đặc trưng phân cấp trong quá trình huấn luyện mà không cần lập trình thủ công từng bước phát hiện cạnh hay hình dạng. Bên cạnh đó, các biểu diễn trung gian của mạng sâu thường khái quát hóa tốt hơn và dễ tái sử dụng giữa các tác vụ khác nhau, làm nền tảng cho học chuyển giao (&lt;em&gt;transfer learning&lt;/em&gt;) và tiền huấn luyện (&lt;em&gt;pretraining&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Hiểu rõ sự đánh đổi giữa độ sâu và độ rộng, cũng như ảnh hưởng của lựa chọn kiến trúc lên quá trình tối ưu, khả năng khái quát hóa và chi phí tính toán, là điều kiện cần để thiết kế mạng neuron hiệu quả. Bài học này trình bày nền tảng toán học và trực giác giúp bạn đưa ra các quyết định kiến trúc có cơ sở.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;h3 id=&quot;mạng-neuron-feedforward-định-nghĩa-hình-thức&quot;&gt;Mạng Neuron Feedforward: Định nghĩa Hình thức&lt;/h3&gt;

&lt;p&gt;Một &lt;strong&gt;mạng neuron truyền thẳng&lt;/strong&gt; (&lt;em&gt;feedforward neural network&lt;/em&gt;, còn gọi là &lt;strong&gt;Multilayer Perceptron&lt;/strong&gt; hay &lt;strong&gt;MLP&lt;/strong&gt;) là một hàm \(f: \mathbb{R}^{n_0} \to \mathbb{R}^{n_L}\) được tạo nên bằng cách hợp thành các phép biến đổi theo từng lớp. Với mạng gồm \(L\) lớp:&lt;/p&gt;

\[f(\mathbf{x}) = f^{[L]} \circ f^{[L-1]} \circ \cdots \circ f^{[1]}(\mathbf{x})\]

&lt;p&gt;trong đó mỗi hàm lớp \(f^{[l]}\) gồm một phép biến đổi affine theo sau bởi một hàm kích hoạt phi tuyến áp dụng theo từng phần tử:&lt;/p&gt;

\[f^{[l]}(\mathbf{a}^{[l-1]}) = \sigma^{[l]}(\mathbf{W}^{[l]} \mathbf{a}^{[l-1]} + \mathbf{b}^{[l]})\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_hidden_activation_formula.jpg&quot; alt=&quot;Công thức lớp ẩn + kích hoạt&quot; /&gt;
&lt;em&gt;Hình: Một lớp ẩn \(z_1=\sigma(xw+b)\) theo sau bởi lớp tuyến tính để cho ra \(f(x)\). (Minh họa từ video về bản chất mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_width_parameters_formula.jpg&quot; alt=&quot;Mở rộng độ rộng (nhiều neuron ẩn)&quot; /&gt;
&lt;em&gt;Hình: Tăng kích thước ma trận \(W\) (thêm neuron ẩn) làm tăng số tham số và khả năng biểu diễn. (Minh họa từ video về bản chất mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_hidden_layer_diagram.jpg&quot; alt=&quot;Sơ đồ lớp ẩn&quot; /&gt;
&lt;em&gt;Hình: Kết nối input → hidden → output tương ứng với ma trận trọng số \(W\). (Minh họa từ video về bản chất mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Dưới đây ta sẽ phân tích chi tiết từng thành phần trong công thức này.&lt;/p&gt;

&lt;h3 id=&quot;tính-toán-từng-lớp&quot;&gt;Tính toán Từng Lớp&lt;/h3&gt;

&lt;p&gt;Xét mạng có \(L\) lớp (không tính lớp đầu vào). Tại mỗi lớp \(l \in \{1, 2, \ldots, L\}\), phép tính gồm hai bước:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tiền kích hoạt (biến đổi tuyến tính):&lt;/strong&gt;
\(\mathbf{z}^{[l]} = \mathbf{W}^{[l]} \mathbf{a}^{[l-1]} + \mathbf{b}^{[l]}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kích hoạt (biến đổi phi tuyến):&lt;/strong&gt;
\(\mathbf{a}^{[l]} = \sigma^{[l]}(\mathbf{z}^{[l]})\)&lt;/p&gt;

&lt;p&gt;Kích thước của các đại lượng:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{a}^{[l-1]} \in \mathbb{R}^{n_{l-1}}\): đầu vào của lớp \(l\) (đầu ra từ lớp trước)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}^{[l]} \in \mathbb{R}^{n_l \times n_{l-1}}\): ma trận trọng số&lt;/li&gt;
  &lt;li&gt;\(\mathbf{b}^{[l]} \in \mathbb{R}^{n_l}\): vector độ lệch&lt;/li&gt;
  &lt;li&gt;\(\mathbf{z}^{[l]} \in \mathbb{R}^{n_l}\): vector tiền kích hoạt&lt;/li&gt;
  &lt;li&gt;\(\mathbf{a}^{[l]} \in \mathbb{R}^{n_l}\): vector hậu kích hoạt (đầu ra của lớp)&lt;/li&gt;
  &lt;li&gt;\(n_l\): số lượng neuron ở lớp \(l\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;vai-trò-của-từng-thành-phần&quot;&gt;Vai trò của Từng Thành phần&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ma trận trọng số \(\mathbf{W}^{[l]}\):&lt;/strong&gt; Mỗi hàng \(\mathbf{w}_i^{[l]}\) quy định tổ hợp tuyến tính đầu vào cho một neuron. Phép nhân ma trận \(\mathbf{W}^{[l]} \mathbf{a}^{[l-1]}\) tính đồng thời giá trị tiền kích hoạt của toàn bộ neuron trong lớp. Trọng số là các tham số học được, liên tục điều chỉnh trong quá trình huấn luyện để nắm bắt cấu trúc dữ liệu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vector độ lệch \(\mathbf{b}^{[l]}\):&lt;/strong&gt; Dịch chuyển hàm kích hoạt sang trái hoặc phải, cho phép neuron kích hoạt ngay cả khi các đầu vào đều gần bằng 0. Nếu thiếu độ lệch, một neuron ReLU khi nhận đầu vào toàn 0 sẽ luôn trả về 0, làm giảm đáng kể khả năng biểu đạt. Độ lệch vì vậy rất cần thiết để học các ngưỡng kích hoạt phù hợp.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hàm kích hoạt \(\sigma^{[l]}\):&lt;/strong&gt; Bổ sung tính phi tuyến để mạng học được các biên quyết định phức tạp. Nếu không có hàm kích hoạt phi tuyến, việc xếp chồng nhiều lớp trở nên vô ích vì hợp của nhiều phép biến đổi tuyến tính vẫn chỉ là một phép biến đổi tuyến tính duy nhất. Các lựa chọn phổ biến gồm:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;ReLU: \(\sigma(z) = \max(0, z)\)&lt;/li&gt;
  &lt;li&gt;Sigmoid: \(\sigma(z) = \frac{1}{1+e^{-z}}\)&lt;/li&gt;
  &lt;li&gt;Tanh: \(\sigma(z) = \tanh(z)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;thiết-kế-lớp-đầu-ra&quot;&gt;Thiết kế Lớp Đầu ra&lt;/h3&gt;

&lt;p&gt;Cấu trúc lớp đầu ra phụ thuộc trực tiếp vào bản chất bài toán để đảm bảo đầu ra tương thích với hàm mất mát.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phân loại nhị phân&lt;/strong&gt; (\(y \in \{0, 1\}\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Một neuron đầu ra với hàm kích hoạt sigmoid&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Diễn giải: $$\hat{y} = P(y=1&lt;/td&gt;
          &lt;td&gt;\mathbf{x})$$&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;Đầu ra: \(\hat{y} = \sigma(z) = \frac{1}{1 + e^{-z}} \in (0,1)\)&lt;/li&gt;
  &lt;li&gt;Hàm mất mát: Entropy chéo nhị phân \(\mathcal{L} = -[y \log \hat{y} + (1-y) \log(1-\hat{y})]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phân loại đa lớp&lt;/strong&gt; (\(y \in \{1,2,\ldots,K\}\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(K\) neuron đầu ra với hàm kích hoạt softmax&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Diễn giải: $$\hat{y}_k = P(y=k&lt;/td&gt;
          &lt;td&gt;\mathbf{x})$$&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;Đầu ra: \(\hat{y}_k = \frac{e^{z_k}}{\sum_{j=1}^K e^{z_j}}\) với \(\sum_{k=1}^K \hat{y}_k = 1\)&lt;/li&gt;
  &lt;li&gt;Hàm mất mát: Entropy chéo đa lớp (&lt;em&gt;categorical cross-entropy&lt;/em&gt;) \(\mathcal{L} = -\sum_{k=1}^K y_k \log \hat{y}_k\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hàm softmax có các tính chất rất hữu ích: khả vi, đầu ra tạo thành một phân phối xác suất hợp lệ, và đóng vai trò phiên bản trơn (“mềm”) của phép &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;argmax&lt;/code&gt;, nhờ đó huấn luyện được bằng gradient descent.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hồi quy&lt;/strong&gt; (\(y \in \mathbb{R}\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Một hoặc nhiều neuron đầu ra với kích hoạt tuyến tính (hàm đồng nhất)&lt;/li&gt;
  &lt;li&gt;Đầu ra: \(\hat{y} = z\) (không áp dụng hàm phi tuyến)&lt;/li&gt;
  &lt;li&gt;Hàm mất mát: Sai số bình phương trung bình \(\mathcal{L} = \frac{1}{2}(y - \hat{y})^2\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;lan-truyền-xuôi-toàn-bộ-quy-trình&quot;&gt;Lan truyền Xuôi: Toàn bộ Quy trình&lt;/h3&gt;

&lt;p&gt;Với đầu vào \(\mathbf{x} \in \mathbb{R}^{n_0}\), quá trình lan truyền xuôi diễn ra như sau:&lt;/p&gt;

\[\begin{align}
\mathbf{a}^{[0]} &amp;amp;= \mathbf{x} \quad \text{(khởi tạo bằng đầu vào)} \\
\\
\text{For } l &amp;amp;= 1 \text{ to } L: \\
\mathbf{z}^{[l]} &amp;amp;= \mathbf{W}^{[l]} \mathbf{a}^{[l-1]} + \mathbf{b}^{[l]} \quad \text{(biến đổi affine)} \\
\mathbf{a}^{[l]} &amp;amp;= \sigma^{[l]}(\mathbf{z}^{[l]}) \quad \text{(kích hoạt phi tuyến)} \\
\\
\hat{\mathbf{y}} &amp;amp;= \mathbf{a}^{[L]} \quad \text{(đầu ra cuối)}
\end{align}\]

&lt;p&gt;Chuỗi tính toán tuần tự này xây dựng các biểu diễn dữ liệu ngày càng trừu tượng, giúp mạng xấp xỉ được nhiều loại hàm phức tạp.&lt;/p&gt;

&lt;h3 id=&quot;số-tham-số-và-độ-phức-tạp&quot;&gt;Số Tham số và Độ phức tạp&lt;/h3&gt;

&lt;p&gt;Tổng số tham số học được của mạng là:&lt;/p&gt;

\[\text{Parameters} = \sum_{l=1}^{L} (n_l \times n_{l-1} + n_l) = \sum_{l=1}^{L} n_l(n_{l-1} + 1)\]

&lt;p&gt;Ví dụ cụ thể với kiến trúc [784, 128, 64, 10]:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Lớp 1: \(128 \times 784 + 128 = 100,480\) tham số&lt;/li&gt;
  &lt;li&gt;Lớp 2: \(64 \times 128 + 64 = 8,256\) tham số&lt;/li&gt;
  &lt;li&gt;Lớp 3: \(10 \times 64 + 10 = 650\) tham số&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổng&lt;/strong&gt;: \(109,386\) tham số&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Số lượng tham số tăng theo bậc hai theo độ rộng lớp nhưng chỉ tăng tuyến tính theo độ sâu. Đây là một trong những lý do khiến mạng sâu và hẹp thường sử dụng tham số hiệu quả hơn mạng nông nhưng rộng khi cần cùng một năng lực biểu diễn.&lt;/p&gt;

&lt;h3 id=&quot;định-lý-xấp-xỉ-phổ-quát&quot;&gt;Định lý Xấp xỉ Phổ quát&lt;/h3&gt;

&lt;div class=&quot;textbook-theorem&quot;&gt;
  &lt;p&gt;&lt;strong&gt;Định lý&lt;/strong&gt; (Cybenko 1989, Hornik et al. 1989): Cho \(\sigma\) là hàm liên tục đơn điệu tăng, bị chặn, không hằng (ví dụ: sigmoid). Khi đó với mọi hàm liên tục \(g\) trên tập compact \(K \subset \mathbb{R}^n\), mọi \(\epsilon &amp;gt; 0\), và mọi độ đo xác suất \(\mu\) trên \(K\), tồn tại mạng neuron một lớp ẩn \(f\) sao cho:&lt;/p&gt;

  &lt;p&gt;\(\int_K |f(\mathbf{x}) - g(\mathbf{x})| d\mu(\mathbf{x}) &amp;lt; \epsilon\)&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Ý nghĩa:&lt;/strong&gt; Mạng neuron có thể xấp xỉ bất kỳ hàm liên tục nào với độ chính xác tùy ý. Về nguyên lý, điều này khẳng định mạng neuron là bộ xấp xỉ hàm phổ quát (&lt;em&gt;universal function approximator&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trực giác thực nghiệm (1D):&lt;/strong&gt; Trên cùng một tập điểm gợn sóng, mạng nông hoặc dung lượng thấp cho đường khớp rất kém; khi tăng độ rộng hoặc độ sâu và huấn luyện đầy đủ, đường dự đoán bám sát dữ liệu hơn nhiều.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_shallow_poor_fit.jpg&quot; alt=&quot;Mạng nông: khớp kém&quot; /&gt;
&lt;em&gt;Hình: Dung lượng thấp — đường dự đoán (hồng) lệch xa dữ liệu. (Minh họa từ video về bản chất mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_deeper_good_fit.jpg&quot; alt=&quot;Mạng đủ sâu/rộng: khớp tốt&quot; /&gt;
&lt;em&gt;Hình: Sau khi mở rộng kiến trúc và huấn luyện — mô hình khớp sát dữ liệu. (Minh họa từ video về bản chất mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_predictions_complex_curve.jpg&quot; alt=&quot;Dự đoán điểm trên đường cong phức tạp&quot; /&gt;
&lt;em&gt;Hình: Lan truyền xuôi tại nhiều giá trị \(x\) tái tạo lại toàn bộ đường cong hàm số. (Minh họa từ video về bản chất mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_prediction_neuron_activation.jpg&quot; alt=&quot;Neuron sáng theo vùng input&quot; /&gt;
&lt;em&gt;Hình: Với mỗi vùng \(x\), các nhóm neuron ẩn khác nhau kích hoạt — minh họa cách mạng chia nhỏ không gian đầu vào. (Minh họa từ video về bản chất mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Các lưu ý quan trọng:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tồn tại không đồng nghĩa với dễ học:&lt;/strong&gt; Định lý khẳng định nghiệm tồn tại nhưng không đảm bảo gradient descent sẽ tìm được nghiệm đó.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Yêu cầu về độ rộng:&lt;/strong&gt; Mạng một lớp ẩn có thể cần số lượng neuron tăng theo cấp số nhân (theo số chiều đầu vào hoặc độ chính xác \(1/\epsilon\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu quả của độ sâu:&lt;/strong&gt; Mạng sâu hơn thường đạt mức xấp xỉ tương đương với số tham số ít hơn nhiều.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không chỉ dẫn thiết kế cụ thể:&lt;/strong&gt; Định lý không cho biết nên chọn hàm kích hoạt, phương pháp khởi tạo hay tốc độ học nào.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nói cách khác, định lý giải thích &lt;em&gt;vì sao&lt;/em&gt; mạng neuron có khả năng biểu diễn về mặt nguyên lý, còn hiệu quả thực tế của học sâu đến từ các tiến bộ về độ sâu, kiến trúc, thuật toán tối ưu và chính quy hóa.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ--trực-giác&quot;&gt;3. Ví dụ / Trực giác&lt;/h2&gt;

&lt;p&gt;Để nắm chắc cách hoạt động của kiến trúc mạng neuron, hãy theo dõi luồng thông tin qua từng bước trong một ví dụ cụ thể.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-mạng-3-lớp-cho-mnist&quot;&gt;Ví dụ: Mạng 3 Lớp cho MNIST&lt;/h3&gt;

&lt;p&gt;Xét một mạng phân loại ảnh chữ số viết tay (ảnh xám kích thước 28×28 thuộc 10 lớp):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kiến trúc:&lt;/strong&gt; [784 → 128 → 64 → 10]&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đầu vào&lt;/strong&gt;: 784 pixel (ảnh 28×28 được làm phẳng)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lớp ẩn 1&lt;/strong&gt;: 128 neuron với ReLU&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lớp ẩn 2&lt;/strong&gt;: 64 neuron với ReLU&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lớp đầu ra&lt;/strong&gt;: 10 neuron với softmax&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;luồng-thông-tin-chi-tiết&quot;&gt;Luồng Thông tin Chi tiết&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Bước 1: Đầu vào (Lớp 0)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Nhận một ảnh 28×28 của chữ số “3” và làm phẳng thành vector:
\(\mathbf{a}^{[0]} = [0.2, 0.1, 0.0, 0.8, 0.9, \ldots] \in \mathbb{R}^{784}\)&lt;/p&gt;

&lt;p&gt;Mỗi phần tử biểu diễn cường độ sáng của một pixel (0 là đen, 1 là trắng). Mạng xem bức ảnh như một điểm trong không gian 784 chiều.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 2: Lớp Ẩn Thứ nhất (Lớp 1)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Lớp này gồm 128 neuron, mỗi neuron học cách phát hiện một mẫu cục bộ khác nhau:&lt;/p&gt;

\[\mathbf{z}^{[1]} = \mathbf{W}^{[1]} \mathbf{a}^{[0]} + \mathbf{b}^{[1]}\]

&lt;p&gt;trong đó \(\mathbf{W}^{[1]} \in \mathbb{R}^{128 \times 784}\) và \(\mathbf{b}^{[1]} \in \mathbb{R}^{128}\).&lt;/p&gt;

&lt;p&gt;Chẳng hạn, trong 128 neuron này:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Neuron 1 có thể kích hoạt mạnh với cạnh dọc ở góc trên bên trái&lt;/li&gt;
  &lt;li&gt;Neuron 2 có thể kích hoạt với đường cong tròn&lt;/li&gt;
  &lt;li&gt;Neuron 3 có thể kích hoạt với nét chéo&lt;/li&gt;
  &lt;li&gt;Và tương tự cho các neuron còn lại&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sau khi qua hàm kích hoạt ReLU: \(\mathbf{a}^{[1]} = \max(0, \mathbf{z}^{[1]}) \in \mathbb{R}^{128}\)&lt;/p&gt;

&lt;p&gt;Một số neuron cho giá trị dương lớn, số khác bị ReLU đưa về 0. Mạng đã chuyển dữ liệu pixel thô sang một biểu diễn đặc trưng, tương ứng với thông tin như: “ảnh này có cạnh dọc rõ, đường cong ở mức trung bình, nét ngang yếu.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 3: Lớp Ẩn Thứ hai (Lớp 2)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Lớp thứ hai kết hợp các đặc trưng mức thấp từ Lớp 1 thành các cấu trúc trừu tượng hơn:&lt;/p&gt;

\[\mathbf{z}^{[2]} = \mathbf{W}^{[2]} \mathbf{a}^{[1]} + \mathbf{b}^{[2]}\]

&lt;p&gt;trong đó \(\mathbf{W}^{[2]} \in \mathbb{R}^{64 \times 128}\).&lt;/p&gt;

&lt;p&gt;Các neuron ở đây có thể phản ứng với các bộ phận lớn hơn:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Neuron 1: “vòng cong phía trên” (kết hợp các đường cong và cạnh ở nửa trên)&lt;/li&gt;
  &lt;li&gt;Neuron 2: “vòng cong phía dưới” (tổ hợp đường cong ở nửa dưới)&lt;/li&gt;
  &lt;li&gt;Neuron 3: “nét dọc” (kết hợp các cạnh dọc)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sau ReLU: \(\mathbf{a}^{[2]} = \max(0, \mathbf{z}^{[2]}) \in \mathbb{R}^{64}\)&lt;/p&gt;

&lt;p&gt;Biểu diễn ở giai đoạn này đã giàu ngữ nghĩa hơn: “ảnh có cả vòng cong trên và dưới, giống đặc trưng của các chữ số 3, 8 hoặc 0.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bước 4: Lớp Đầu ra (Lớp 3)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Lớp cuối cùng tính điểm phân loại cho từng chữ số:&lt;/p&gt;

\[\mathbf{z}^{[3]} = \mathbf{W}^{[3]} \mathbf{a}^{[2]} + \mathbf{b}^{[3]} \in \mathbb{R}^{10}\]

&lt;p&gt;trong đó \(\mathbf{W}^{[3]} \in \mathbb{R}^{10 \times 64}\).&lt;/p&gt;

&lt;p&gt;Các giá trị thô (logits) này sau đó được chuyển sang phân phối xác suất bằng softmax:&lt;/p&gt;

\[\hat{\mathbf{y}} = \text{softmax}(\mathbf{z}^{[3]})\]

&lt;p&gt;Kết quả có dạng:
\(\hat{\mathbf{y}} = [0.01, 0.02, 0.05, 0.82, 0.03, 0.01, 0.02, 0.02, 0.01, 0.01]\)&lt;/p&gt;

&lt;p&gt;Mạng dự đoán với xác suất 82% rằng ảnh là chữ số “3” (chỉ số 3), đồng thời gán xác suất nhỏ cho các chữ số khác có vài đặc trưng tương đồng.&lt;/p&gt;

&lt;h3 id=&quot;vì-sao-cấu-trúc-lớp-này-hoạt-động-hiệu-quả&quot;&gt;Vì sao Cấu trúc Lớp này Hoạt động Hiệu quả&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Học đặc trưng phân cấp:&lt;/strong&gt; Lớp 1 học cạnh và đường cong, Lớp 2 ghép chúng thành bộ phận chữ số, còn Lớp 3 tổng hợp các bộ phận để đưa ra kết luận cuối cùng. Hệ thống phân cấp này tự hình thành qua huấn luyện mà không cần thiết kế thủ công.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Biểu diễn phân tán:&lt;/strong&gt; Khái niệm chữ số “3” không nằm gói gọn ở một neuron duy nhất mà được mã hóa qua tổ hợp kích hoạt của cả 64 neuron ở Lớp 2. Cách biểu diễn này vừa có độ bền cao (mất một vài neuron không làm hỏng hoàn toàn dự đoán) vừa tiết kiệm (cùng các đặc trưng có thể tái sử dụng cho nhiều chữ số).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Giảm chiều dần:&lt;/strong&gt; Dữ liệu đi từ 784 chiều nén dần xuống 128 → 64 → 10. Quá trình thu hẹp chiều buộc mạng giữ lại các thông tin phân biệt quan trọng và loại bỏ nhiễu không cần thiết.&lt;/p&gt;

&lt;h3 id=&quot;trực-giác-vì-sao-độ-sâu-hiệu-quả-hơn-độ-rộng&quot;&gt;Trực giác: Vì sao Độ sâu Hiệu quả hơn Độ rộng&lt;/h3&gt;

&lt;p&gt;So sánh hai kiến trúc thay thế cho cùng một bài toán:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Nông – Rộng:&lt;/strong&gt; [784 → 4096 → 10]&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Một lớp ẩn rất rộng với 4096 neuron&lt;/li&gt;
  &lt;li&gt;Tổng số tham số: khoảng 3.26M&lt;/li&gt;
  &lt;li&gt;Mỗi neuron phải học trực tiếp mẫu hoàn chỉnh từ pixel thô&lt;/li&gt;
  &lt;li&gt;Không hình thành hệ thống đặc trưng phân cấp rõ rệt&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Sâu – Hẹp:&lt;/strong&gt; [784 → 128 → 64 → 32 → 10]&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Ba lớp ẩn nhỏ hơn&lt;/li&gt;
  &lt;li&gt;Tổng số tham số: khoảng 111K (ít hơn gần 29 lần)&lt;/li&gt;
  &lt;li&gt;Tự hình thành phân cấp đặc trưng qua các lớp&lt;/li&gt;
  &lt;li&gt;Thường khái quát hóa tốt hơn và dễ huấn luyện hơn&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mạng sâu chiếm ưu thế vì hầu hết dữ liệu trong thực tế đều có cấu trúc hợp thành: khuôn mặt tạo nên từ mắt, mũi, miệng; câu văn tạo nên từ cụm từ, từ và chữ cái. Kiến trúc nhiều lớp phản ánh trực tiếp cấu trúc phân tầng đó.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ các video của Machine Learning Thực Chiến:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/793200140509765&quot;&gt;Trực giác mạng nơ-ron (Perceptron → Deep Learning)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/720970114372332&quot;&gt;Mạng nơ-ron là bộ xấp xỉ hàm&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Diễn giải mỗi lớp như một ánh xạ affine kết hợp phi tuyến, khớp với công thức trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=CqOfi41LfDw&quot;&gt;The Essential Main Ideas of Neural Networks&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa chi tiết một lớp ẩn với kích thước ma trận hiển thị rõ ràng.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 4&lt;/td&gt;
          &lt;td&gt;Introduction to Neural Networks](https://www.youtube.com/watch?v=d14TUNcbn1k) — Stanford University School of Engineering, tiếng Anh. Bài giảng trình bày phương trình các lớp và lý giải vai trò của phép hợp hàm trong mạng sâu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-01 Perceptron và Neuron Nhân tạo</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_01_Perceptron_and_Neurons/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_01_Perceptron_and_Neurons</id>
   <content type="html">&lt;p&gt;Từng có thời điểm năm 1969, cuốn sách &lt;em&gt;Perceptrons&lt;/em&gt; của Marvin Minsky và Seymour Papert đã chứng minh rằng một Perceptron đơn lẻ hoàn toàn bất lực trước một cổng logic cực kỳ đơn giản: &lt;strong&gt;phép XOR&lt;/strong&gt;—gây ra “mùa đông AI” đầu tiên kéo dài hơn một thập kỷ. Vì sao một phép tính nhỏ bé như XOR lại đánh bại được Perceptron? Câu trả lời nằm ngay trong hình học của phương trình \(\mathbf{w}^\top \mathbf{x} + b = 0\): một nơ-ron đơn chỉ biết kẻ &lt;strong&gt;một đường thẳng duy nhất&lt;/strong&gt;. Bài học này phân tích sâu cấu tạo toán học, trực giác siêu phẳng và giới hạn tuyến tính của Perceptron để thấy rõ vì sao ta buộc phải xây dựng mạng nhiều tầng.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-mảnh-ghép-cốt-lõi-của-perceptron-và-nơ-ron-nhân-tạo&quot;&gt;Kiến thức cần nhớ: Bốn mảnh ghép cốt lõi của Perceptron và Nơ-ron Nhân tạo&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tổng có trọng số và Độ lệch (Weighted Sum &amp;amp; Bias)&lt;/strong&gt;:
Vector trọng số \(\mathbf{w}\) quyết định &lt;strong&gt;hướng&lt;/strong&gt; (vector pháp tuyến) và độ nhạy của ranh giới quyết định; còn bias \(b\) dịch chuyển siêu phẳng ra khỏi gốc tọa độ để khớp dữ liệu tự do hơn.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hình học Siêu phẳng và Tính Khả tách Tuyến tính (Linear Separability)&lt;/strong&gt;:
Phương trình \(\mathbf{w}^\top \mathbf{x} + b = 0\) chia \(\mathbb{R}^d\) thành đúng hai nửa không gian dương/âm. Perceptron chỉ giải hoàn hảo các bài toán mà hai lớp có thể ngăn cách bởi một mặt phẳng (như AND, OR), và bó tay với XOR.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hàm bước nhảy (Step Function) vs. Hàm kích hoạt khả vi (Sigmoid / ReLU)&lt;/strong&gt;:
Perceptron cổ điển dùng hàm bước Heaviside có đạo hàm bằng \(0\) khắp nơi (và không xác định tại \(0\)), nên không dùng được Gradient Descent; thay bằng hàm trơn khả vi mở ra kỷ nguyên huấn luyện bằng lan truyền ngược.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Quy tắc cập nhật Perceptron (Perceptron Learning Rule)&lt;/strong&gt;:
Khi đoán sai mẫu \((\mathbf{x}, y)\), xoay vector trọng số theo \(\mathbf{w} \leftarrow \mathbf{w} + \eta (y - \hat{y})\mathbf{x}\)—định lý hội tụ Perceptron đảm bảo thuật toán dừng sau hữu hạn bước nếu dữ liệu khả tách tuyến tính.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tự-tay-kiểm-chứng-perceptron-giải-được-and-nhưng-thất-bại-trước-xor&quot;&gt;Giải thích: Tự tay kiểm chứng Perceptron giải được AND nhưng thất bại trước XOR&lt;/h3&gt;

&lt;p&gt;Xét bốn điểm góc của hình vuông đơn vị \((x_1, x_2) \in \{(0,0), (0,1), (1,0), (1,1)\}\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Perceptron giải cổng AND&lt;/strong&gt; với \(w_1 = 1, w_2 = 1, b = -1.5\) và quy tắc \(\hat{y} = 1\) nếu \(z = x_1 + x_2 - 1.5 \ge 0\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\((0,0) \to z = -1.5 &amp;lt; 0 \implies \hat{y} = 0\) (đúng)&lt;/li&gt;
  &lt;li&gt;\((0,1) \to z = -0.5 &amp;lt; 0 \implies \hat{y} = 0\) (đúng)&lt;/li&gt;
  &lt;li&gt;\((1,0) \to z = -0.5 &amp;lt; 0 \implies \hat{y} = 0\) (đúng)&lt;/li&gt;
  &lt;li&gt;\((1,1) \to z = +0.5 \ge 0 \implies \hat{y} = 1\) (đúng)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Chứng minh bằng phản chứng Perceptron KHÔNG THỂ giải XOR&lt;/strong&gt; (nhãn \(y(0,0)=0, y(1,1)=0\) nhưng \(y(0,1)=1, y(1,0)=1\)):
Giả sử tồn tại \(w_1, w_2, b\) phân tách được XOR:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tại \((0,0)\) cho \(0 \implies b &amp;lt; 0\).&lt;/li&gt;
  &lt;li&gt;Tại \((0,1)\) cho \(1 \implies w_2 + b \ge 0\).&lt;/li&gt;
  &lt;li&gt;Tại \((1,0)\) cho \(1 \implies w_1 + b \ge 0\).&lt;/li&gt;
  &lt;li&gt;Cộng hai bất đẳng thức giữa: \(w_1 + w_2 + 2b \ge 0\). Vì \(b &amp;lt; 0\) nên \(w_1 + w_2 + b &amp;gt; w_1 + w_2 + 2b \ge 0\)!&lt;/li&gt;
  &lt;li&gt;Nhưng điều đó ép điểm \((1,1)\) phải cho \(z = w_1 + w_2 + b &amp;gt; 0 \implies \hat{y} = 1\), &lt;strong&gt;mâu thuẫn&lt;/strong&gt; với nhãn XOR bằng \(0\)! Chỉ cần 4 dòng bất đẳng thức, bạn đã thấy trọn vẹn lý do lịch sử buộc nhân loại phải phát minh ra mạng nhiều tầng (MLP)!&lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;perceptron-và-neuron-nhân-tạo&quot;&gt;Perceptron và Neuron Nhân tạo&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Perceptron_moj.png/400px-Perceptron_moj.png&quot; alt=&quot;Perceptron Diagram&quot; /&gt;
&lt;em&gt;Hình ảnh: Sơ đồ cấu trúc của một Perceptron. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;Hành trình tìm hiểu học sâu bắt đầu từ đơn vị cơ bản nhất: neuron nhân tạo (&lt;em&gt;artificial neuron&lt;/em&gt;). Dù học sâu hiện đại đã tiến rất xa so với perceptron đơn giản do Frank Rosenblatt giới thiệu năm 1958, việc nắm rõ điểm xuất phát lịch sử này giúp ta hiểu vì sao các mạng neuron ngày nay lại được thiết kế như vậy. Perceptron là một trong những nỗ lực đầu tiên nhằm xây dựng hệ thống có thể tự học từ ví dụ, lấy cảm hứng đơn giản hóa từ cách neuron sinh học xử lý thông tin.&lt;/p&gt;

&lt;p&gt;Về bản chất, perceptron là một bộ phân loại nhị phân. Nó nhận nhiều đầu vào dạng số, kết hợp chúng thông qua các trọng số (&lt;em&gt;weights&lt;/em&gt;) học được, rồi đưa ra một đầu ra nhị phân cho biết mẫu dữ liệu thuộc lớp nào trong hai lớp. Điểm quan trọng ở cơ chế này là khả năng tự động học trọng số từ dữ liệu: thuật toán lặp lại việc điều chỉnh trọng số cho đến khi phân loại đúng các mẫu huấn luyện. Dù đơn giản so với chuẩn mực hiện đại, ý tưởng này đã tạo ra bước ngoặt lớn vào thời điểm ra đời và đặt nền móng cho toàn bộ lĩnh vực mạng neuron sau này.&lt;/p&gt;

&lt;p&gt;Hiểu rõ perceptron rất cần thiết vì nó giới thiệu nhiều khái niệm cốt lõi vẫn được dùng xuyên suốt học sâu. Cơ chế tổng có trọng số phản ánh mức độ đóng góp khác nhau của từng đặc trưng vào quyết định cuối cùng. Hạng tử độ lệch (&lt;em&gt;bias&lt;/em&gt;) cho phép dịch chuyển biên quyết định ra khỏi gốc tọa độ. Quy tắc học minh họa cách cập nhật tham số dựa trên sai số dự đoán. Quan trọng hơn cả, hạn chế căn bản của perceptron — không thể giải các bài toán không tách tuyến tính như XOR — đã trực tiếp thúc đẩy sự ra đời của mạng nhiều lớp và các kiến trúc sâu trong học sâu hiện đại.&lt;/p&gt;

&lt;p&gt;Bước chuyển từ perceptron sang neuron nhân tạo hiện đại nằm ở việc thay thế hàm bước cứng bằng các hàm kích hoạt trơn và khả vi. Thay đổi tưởng chừng nhỏ này lại có tác động rất lớn: hàm kích hoạt trơn cho phép tối ưu dựa trên gradient thông qua lan truyền ngược (&lt;em&gt;backpropagation&lt;/em&gt;), từ đó huấn luyện được mạng nhiều lớp. Đồng thời, chúng bổ sung tính phi tuyến cần thiết để mạng neuron xấp xỉ các hàm phức tạp. Việc lựa chọn hàm kích hoạt ảnh hưởng trực tiếp đến tốc độ hội tụ cũng như khả năng biểu diễn dữ liệu, khiến đây trở thành một quyết định kiến trúc quan trọng trong học sâu.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Blausen_0657_MultipolarNeuron.png/500px-Blausen_0657_MultipolarNeuron.png&quot; alt=&quot;Biological vs Artificial Neuron&quot; /&gt;
&lt;em&gt;Hình ảnh: Neuron sinh học (trái) đã truyền cảm hứng cho neuron nhân tạo. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Perceptron thực hiện một phép tính khá đơn giản, nhưng công thức toán học của nó làm rõ bản chất của bộ phân loại tuyến tính và biên quyết định. Cho vector đầu vào \(\mathbf{x} = (x_1, x_2, \ldots, x_n)\) với mỗi \(x_i\) là một đặc trưng, và vector trọng số tương ứng \(\mathbf{w} = (w_1, w_2, \ldots, w_n)\), perceptron trước hết tính tổng có trọng số:&lt;/p&gt;

\[z = \sum_{i=1}^{n} w_i x_i + b = \mathbf{w}^T \mathbf{x} + b\]

&lt;p&gt;Đại lượng \(z\), thường gọi là giá trị tiền kích hoạt (&lt;em&gt;pre-activation&lt;/em&gt;) hoặc logit, biểu diễn tổ hợp tuyến tính của các đầu vào. Mỗi trọng số \(w_i\) quyết định mức độ ảnh hưởng của đặc trưng \(x_i\) tới kết quả cuối cùng. Hạng tử độ lệch \(b\) đóng vai trò như một ngưỡng dịch chuyển, giúp đặt biên quyết định ở vị trí phù hợp trong không gian đầu vào thay vì buộc phải đi qua gốc tọa độ.&lt;/p&gt;

&lt;p&gt;Tiếp theo, perceptron áp dụng hàm bước Heaviside lên tổ hợp tuyến tính này để tạo ra đầu ra nhị phân:&lt;/p&gt;

\[y = H(z) = \begin{cases} 
1 &amp;amp; \text{if } z \geq 0 \\
0 &amp;amp; \text{if } z &amp;lt; 0
\end{cases}\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/heaviside_step_function.jpg&quot; alt=&quot;Đồ thị hàm bước Heaviside&quot; /&gt;
&lt;em&gt;Hình: Hàm bước Heaviside \(H(x)\) — đầu ra chỉ nhận giá trị \(0\) hoặc \(1\). (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Hàm bước tạo ra một biên quyết định sắc nét: mọi điểm ở một phía được gán nhãn dương (1), phía còn lại được gán nhãn âm (0). Về mặt hình học, các trọng số xác định một siêu phẳng (&lt;em&gt;hyperplane&lt;/em&gt;) trong không gian đầu vào theo phương trình \(\mathbf{w}^T \mathbf{x} + b = 0\), và các điểm dữ liệu được phân loại tùy theo phía của siêu phẳng mà chúng nằm trên đó.&lt;/p&gt;

&lt;p&gt;Vector trọng số \(\mathbf{w}\) vuông góc (trực giao) với siêu phẳng quyết định. Có thể thấy ngay điều này: nếu hai điểm \(\mathbf{x}_1\) và \(\mathbf{x}_2\) cùng nằm trên siêu phẳng thì \(\mathbf{w}^T(\mathbf{x}_1 - \mathbf{x}_2) = 0\), chứng tỏ \(\mathbf{w}\) trực giao với mọi vector nằm trong siêu phẳng. Độ lớn của \(\mathbf{w}\) quyết định tốc độ biến thiên của \(z\) khi di chuyển theo phương vuông góc với siêu phẳng, còn độ lệch \(b\) điều khiển khoảng cách từ siêu phẳng tới gốc tọa độ dọc theo hướng \(\mathbf{w}\).&lt;/p&gt;

&lt;p&gt;Thuật toán học perceptron đưa ra cách đơn giản để tìm bộ trọng số phù hợp khi dữ liệu tách tuyến tính được. Bắt đầu từ các trọng số khởi tạo (thường bằng 0 hoặc giá trị ngẫu nhiên nhỏ), thuật toán duyệt qua từng mẫu huấn luyện \((\mathbf{x}_i, y_i)\). Nếu dự đoán đúng, trọng số được giữ nguyên; nếu phân loại sai, thuật toán cập nhật theo công thức:&lt;/p&gt;

\[\mathbf{w} \leftarrow \mathbf{w} + \eta (y_i - \hat{y}_i) \mathbf{x}_i\]

\[b \leftarrow b + \eta (y_i - \hat{y}_i)\]

&lt;p&gt;Trong đó, \(\eta\) là tốc độ học (&lt;em&gt;learning rate&lt;/em&gt;) điều chỉnh kích thước bước cập nhật, còn \((y_i - \hat{y}_i)\) là sai số. Khi nhãn thật là 1 nhưng mô hình dự đoán 0, sai số bằng +1 nên trọng số được dịch chuyển theo hướng của \(\mathbf{x}_i\), làm tăng khả năng mẫu này được phân vào lớp 1 ở các lần sau. Ngược lại, khi dự đoán 1 nhưng nhãn thật là 0, trọng số được dịch ra xa \(\mathbf{x}_i\). Trực giác hình học này — xoay và dịch biên quyết định để phân tách đúng các điểm dữ liệu — là nền tảng của nhiều thuật toán học máy.&lt;/p&gt;

&lt;p&gt;Định lý Hội tụ Perceptron đảm bảo rằng nếu tập dữ liệu huấn luyện tách tuyến tính được, thuật toán sẽ tìm ra siêu phẳng phân tách sau hữu hạn bước. Tuy nhiên, định lý này cũng bộc lộ giới hạn căn bản của perceptron: nó không thể giải quyết các bài toán mà hai lớp không tách tuyến tính được. Ví dụ kinh điển là hàm XOR, nơi các điểm lớp dương và lớp âm nằm xen kẽ nhau khiến không tồn tại đường thẳng (hay siêu phẳng ở không gian nhiều chiều) nào phân tách được chúng. Hạn chế này là một trong những nguyên nhân dẫn đến “mùa đông AI” đầu tiên vào thập niên 1970, khi người ta nhận ra perceptron một lớp không đủ khả năng giải nhiều bài toán thực tế.&lt;/p&gt;

&lt;p&gt;Neuron nhân tạo hiện đại khắc phục hạn chế đó trong khi vẫn giữ lại phép tính cốt lõi là tổng có trọng số. Thay cho hàm bước, ta sử dụng một hàm kích hoạt trơn \(\sigma\):&lt;/p&gt;

\[a = \sigma\left(\sum_{i=1}^{n} w_i x_i + b\right) = \sigma(\mathbf{w}^T \mathbf{x} + b)\]

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Gjl-t%28x%29.svg/500px-Gjl-t%28x%29.svg.png&quot; alt=&quot;Activation Functions&quot; /&gt;
&lt;em&gt;Hình ảnh: Các hàm kích hoạt phổ biến (Sigmoid, Tanh, ReLU). Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Cách chọn hàm \(\sigma\) tác động lớn đến hành vi của neuron. Hàm sigmoid \(\sigma(z) = \frac{1}{1+e^{-z}}\) chuyển tiếp mượt giữa 0 và 1, cho phép diễn giải như xác suất và quan trọng nhất là khả vi tại mọi điểm. Hàm tang hyperbolic \(\tanh(z)\) nhận giá trị trong khoảng \((-1, 1)\) và đối xứng quanh 0, thường giúp luồng gradient ổn định hơn. Đơn vị tuyến tính chỉnh lưu (ReLU), định nghĩa là \(\max(0, z)\), trở thành lựa chọn phổ biến nhất trong học sâu hiện đại vì tính toán nhanh, không bị bão hòa ở miền dương (giảm hiện tượng gradient biến mất) và tạo ra biểu diễn thưa khi các đầu vào âm đều cho đầu ra bằng 0.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ--trực-giác&quot;&gt;3. Ví dụ / Trực giác&lt;/h2&gt;

&lt;h3 id=&quot;31-trực-giác-hình-học-từ-1d-đến-3d&quot;&gt;3.1. Trực giác hình học: từ 1D đến 3D&lt;/h3&gt;

&lt;p&gt;Trước khi quay lại bài toán AND và XOR, hãy hình dung perceptron như một &lt;strong&gt;ranh giới&lt;/strong&gt; trong không gian đầu vào.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Một chiều (ví dụ nhiệt độ):&lt;/strong&gt; Neuron nhận một giá trị \(x\) (độ C). Trọng số và độ lệch xác định một ngưỡng — chẳng hạn tại \(20\): một phía là trạng thái &lt;em&gt;Inactive&lt;/em&gt;, phía kia là &lt;em&gt;Active&lt;/em&gt;. Perceptron chỉ thực hiện việc bật hoặc tắt tùy thuộc đầu vào nằm bên nào của ngưỡng.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/perceptron_1d_threshold.jpg&quot; alt=&quot;Ranh giới 1D: Inactive vs Active&quot; /&gt;
&lt;em&gt;Hình: Perceptron 1D đặt ranh giới (ví dụ tại vị trí 20) trên trục Input Space. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Khi đổi &lt;strong&gt;dấu của trọng số&lt;/strong&gt;, vùng kích hoạt sẽ đảo ngược. Ví dụ, \(\hat{y} = H(-x + 20)\) kích hoạt khi \(x\) nhỏ (vùng &lt;em&gt;Active&lt;/em&gt; nằm bên trái ngưỡng 20).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/perceptron_1d_weight_sign.jpg&quot; alt=&quot;Đảo ranh giới bằng dấu weight&quot; /&gt;
&lt;em&gt;Hình: \(\hat{y}=H(-x+20)\) — trọng số âm đảo ngược vùng Active và Inactive. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hai chiều (ví dụ Temp và Humidity):&lt;/strong&gt; Với hai đặc trưng, biên quyết định trở thành một &lt;strong&gt;đường thẳng&lt;/strong&gt; trên mặt phẳng. Các điểm thuộc hai lớp nằm về hai phía của đường thẳng (đường màu vàng trong hình dưới).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/perceptron_2d_decision_boundary.jpg&quot; alt=&quot;Biên quyết định 2D&quot; /&gt;
&lt;em&gt;Hình: Perceptron hai đầu vào (Temp, Humidity) và đường phân tách tuyến tính trên mặt phẳng. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Ta có thể viết gọn phép tính dưới dạng vector/ma trận:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/perceptron_vector_form.jpg&quot; alt=&quot;Dạng vector của perceptron&quot; /&gt;
&lt;em&gt;Hình: \(\hat{y}=H(w_1x_1+w_2x_2+b)=H(\mathbf{W}\mathbf{x}+b)\). (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ba chiều trở lên:&lt;/strong&gt; Khi thêm đặc trưng thứ ba (ví dụ Wind Speed), biên quyết định mở rộng thành một &lt;strong&gt;siêu phẳng&lt;/strong&gt; trong không gian đầu vào:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/perceptron_3d_hyperplane.jpg&quot; alt=&quot;Siêu phẳng quyết định 3D&quot; /&gt;
&lt;em&gt;Hình: Ba đầu vào (Temp, Humidity, Wind Speed) và siêu phẳng phân loại trong không gian 3D. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/linearly_separable.jpg&quot; alt=&quot;Dữ liệu tách tuyến tính được&quot; /&gt;
&lt;em&gt;Hình: Hai lớp tách tuyến tính được (&lt;/em&gt;linearly separable&lt;em&gt;) — chỉ cần một đường thẳng để phân tách. Khi dữ liệu không tách tuyến tính được, cần bổ sung tính phi tuyến và nhiều lớp. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;32-ví-dụ-logic-and-và-xor&quot;&gt;3.2. Ví dụ logic: AND và XOR&lt;/h3&gt;

&lt;p&gt;Để hiểu rõ hơn cách perceptron vận hành, hãy xét một ví dụ cụ thể cho thấy cả ưu điểm lẫn giới hạn của nó: hàm logic AND, chỉ trả về 1 khi cả hai đầu vào đều bằng 1. Dù bài toán này đơn giản, việc một mô hình có thể tự học quan hệ logic chỉ từ các ví dụ đã là một bước tiến quan trọng vào thời điểm đó.&lt;/p&gt;

&lt;p&gt;Giả sử ta muốn perceptron học hàm AND từ bốn mẫu: \((0,0) \to 0\), \((0,1) \to 0\), \((1,0) \to 0\), \((1,1) \to 1\). Khởi tạo \(w_1 = 0, w_2 = 0, b = 0\) và chọn tốc độ học \(\eta = 1\). Với mẫu đầu tiên \((0,0)\) có nhãn 0, mô hình dự đoán \(H(0 \cdot 0 + 0 \cdot 0 + 0) = H(0) = 1\), bị sai. Sai số là \(0 - 1 = -1\), nên ta cập nhật: \(w_1 \leftarrow 0 + 1 \cdot (-1) \cdot 0 = 0\), \(w_2 \leftarrow 0\), \(b \leftarrow 0 + 1 \cdot (-1) = -1\). Lúc này độ lệch đã trở thành -1, tạo ra một ngưỡng kích hoạt.&lt;/p&gt;

&lt;p&gt;Tiếp tục lặp qua các mẫu huấn luyện, perceptron sẽ hội tụ về một bộ tham số chẳng hạn như \(w_1 = 1, w_2 = 1, b = -1.5\). Kiểm tra lại: với đầu vào \((1,1)\), ta có \(z = 1 \cdot 1 + 1 \cdot 1 - 1.5 = 0.5\), suy ra \(H(0.5) = 1\) ✓. Với \((1,0)\), ta có \(z = 1 \cdot 1 + 1 \cdot 0 - 1.5 = -0.5\), suy ra \(H(-0.5) = 0\) ✓. Như vậy, perceptron đã học được quy tắc rằng cả hai đầu vào phải cùng bằng 1 để tổng vượt ngưỡng 1.5.&lt;/p&gt;

&lt;p&gt;Bây giờ hãy xét vì sao một perceptron đơn lẻ không thể giải bài toán XOR. Hàm XOR trả về 1 khi hai đầu vào khác nhau: \((0,0) \to 0\), \((0,1) \to 1\), \((1,0) \to 1\), \((1,1) \to 0\). Khi biểu diễn bốn điểm này trên mặt phẳng 2D, hai mẫu dương \((0,1)\) và \((1,0)\) nằm trên một đường chéo, còn hai mẫu âm \((0,0)\) và \((1,1)\) nằm trên đường chéo kia. Không có đường thẳng nào có thể tách riêng hai nhóm này — ta cần một biên quyết định phi tuyến, chẳng hạn một đường cong hoặc tổ hợp nhiều đoạn thẳng. Giới hạn hình học này cho thấy một mô hình tuyến tính một lớp không thể biểu diễn mọi quan hệ logic.&lt;/p&gt;

&lt;p&gt;Chính hạn chế này đã thúc đẩy sự phát triển của mạng nhiều lớp. Nếu xếp hai perceptron ở lớp đầu rồi nối đầu ra của chúng vào một perceptron thứ ba ở lớp sau, ta có thể giải được XOR: lớp đầu học cách phát hiện \(x_1 \text{ OR } x_2\) và \(x_1 \text{ AND } x_2\), còn lớp thứ hai học quy tắc “OR nhưng không AND”, tức là đúng bằng XOR. Ví dụ này minh họa một nguyên lý cốt lõi: tăng độ sâu (nhiều lớp) cho phép mạng học các biên quyết định phức tạp hơn. Mỗi lớp mới kết hợp các đặc trưng từ lớp trước theo những cách mới, mở rộng mạnh mẽ tập các hàm mà mạng có thể biểu diễn.&lt;/p&gt;

&lt;p&gt;Sự liên hệ với sinh học, dù chỉ mang tính gần đúng, vẫn đem lại trực giác hữu ích. Neuron sinh học trong não nhận tín hiệu qua sợi nhánh (&lt;em&gt;dendrite&lt;/em&gt;), tổng hợp tín hiệu tại thân tế bào (&lt;em&gt;soma&lt;/em&gt;), và phát xung điện thế hoạt động dọc theo sợi trục (&lt;em&gt;axon&lt;/em&gt;) khi tín hiệu vượt ngưỡng. Độ mạnh của khớp nối synapse tương ứng với trọng số — synapse càng mạnh thì ảnh hưởng tới việc neuron có phát xung hay không càng lớn. Tuy nhiên, không nên diễn giải phép ẩn dụ này quá sát nghĩa. Neuron sinh học phức tạp hơn rất nhiều, với các cơ chế hóa sinh, quá trình xử lý trên sợi nhánh và động lực học theo thời gian mà mô hình tổng có trọng số đơn giản không thể tái hiện. Neuron nhân tạo là một mô hình toán học và kỹ thuật lấy cảm hứng từ sinh học, chứ không phải bản mô phỏng chính xác hoạt động của não bộ.&lt;/p&gt;

&lt;h2 id=&quot;4-đoạn-mã&quot;&gt;4. Đoạn Mã&lt;/h2&gt;

&lt;p&gt;Dưới đây là cài đặt của cả perceptron cổ điển và neuron hiện đại để so sánh điểm giống và khác nhau giữa chúng. Trước tiên là phiên bản NumPy cho perceptron cổ điển nhằm thể hiện rõ quá trình cập nhật trọng số:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Perceptron cổ điển với kích hoạt hàm bước&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Khởi tạo perceptron với trọng số ngẫu nhiên nhỏ.
        
        Vì sao trọng số ngẫu nhiên nhỏ? Cần phá đối xứng - nếu mọi trọng số
        khởi đầu bằng nhau, mọi neuron học cùng đặc trưng. Giá trị nhỏ đảm bảo
        ta bắt đầu trong vùng gradient (với kích hoạt trơn) có ý nghĩa.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Bắt đầu bằng không cho perceptron cổ điển (đơn giản và hiệu quả với dữ liệu tách tuyến tính)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;errors_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Theo dõi sai số mỗi epoch để chẩn đoán
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;activation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Hàm bước Heaviside: cho ra 1 nếu z &amp;gt;= 0, ngược lại 0
        
        Tạo biên quyết định sắc nét. Mọi thứ trên ngưỡng được phân lớp 1,
        dưới ngưỡng là 0. Bản chất tất-cả-hoặc-không-gì vừa là sức mạnh
        (quyết định rõ) vừa là điểm yếu của perceptron
        (không khả vi, không dùng được gradient descent).
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Đưa ra dự đoán cho đầu vào X.
        
        Phép tính X @ weights là tích ma trận-vectơ theo batch.
        Với mỗi mẫu (hàng của X), ta tính tích vô hướng với trọng số,
        cộng độ lệch, và áp dụng kích hoạt. Cách vectorized này nhanh hơn
        lặp qua các mẫu nhiều bậc độ lớn.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;activation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Huấn luyện perceptron bằng quy tắc học perceptron.
        
        Vì sao điều này hoạt động? Quy tắc học perceptron có diễn giải
        hình học đẹp: khi phân loại sai một điểm, ta điều chỉnh biên quyết định
        tiến về điểm đó (nếu phải dương) hoặc ra xa (nếu phải âm). Với dữ liệu
        tách tuyến tính, quá trình này được đảm bảo hội tụ.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;errors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
                &lt;span class=&quot;c1&quot;&gt;# Tính dự đoán
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;activation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                
                &lt;span class=&quot;c1&quot;&gt;# Chỉ cập nhật nếu dự đoán sai
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                    &lt;span class=&quot;c1&quot;&gt;# Quy tắc cập nhật: w ← w + η(y - ŷ)x
&lt;/span&gt;                    &lt;span class=&quot;c1&quot;&gt;# Khi y=1, ŷ=0: error=+1, tiến về x (tăng tích vô hướng)
&lt;/span&gt;                    &lt;span class=&quot;c1&quot;&gt;# Khi y=0, ŷ=1: error=-1, ra xa x (giảm tích vô hướng)
&lt;/span&gt;                    &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;errors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;errors_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;errors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Dừng sớm nếu hội tụ
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;errors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Converged at iteration &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Minh họa học hàm AND
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Perceptron on AND gate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_and&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_and&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_and&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_and&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Learned weights: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Learned bias: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_and&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True labels:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_and&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Decision boundary equation: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;*x1 + &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;*x2 + &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; = 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Minh họa bất khả XOR
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Attempting to learn XOR (will fail!)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;perceptron_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;perceptron_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;predictions_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;perceptron_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions_xor&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True labels:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_xor&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Errors remaining: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;errors_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Note: Perceptron cannot solve XOR because it&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s not linearly separable!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Tiếp theo là cài đặt neuron hiện đại bằng PyTorch với các hàm kích hoạt trơn, cho phép huấn luyện dựa trên gradient:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ModernNeuron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Neuron nhân tạo hiện đại với hàm kích hoạt trơn.
    
    Khác biệt then chốt so với perceptron là hàm kích hoạt.
    Thay vì hàm bước chỉ 0 hoặc 1, ta dùng hàm trơn có thể
    cho ra mọi giá trị trong một khoảng và, then chốt, khả vi.
    Tính khả vi này cho phép lan truyền ngược và gradient descent.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ModernNeuron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Lớp tuyến tính: y = Wx + b
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# PyTorch mặc định khởi tạo bằng Kaiming uniform,
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# được thiết kế cho kích hoạt ReLU
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linear&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Chọn hàm kích hoạt
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Mỗi hàm có tính chất và trường hợp dùng khác nhau
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# ReLU: max(0, z) - phổ biến nhất, ngăn gradient biến mất
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Sigmoid: 1/(1+e^(-z)) - đầu ra [0,1], tốt cho xác suất
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Tanh: (e^z - e^(-z))/(e^z + e^(-z)) - đầu ra [-1,1], tâm không
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Tuyến tính: f(z) = z - cho hồi quy
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Identity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Lan truyền xuôi qua neuron.
        
        Phép tính giống perceptron (tổng có trọng số + độ lệch)
        nhưng ta áp dụng hàm kích hoạt trơn. Tính trơn này then chốt:
        thay đổi nhỏ của trọng số gây thay đổi nhỏ của đầu ra,
        cho phép gradient descent hoạt động hiệu quả.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Tổ hợp tuyến tính: z = w^T x + b
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;activation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Áp dụng kích hoạt phi tuyến
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Minh họa neuron hiện đại có thể học XOR với nhiều lớp
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TwoLayerNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Mạng hai lớp CÓ THỂ giải XOR.
    
    Minh họa vì sao độ sâu quan trọng: lớp đầu tạo không gian biểu diễn
    mới trong đó XOR trở nên tách tuyến tính, và lớp thứ hai sau đó
    có thể tách bằng biên tuyến tính.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TwoLayerNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Lớp đầu tạo đặc trưng phi tuyến
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Lớp thứ hai kết hợp các đặc trưng này
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện trên XOR
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training 2-Layer Network on XOR&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_xor_torch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_xor_torch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TwoLayerNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BCELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Binary Cross-Entropy
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vòng lặp huấn luyện
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Lan truyền xuôi
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_xor_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Lan truyền ngược
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Kiểm tra mô hình đã học
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;final_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;binary_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;final_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Final Predictions (probabilities):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;final_predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_xor_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Input &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; → Pred: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, True: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Classified as: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;binary_predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Success! The network learned XOR, something a single perceptron cannot do.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This demonstrates why depth (multiple layers) is fundamental to neural networks.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Ta cũng có thể so sánh trực tiếp cách các hàm kích hoạt khác nhau tác động lên cùng một tập giá trị đầu vào:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# So sánh các hàm kích hoạt
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;relu_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sigmoid_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;tanh_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Activation Function Characteristics&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;For z = -2.0:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ReLU:    &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (zero for negative)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Sigmoid: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (near 0, but not exactly)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tanh:    &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (negative output)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;For z = 2.0:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ReLU:    &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (linear for positive)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Sigmoid: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (approaching 1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tanh:    &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (approaching 1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Key observations:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - ReLU: Outputs exactly zero for negative inputs, creates sparsity&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Sigmoid: Always positive, good for probabilities but can saturate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Tanh: Zero-centered (outputs can be negative), better gradient flow than sigmoid&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Lý do ReLU trở nên phổ biến rộng rãi nằm ở đặc tính của đạo hàm. Với sigmoid hoặc tanh, khi đầu vào có độ lớn cao (dương hoặc âm), độ dốc trở nên rất nhỏ. Hiện tượng bão hòa này làm gradient suy giảm nhanh khi truyền ngược qua nhiều lớp, gây khó khăn cho việc huấn luyện mạng sâu. Ngược lại, ReLU không bị bão hòa ở miền dương — đạo hàm luôn bằng 1 — giúp gradient truyền qua nhiều lớp mà không bị suy giảm. Tính chất này đóng vai trò quan trọng giúp huấn luyện được các mạng sâu hơn nhiều trong thập niên 2010.&lt;/p&gt;

&lt;p&gt;Tuy vậy, ReLU cũng có nhược điểm riêng là hiện tượng “ReLU chết” (&lt;em&gt;dying ReLU&lt;/em&gt;). Nếu đầu vào của một neuron luôn mang giá trị âm trong quá trình huấn luyện, đầu ra và đạo hàm của nó đều bằng 0, khiến trọng số không còn được cập nhật nữa. Tình trạng này thường xảy ra khi khởi tạo kém hoặc tốc độ học quá lớn. Các biến thể như Leaky ReLU (\(\max(\alpha z, z)\) với \(\alpha \approx 0.01\)) khắc phục điểm yếu này bằng cách giữ lại một độ dốc nhỏ ở miền âm, đảm bảo gradient không triệt tiêu hoàn toàn.&lt;/p&gt;

&lt;h2 id=&quot;5-các-khái-niệm-liên-quan&quot;&gt;5. Các Khái niệm Liên quan&lt;/h2&gt;

&lt;p&gt;Đặt perceptron và neuron nhân tạo trong bức tranh chung của học máy sẽ giúp thấy rõ mối liên hệ giữa các phương pháp. Nếu thay hàm bước trong perceptron bằng hàm kích hoạt sigmoid, ta thu được đúng mô hình hồi quy logistic (&lt;em&gt;logistic regression&lt;/em&gt;), trong đó xác suất thuộc lớp dương được mô hình hóa là \(P(y=1 \mid \mathbf{x}) = \sigma(\mathbf{w}^T \mathbf{x} + b)\). Hồi quy logistic thường được huấn luyện theo ước lượng hợp lý cực đại (&lt;em&gt;maximum likelihood estimation&lt;/em&gt;), tương đương với việc cực tiểu hóa hàm mất mát entropy chéo nhị phân (&lt;em&gt;binary cross-entropy&lt;/em&gt;). Đây cũng chính là hàm mất mát tiêu chuẩn cho lớp đầu ra của mạng neuron trong bài toán phân loại nhị phân.&lt;/p&gt;

&lt;p&gt;So sánh với máy vector hỗ trợ (&lt;em&gt;Support Vector Machine&lt;/em&gt; — SVM) cũng giúp làm sáng tỏ thêm bản chất của perceptron. Cả hai đều tìm siêu phẳng phân tách cho dữ liệu tách tuyến tính. Tuy nhiên, SVM tối ưu siêu phẳng có lề cực đại (&lt;em&gt;maximum-margin hyperplane&lt;/em&gt;) — tức siêu phẳng nằm xa các điểm dữ liệu gần nhất của cả hai lớp nhất có thể, qua đó mang lại đảm bảo lý thuyết tốt hơn về khả năng khái quát hóa. Ngược lại, perceptron dừng lại ở bất kỳ siêu phẳng phân tách nào tìm được mà không tối ưu lề. Dù SVM có lợi thế về mặt lý thuyết ở trường hợp tuyến tính, mạng neuron sâu xây từ các đơn vị kiểu perceptron lại linh hoạt hơn với dữ liệu phức tạp, nhiều chiều vì có thể tự học các đặc trưng phi tuyến qua nhiều lớp.&lt;/p&gt;

&lt;p&gt;Bước tiến từ perceptron đơn lẻ sang mạng perceptron nhiều lớp (&lt;em&gt;Multi-Layer Perceptron&lt;/em&gt; — MLP) là một cột mốc quan trọng của học máy. MLP xếp chồng nhiều lớp neuron nối tiếp nhau, đầu ra của lớp trước làm đầu vào cho lớp sau, giúp mạng học biểu diễn phân cấp (&lt;em&gt;hierarchical representation&lt;/em&gt;). Chẳng hạn, lớp đầu phát hiện các mẫu đơn giản (như cạnh trong ảnh hoặc cụm từ ngắn trong văn bản), lớp giữa kết hợp chúng thành các đặc trưng mức trung bình (như hình dạng hoặc ngữ nghĩa cụm từ), còn các lớp sâu hơn tổng hợp thành khái niệm ở mức trừu tượng cao hơn. Khả năng học phân cấp này là đặc trưng cốt lõi giúp mạng neuron sâu vượt qua giới hạn của perceptron một lớp.&lt;/p&gt;

&lt;p&gt;Sự tương đồng với hệ thần kinh sinh học cũng gợi ý vì sao biểu diễn phân tán (&lt;em&gt;distributed representation&lt;/em&gt;) lại hiệu quả. Trong não, thông tin và khái niệm không được lưu ở một neuron đơn lẻ mà phân bố trên mẫu kích hoạt của nhiều neuron. Tương tự, trong mạng neuron nhân tạo, biểu diễn được trải đều trên nhiều đơn vị. Cơ chế này mang lại tính bền vững — nếu một vài neuron bị tắt (chẳng hạn khi dùng dropout), mạng vẫn duy trì được hoạt động. Đồng thời, nó cho phép biểu diễn số lượng khái niệm rất lớn chỉ với số lượng neuron tăng tuyến tính.&lt;/p&gt;

&lt;p&gt;Cuối cùng, nhu cầu sử dụng hàm kích hoạt trơn gắn chặt với bài toán tối ưu hóa. Thuật toán huấn luyện chủ đạo của mạng neuron là gradient descent, vốn đòi hỏi đạo hàm có nghĩa. Đạo hàm của hàm bước bằng 0 hầu như khắp nơi và không xác định tại ngưỡng, khiến tối ưu theo gradient không thể thực hiện. Các hàm kích hoạt trơn như sigmoid, tanh hay ReLU cung cấp tín hiệu đạo hàm dẫn đường cho quá trình cập nhật tham số. Lựa chọn hàm kích hoạt ảnh hưởng trực tiếp đến độ lớn gradient và tốc độ học giữa các lớp, đặc biệt quan trọng khi mạng có nhiều lớp sâu.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các Bài báo Nền tảng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://psycnet.apa.org/record/1959-09865-001&quot;&gt;“The Perceptron: A Probabilistic Model for Information Storage and Organization in the Brain” (1958)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Frank Rosenblatt&lt;br /&gt;
Bài báo nền tảng này giới thiệu mô hình perceptron và chứng minh rằng một neuron nhân tạo đơn giản có thể tự học từ ví dụ. Rosenblatt vừa trình bày tính chất hội tụ về mặt lý thuyết, vừa xây dựng phần cứng thực tế có khả năng nhận dạng mẫu. Công trình này tạo nên làn sóng kỳ vọng lớn cho lĩnh vực trí tuệ nhân tạo, trước khi những hạn chế của nó được phân tích kỹ hơn về sau. Giá trị lịch sử của bài báo nằm không chỉ ở bản thân thuật toán mà còn ở việc đặt nền móng cho tư duy học từ dữ liệu trong học máy hiện đại.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://mitpress.mit.edu/books/perceptrons&quot;&gt;“Perceptrons: An Introduction to Computational Geometry” (1969)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Marvin Minsky và Seymour Papert&lt;br /&gt;
Cuốn sách kinh điển này (không có trên arXiv) phân tích chặt chẽ các giới hạn toán học của perceptron, chứng minh rằng perceptron một lớp không thể giải các bài toán như XOR. Những phân tích nghiêm ngặt và kết luận thận trọng của tác phẩm đã góp phần làm giảm mạnh nguồn tài trợ nghiên cứu mạng neuron trong hơn một thập niên, mở đầu mùa đông AI lần thứ nhất. Thực tế, Minsky và Papert có đề cập rằng mạng nhiều lớp có thể vượt qua hạn chế này, nhưng khi đó thuật toán huấn luyện phù hợp (lan truyền ngược) chưa được phổ biến. Tác phẩm đến nay vẫn có giá trị trong việc tìm hiểu nền tảng toán học của bộ phân loại tuyến tính cũng như lịch sử phát triển của mạng neuron.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.nature.com/articles/323533a0&quot;&gt;“Learning representations by back-propagating errors” (1986)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: David E. Rumelhart, Geoffrey E. Hinton, Ronald J. Williams&lt;br /&gt;
Bài báo này khơi dậy trở lại nghiên cứu mạng neuron bằng cách trình bày cách huấn luyện mạng nhiều lớp thông qua thuật toán lan truyền ngược. Ý tưởng cốt lõi là áp dụng quy tắc dây chuyền để tính gradient theo từng lớp, nhờ đó phân bổ sai số cho mọi trọng số trong mạng chứ không chỉ ở lớp đầu ra. Nhờ vậy, mạng nhiều lớp có thể học được XOR và nhiều bài toán phi tuyến mà perceptron đơn lẻ không giải được, mở đường cho sự phát triển của học sâu hiện đại.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://proceedings.mlr.press/v15/glorot11a.html&quot;&gt;“Deep Sparse Rectifier Neural Networks” (2011)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Xavier Glorot, Antoine Bordes, Yoshua Bengio&lt;br /&gt;
Bài báo giới thiệu Rectified Linear Unit (ReLU) như một hàm kích hoạt hiệu quả hơn cho mạng sâu và chứng minh bằng thực nghiệm ưu thế của nó so với sigmoid và tanh. Các tác giả chỉ ra rằng ReLU giúp giảm hiện tượng gradient biến mất, tính toán đơn giản (chỉ gồm phép lấy cực đại) và tạo ra biểu diễn thưa khi nhiều neuron có đầu ra bằng 0. Việc áp dụng rộng rãi ReLU là một trong những yếu tố then chốt giúp huấn luyện thành công các mạng có hàng chục đến hàng trăm lớp.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1502.01852&quot;&gt;“Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả&lt;/em&gt;: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun&lt;br /&gt;
Bài báo giới thiệu PReLU (Parametric ReLU, trong đó độ dốc ở miền âm là tham số học được) cùng phương pháp khởi tạo He thiết kế riêng cho mạng dùng ReLU. Nghiên cứu cho thấy với cách khởi tạo phù hợp, mạng rất sâu (22 lớp vào thời điểm công bố) không chỉ huấn luyện ổn định mà còn vượt qua mức hiệu năng của con người trên bài toán phân loại ImageNet. Khởi tạo He sử dụng độ lệch chuẩn \(\sqrt{2/n_{in}}\) (tương ứng phương sai \(2/n_{in}\)) thay vì \(\sqrt{1/n_{in}}\) của khởi tạo Xavier, nhằm bù trừ việc ReLU triệt tiêu trung bình một nửa số neuron và giữ cho thang đo kích hoạt cũng như gradient ổn định qua các lớp sâu.&lt;/p&gt;

&lt;h2 id=&quot;cạm-bẫy-và-mẹo-thường-gặp&quot;&gt;Cạm bẫy và Mẹo Thường gặp&lt;/h2&gt;

&lt;p&gt;Một sai lầm phổ biến khi cài đặt mạng neuron là khởi tạo tất cả trọng số bằng cùng một giá trị, đặc biệt là bằng 0. Ý tưởng bắt đầu từ trạng thái “trung tính” nghe có vẻ hợp lý nhưng lại gây ra hiện tượng đối xứng (&lt;em&gt;symmetry problem&lt;/em&gt;): nếu mọi neuron trong cùng một lớp có trọng số giống hệt nhau, chúng sẽ nhận gradient như nhau khi lan truyền ngược và cập nhật giống hệt nhau trong suốt quá trình huấn luyện. Khi đó, một lớp gồm 100 neuron cũng chỉ học được đúng một đặc trưng như một neuron đơn lẻ. Khởi tạo ngẫu nhiên giúp phá vỡ tính đối xứng này để từng neuron phát triển theo hướng riêng.&lt;/p&gt;

&lt;p&gt;Thang đo khởi tạo trọng số cũng quan trọng không kém. Nếu trọng số khởi tạo quá lớn, kích hoạt dễ rơi vào vùng bão hòa (với sigmoid/tanh) hoặc tăng bùng nổ qua các lớp, kéo theo gradient bùng nổ và làm quá trình huấn luyện mất ổn định. Ngược lại, nếu trọng số quá nhỏ, kích hoạt và gradient sẽ co dần về 0 qua các lớp, khiến mạng sâu học rất chậm. Giải pháp là điều chỉnh phương sai khởi tạo theo số chiều đầu vào của lớp: khởi tạo Xavier (\(\mathcal{N}(0, 1/n_{in})\)) phù hợp với sigmoid và tanh, còn khởi tạo He (\(\mathcal{N}(0, 2/n_{in})\)) được thiết kế cho ReLU để bù lại việc triệt tiêu đầu vào âm.&lt;/p&gt;

&lt;p&gt;Hiện tượng ReLU chết là một lỗi thường gặp trong thực tế. Khi giá trị tiền kích hoạt của một neuron ReLU luôn âm, cả đầu ra lẫn gradient của nó đều bằng 0 nên trọng số không thể cập nhật thêm. Nguyên nhân có thể do khởi tạo chưa phù hợp, tốc độ học quá cao gây ra bước nhảy lớn đẩy neuron sang miền âm, hoặc do đặc điểm lệch trong dữ liệu. Một khi đã rơi vào trạng thái này, neuron thường không tự phục hồi trong lần huấn luyện đó. Để theo dõi, ta có thể kiểm tra tỷ lệ neuron luôn xuất ra 0; nếu tỷ lệ này vượt 20–30%, cần xem lại cấu hình huấn luyện. Các biện pháp khắc phục gồm chuyển sang Leaky ReLU, giảm tốc độ học, chọn cách khởi tạo phù hợp hoặc áp dụng batch normalization (sẽ học ở các chương sau) để ổn định phân phối kích hoạt.&lt;/p&gt;

&lt;p&gt;Một kỹ thuật đơn giản nhưng hữu ích là khởi tạo độ lệch của neuron ReLU bằng một giá trị dương nhỏ (chẳng hạn 0.01) trong khi vẫn khởi tạo ngẫu nhiên các trọng số. Cách làm này giúp đa số neuron ở trạng thái hoạt động ngay từ đầu thay vì lập tức rơi vào vùng bằng 0, tạo điều kiện cho chúng bắt đầu học trước khi có nguy cơ bị chết.&lt;/p&gt;

&lt;p&gt;Cuối cùng, hiểu ý nghĩa hình học của trọng số sẽ hỗ trợ đáng kể cho việc gỡ lỗi và diễn giải mô hình. Vector trọng số xác định hướng trong không gian đầu vào mà neuron đặc biệt nhạy cảm; độ lớn của nó thể hiện mức độ phản ứng khi đầu vào thay đổi theo hướng đó. Trong thị giác máy tính, khi trực quan hóa mẫu đầu vào kích hoạt cực đại từng neuron, ta thường thấy các lớp đầu học phát hiện cạnh theo hướng nhất định, còn các lớp sâu hơn dần nhận diện kết cấu (&lt;em&gt;texture&lt;/em&gt;), bộ phận và toàn bộ đối tượng.&lt;/p&gt;

&lt;h2 id=&quot;điểm-then-chốt&quot;&gt;Điểm Then chốt&lt;/h2&gt;

&lt;p&gt;Dù có cấu trúc đơn giản, perceptron đã đặt ra những ý niệm nền tảng vẫn còn nguyên giá trị trong học sâu: học từ ví dụ bằng cách cập nhật trọng số theo sai số, biểu diễn phép tính qua tổng có trọng số, và nhận thức rằng mô hình tuyến tính một lớp có giới hạn nên cần đến tính phi tuyến và độ sâu. Neuron nhân tạo hiện đại mở rộng perceptron bằng các hàm kích hoạt trơn, khả vi, cho phép huấn luyện mạng sâu tùy ý bằng gradient descent. Trong đó, ReLU trở thành lựa chọn mặc định cho các lớp ẩn nhờ chi phí tính toán thấp và khả năng hạn chế gradient biến mất. Bên cạnh đó, khởi tạo trọng số đúng cách — điển hình là khởi tạo He cho mạng ReLU — giúp phá vỡ đối xứng và giữ thang đo kích hoạt lẫn gradient ổn định. Nắm chắc không chỉ công thức mà cả lý do chúng hoạt động và các tình huống dễ gặp lỗi là cơ sở quan trọng để làm chủ học sâu.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ video của Machine Learning Thực Chiến:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/793200140509765&quot;&gt;Trực giác mạng nơ-ron (Perceptron → Deep Learning)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=i1G7PXZMnSc&quot;&gt;The Perceptron Explained&lt;/a&gt; — Alice Heiman, tiếng Anh. Giải thích perceptron như tổng có trọng số cộng ngưỡng, khớp với mô hình mở đầu của bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Minh họa điều gì thay đổi khi xếp chồng nhiều perceptron và thay ngưỡng cứng bằng hàm kích hoạt trơn.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sWPNm_GhhCA&quot;&gt;Tất tần tật về Neural Network trong 12 phút&lt;/a&gt; — Việt Nguyễn AI, tiếng Việt. Giới thiệu mạch phát triển từ một neuron đến cả mạng bằng tiếng Việt.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02 Giới thiệu về Mạng Neuron</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter02/02_00_Introduction</id>
   <content type="html">&lt;p&gt;Năm 1957, nhà tâm lý học Frank Rosenblatt xây dựng cỗ máy Mark I Perceptron từ hàng trăm biến trở cơ khí và dây điện chằng chịt, dạy nó nhận diện các tấm thẻ đục lỗ chỉ bằng cách vặn dần điện trở sau mỗi lần đoán sai. Hơn sáu thập kỷ sau, từ một tế bào nhân tạo đơn lẻ ấy đã nảy sinh những mạng nơ-ron hàng trăm tỷ tham số có khả năng viết mã, suy luận và sáng tác. Chương 02 đưa bạn đi xuyên suốt giải phẫu học của một mạng nơ-ron hoàn chỉnh: từ một nơ-ron đơn, cách xếp lớp thành kiến trúc sâu, vai trò của hàm kích hoạt phi tuyến, đến luồng tính toán lan truyền xuôi (&lt;em&gt;forward propagation&lt;/em&gt;).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-giải-phẫu-mạng-nơ-ron-nhân-tạo&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột giải phẫu Mạng Nơ-ron Nhân tạo&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Perceptron và Nơ-ron Nhân tạo (The Building Block)&lt;/strong&gt;:
Thực hiện phép tính hai nhịp kinh điển: tổng hợp tuyến tính \(z = \mathbf{w}^\top \mathbf{x} + b\) (tạo một siêu phẳng phân tách không gian) rồi đi qua hàm kích hoạt \(a = \sigma(z)\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kiến trúc Mạng, Độ sâu và Độ rộng (MLP Architecture)&lt;/strong&gt;:
Xếp song song nhiều nơ-ron tạo thành một tầng (&lt;em&gt;width&lt;/em&gt;) để tăng số đặc trưng học được; xếp nối tiếp nhiều tầng (&lt;em&gt;depth&lt;/em&gt;) để ghép các đặc trưng đơn giản thành khái niệm phức tạp hơn theo cấp số nhân.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hàm Kích hoạt Phi tuyến (Activation Functions)&lt;/strong&gt;:
Thành phần “bẻ cong” không gian không thể thiếu—từ Sigmoid/Tanh cổ điển dễ bão hòa đến ReLU, GELU và SwiGLU hiện đại giúp gradient chảy xuyên qua mạng hàng trăm tầng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lan truyền Xuôi (Forward Propagation)&lt;/strong&gt;:
Biến toàn bộ mạng thành một chuỗi phép nhân ma trận và hàm kích hoạt theo từng mini-batch, biến vector đầu vào thô thành dự đoán cuối cùng một cách hiệu quả trên GPU.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-theo-dõi-1-điểm-dữ-liệu-chạy-xuyên-qua-mạng-221-bằng-tay&quot;&gt;Giải thích: Theo dõi 1 điểm dữ liệu chạy xuyên qua mạng 2–2–1 bằng tay&lt;/h3&gt;

&lt;p&gt;Xét mạng cực gọn nhận đầu vào \(\mathbf{x} = \begin{bmatrix} 1 \\ 2 \end{bmatrix}\), có 1 tầng ẩn gồm 2 nơ-ron ReLU và 1 nơ-ron đầu ra tuyến tính:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tầng ẩn: \(\mathbf{W}^{(1)} = \begin{bmatrix} 1 &amp;amp; -1 \\ 0.5 &amp;amp; 1 \end{bmatrix}, \;\mathbf{b}^{(1)} = \begin{bmatrix} 0 \\ -1 \end{bmatrix}\).&lt;/li&gt;
  &lt;li&gt;Tầng ra: \(\mathbf{w}^{(2)} = \begin{bmatrix} 2 &amp;amp; -1 \end{bmatrix}, \; b^{(2)} = 0.5\).&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính tiền kích hoạt tầng ẩn&lt;/strong&gt;:
\(\mathbf{z}^{(1)} = \mathbf{W}^{(1)}\mathbf{x} + \mathbf{b}^{(1)} = \begin{bmatrix} 1(1) + (-1)(2) + 0 \\ 0.5(1) + 1(2) - 1 \end{bmatrix} = \begin{bmatrix} -1 \\ 1.5 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng ReLU&lt;/strong&gt; \(\max(0, z)\):
\(\mathbf{a}^{(1)} = \begin{bmatrix} \max(0, -1) \\ \max(0, 1.5) \end{bmatrix} = \begin{bmatrix} 0 \\ 1.5 \end{bmatrix}.\)
(Nơ-ron ẩn 1 bị tắt về \(0\), chỉ nơ-ron ẩn 2 kích hoạt!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính đầu ra cuối&lt;/strong&gt;:
\(\hat{y} = 2(0) + (-1)(1.5) + 0.5 = -1.0.\)
Toàn bộ mạng nơ-ron hàng tỷ tham số chỉ là sự mở rộng quy mô của đúng ba bước nhân–cộng–bẻ cong giản dị này!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mạng neuron (&lt;em&gt;neural networks&lt;/em&gt;) là nền tảng của học sâu hiện đại. Chương này giới thiệu các thành phần cơ bản của mạng neuron, bao gồm neuron, lớp (&lt;em&gt;layer&lt;/em&gt;), hàm kích hoạt (&lt;em&gt;activation function&lt;/em&gt;) và lan truyền xuôi (&lt;em&gt;forward propagation&lt;/em&gt;). Ta sẽ tìm hiểu cách các đơn vị đơn giản này kết hợp với nhau để tạo thành những hệ thống có khả năng học và giải quyết các bài toán phức tạp.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/mnist_digits_grid.jpg&quot; alt=&quot;Chữ số viết tay trên lưới pixel&quot; /&gt;
&lt;em&gt;Hình: Bài toán nhận diện chữ số viết tay — mỗi ảnh là một lưới pixel. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Việc nắm vững mạng neuron là nền tảng cần thiết cho bất kỳ ai làm việc trong lĩnh vực học sâu, bởi đây là cơ sở cho các kiến trúc và kỹ thuật nâng cao hơn ở các chương sau.&lt;/p&gt;

&lt;h3 id=&quot;trực-giác-nhanh-từ-pixel-đến-dự-đoán&quot;&gt;Trực giác nhanh: từ pixel đến dự đoán&lt;/h3&gt;

&lt;p&gt;Khi xử lý ảnh chữ số (ví dụ lưới \(28 \times 28\)), ta thường &lt;strong&gt;làm phẳng&lt;/strong&gt; (&lt;em&gt;flatten&lt;/em&gt;) ảnh thành một vector gồm \(784\) số, rồi đưa qua các lớp neuron. Mỗi lớp sẽ biến đổi biểu diễn dữ liệu sang một không gian mới; lớp cuối cùng có thể xuất ra \(10\) giá trị tương ứng với các chữ số từ \(0\) đến \(9\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/mnist_to_mlp_layers.jpg&quot; alt=&quot;Từ ảnh 28×28 tới mạng nhiều lớp&quot; /&gt;
&lt;em&gt;Hình: Ảnh \(28\times28\) → \(784\) đầu vào → các lớp ẩn → đầu ra. (Minh họa từ video nhập môn mạng neuron)&lt;/em&gt;&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ video của Machine Learning Thực Chiến:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/793200140509765&quot;&gt;Trực giác mạng nơ-ron (Perceptron → Deep Learning)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau các bài về neuron và hàm kích hoạt, bạn có thể xem thêm &lt;strong&gt;02-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; để tìm hiểu về SwiGLU, RMSNorm và cách khối MLP được tổ chức trong các mô hình nền tảng (&lt;em&gt;foundation model&lt;/em&gt;) hiện nay. Bài &lt;strong&gt;26-07&lt;/strong&gt; trong phần về LLM trình bày lại cùng khối này kèm phân tích FLOPs và sơ đồ decoder.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (luyện phỏng vấn):&lt;/strong&gt; Sau khi học hàm kích hoạt và MLP, bạn có thể xem &lt;strong&gt;02-98 Luyện phỏng vấn&lt;/strong&gt; với các bài tập gốc về perceptron, softmax và ReLU; bộ câu hỏi và lời giải đầy đủ nằm trong &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Trình bày lần lượt từ một neuron, đến một lớp, rồi thành cả mạng — đúng theo mạch nội dung của chương này.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=CqOfi41LfDw&quot;&gt;The Essential Main Ideas of Neural Networks&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa trực quan từng trọng số mà chương này sẽ định nghĩa.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sWPNm_GhhCA&quot;&gt;Tất tần tật về Neural Network trong 12 phút&lt;/a&gt; — Việt Nguyễn AI, tiếng Việt. Tổng quan ngắn gọn bằng tiếng Việt về cấu trúc mạng neuron trước khi đi vào bài perceptron.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Nếu năm 2016 câu hỏi mặc định khi bắt đầu một dự án AI là &lt;em&gt;“Mình nên thu thập bao nhiêu nghìn mẫu để huấn luyện mạng từ đầu?”&lt;/em&gt;, thì trong giai đoạn 2022–2026 câu hỏi mặc định đã hoàn toàn thay đổi: &lt;em&gt;“Mình nên bắt đầu từ mô hình nền tảng (Foundation Model) nào, thử prompting/RAG trước hay tinh chỉnh nhẹ bằng LoRA?”&lt;/em&gt; Sự chuyển dịch này không hề làm kiến thức nền tảng của bạn trở nên lỗi thời—ngược lại, nó giúp bạn đi xa hơn gấp nhiều lần nếu hiểu rõ quy trình thực hành hiện đại và biết đánh giá rủi ro của từng lựa chọn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-tầng-của-quy-trình-thực-hành-học-sâu-hiện-đại&quot;&gt;Kiến thức cần nhớ: Bốn tầng của Quy trình Thực hành Học sâu Hiện đại&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Bậc thang Thích ứng (Adaptation Ladder: Prompting \(\to\) RAG \(\to\) LoRA \(\to\) Pretraining)&lt;/strong&gt;:
Luôn đi từ phương án chi phí thấp, lặp nhanh nhất trước khi đầu tư tinh chỉnh trọng số hay huấn luyện từ đầu—chỉ nâng bậc khi đo lường thực nghiệm chứng minh bậc dưới đã chạm trần.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đánh giá Hệ thống (Evals-Driven Development)&lt;/strong&gt;:
Trong kỷ nguyên mô hình sinh, độ chính xác đơn thuần không còn đủ; kỹ sư phải xây dựng bộ &lt;em&gt;evals&lt;/em&gt; tự động đo độ trung thực (chống ảo giác), độ tuân thủ định dạng, độ trễ và chi phí mỗi truy vấn.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Suy luận Hiệu quả và Triển khai (Quantization, KV-Cache, Serving)&lt;/strong&gt;:
Hiểu các nút thắt bộ nhớ băng thông (memory-bandwidth bound) khi sinh token, cách lượng tử hóa xuống &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;INT8&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FP8&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;INT4&lt;/code&gt; cắt giảm VRAM gấp 2–4 lần mà hầu như giữ nguyên chất lượng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Sự kết hợp giữa Mô hình Nền tảng và Mô hình Chuyên biệt&lt;/strong&gt;:
Dùng mô hình lớn làm “giáo viên” sinh dữ liệu tổng hợp hoặc gán nhãn tự động, rồi chưng cất (&lt;em&gt;distill&lt;/em&gt;) sang mô hình nhỏ chạy siêu nhanh và tiết kiệm chi phí trong sản xuất.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-lượng-vram-cần-thiết-để-nạp-một-llm-7-tỷ-tham-số-ở-các-độ-chính-xác-khác-nhau&quot;&gt;Giải thích: Tính tay lượng VRAM cần thiết để nạp một LLM 7 tỷ tham số ở các độ chính xác khác nhau&lt;/h3&gt;

&lt;p&gt;Giả sử bạn muốn chạy suy luận một mô hình nền tảng cỡ \(7\text{ tỷ}\) tham số (\(7 \times 10^9\)) trên GPU cá nhân có 16 GB VRAM:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Định dạng số học&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Số byte / tham số&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Bộ nhớ chỉ riêng trọng số (ước tính)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Chạy vừa trên GPU 16 GB VRAM?&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;FP32 (32-bit)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(4\text{ bytes}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(7 \times 4 = 28\text{ GB}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Không&lt;/strong&gt; (tràn VRAM ngay lập tức)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;FP16 / BF16 (16-bit)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(2\text{ bytes}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(7 \times 2 = 14\text{ GB}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Sát ngưỡng&lt;/strong&gt; (chỉ còn 2 GB cho KV-cache)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;INT8 (8-bit)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1\text{ byte}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(7 \times 1 = 7\text{ GB}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Thoải mái&lt;/strong&gt; (còn 9 GB cho ngữ cảnh dài)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;INT4 / Q4 (4-bit)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.5\text{ byte}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(7 \times 0.5 = 3.5\text{ GB}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Rất nhẹ&lt;/strong&gt; (chạy tốt cả trên laptop 8 GB VRAM)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Chỉ bằng một phép nhân đơn giản (\(\text{Số tham số} \times \text{Số byte}\)), bạn đã có thể ước tính tức thì cấu hình phần cứng và quyết định chiến lược triển khai mà không cần đoán mò!&lt;/p&gt;

&lt;h1 id=&quot;tùy-chọn-thực-hành-học-sâu-trong-kỷ-nguyên-mô-hình-nền-tảng&quot;&gt;Tùy chọn: Thực hành học sâu trong kỷ nguyên mô hình nền tảng&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là phần &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế các bài cốt lõi về giới thiệu học sâu, MNIST hay hướng dẫn khóa học. Mục đích của bài là cập nhật &lt;em&gt;quy trình thực hành&lt;/em&gt; trong ngành kể từ khi mô hình nền tảng (&lt;em&gt;foundation model&lt;/em&gt;) trở thành điểm xuất phát mặc định.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ý tưởng trọng tâm của Chương 01 là mô hình sâu học các đặc trưng phân cấp từ dữ liệu. Từ năm 2022 trở đi, phần lớn dự án thực tế không còn bắt đầu từ một mạng MNIST khởi tạo ngẫu nhiên mà xuất phát từ mô hình &lt;strong&gt;đã được tiền huấn luyện&lt;/strong&gt; (&lt;em&gt;pretrained&lt;/em&gt;) cùng một hạ tầng phục vụ (&lt;em&gt;serving stack&lt;/em&gt;). Tuy vậy, những câu hỏi cốt lõi — khi nào học sâu thực sự hữu ích, cần loại dữ liệu nào và mô hình dễ sai ở đâu — vẫn quyết định hiệu quả của hệ thống.&lt;/p&gt;

&lt;h2 id=&quot;1-quy-trình-mặc-định-mới&quot;&gt;1. Quy trình mặc định mới&lt;/h2&gt;

&lt;p&gt;Một dự án ứng dụng điển hình giai đoạn 2024–2026 thường đi qua ba bước:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Chọn mô hình nền tảng phù hợp (thị giác, ngôn ngữ, tiếng nói hoặc đa phương thức).&lt;/li&gt;
  &lt;li&gt;Thích nghi mô hình cho bài toán đích bằng kỹ thuật &lt;em&gt;prompting&lt;/em&gt;, truy xuất thông tin (&lt;em&gt;retrieval&lt;/em&gt;) hoặc tinh chỉnh tiết kiệm tham số (Chương 15).&lt;/li&gt;
  &lt;li&gt;Đánh giá trên tập kiểm thử giữ lại, &lt;em&gt;đồng thời&lt;/em&gt; kiểm tra các ràng buộc về an toàn và chi phí vận hành.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bản chất vẫn dựa trên học có giám sát hoặc học tự giám sát; điểm thay đổi nằm ở &lt;strong&gt;trạng thái khởi tạo&lt;/strong&gt; và &lt;strong&gt;giao diện tương tác&lt;/strong&gt; (API, &lt;em&gt;tokenizer&lt;/em&gt;, mẫu hội thoại &lt;em&gt;chat template&lt;/em&gt;), chứ không phải định nghĩa của mạng nơ-ron.&lt;/p&gt;

&lt;h2 id=&quot;2-một-số-ứng-dụng-cụ-thể&quot;&gt;2. Một số ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;trợ-lý-cho-khoa-học-dữ-liệu&quot;&gt;Trợ lý cho khoa học dữ liệu&lt;/h3&gt;

&lt;p&gt;Các quy trình xử lý dữ liệu dạng bảng và SQL hiện thường tích hợp LLM quanh &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pandas&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scikit-learn&lt;/code&gt; và truy vấn kho dữ liệu. Mô hình không thay thế hàm mất mát hay quy tắc chia tập dữ liệu, mà hỗ trợ viết mã nguồn và giải thích kết quả. Hai thư viện &lt;a href=&quot;https://github.com/huggingface/transformers&quot;&gt;transformers&lt;/a&gt; và &lt;a href=&quot;https://github.com/huggingface/datasets&quot;&gt;datasets&lt;/a&gt; của Hugging Face đóng vai trò kết nối phổ biến trong nghiên cứu và phát triển.&lt;/p&gt;

&lt;h3 id=&quot;huấn-luyện-tối-ưu-theo-ngân-sách-tính-toán&quot;&gt;Huấn luyện tối ưu theo ngân sách tính toán&lt;/h3&gt;

&lt;p&gt;Nghiên cứu &lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Hoffmann et al., 2022&lt;/a&gt; chỉ ra rằng nhiều mô hình cỡ GPT-3 trước đây bị &lt;strong&gt;huấn luyện thiếu dữ liệu&lt;/strong&gt; (&lt;em&gt;undertrained&lt;/em&gt;): với ngân sách tính toán FLOP \(C\) cố định, số tham số tối ưu \(N\) và số token huấn luyện \(D\) cần tăng đồng thời. Nhờ đó, các nhóm kỹ thuật hiện thường đặt câu hỏi “tỷ lệ bao nhiêu token trên mỗi tham số?” trước khi đầu tư cụm GPU.&lt;/p&gt;

&lt;h3 id=&quot;hệ-sinh-thái-mô-hình-trọng-số-mở&quot;&gt;Hệ sinh thái mô hình trọng số mở&lt;/h3&gt;

&lt;p&gt;Các thế hệ &lt;a href=&quot;https://arxiv.org/abs/2302.13971&quot;&gt;LLaMA&lt;/a&gt;, &lt;a href=&quot;https://arxiv.org/abs/2307.09288&quot;&gt;Llama 2&lt;/a&gt; và Llama 3 của Meta, cùng nhiều họ mô hình mở khác (Mistral, Qwen, Gemma), đã giúp việc chạy mô hình ngôn ngữ chất lượng tốt ngay trên một máy trạm với &lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;llama.cpp&lt;/a&gt; hoặc &lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt; trở nên phổ biến. Bài toán MNIST vẫn dạy đúng vòng lặp huấn luyện nền tảng, còn các công cụ trên là môi trường triển khai thực tế của vòng lặp đó.&lt;/p&gt;

&lt;h2 id=&quot;3-công-cụ-phần-mềm-phổ-biến&quot;&gt;3. Công cụ phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://pytorch.org/&quot;&gt;PyTorch&lt;/a&gt; 2.x với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt; là lựa chọn tăng tốc mặc định.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://huggingface.co/&quot;&gt;Hugging Face Hub&lt;/a&gt; — nơi lưu trữ &lt;em&gt;model card&lt;/em&gt;, &lt;em&gt;tokenizer&lt;/em&gt; và bộ công cụ đánh giá chuẩn hóa.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX&lt;/a&gt; / Flax — được dùng rộng rãi trong huấn luyện nghiên cứu quy mô lớn.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-tài-liệu-tham-khảo-20222026&quot;&gt;4. Tài liệu tham khảo (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Hoffmann et al., 2022&lt;/a&gt; — quy luật Chinchilla về việc mở rộng đồng thời lượng dữ liệu và kích thước mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2302.13971&quot;&gt;LLaMA (Touvron et al., 2023)&lt;/a&gt; — mô hình ngôn ngữ nền tảng công bố chi tiết kỹ thuật, tạo bước chuyển lớn cho hệ sinh thái mô hình mở.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2307.09288&quot;&gt;Llama 2 (Touvron et al., 2023)&lt;/a&gt; — mô hình trọng số mở được tinh chỉnh hội thoại và căn chỉnh bằng RLHF.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-vai-trò-của-bài-này-đối-với-phần-cốt-lõi&quot;&gt;5. Vai trò của bài này đối với phần cốt lõi&lt;/h2&gt;

&lt;p&gt;Các bài &lt;em&gt;Học sâu là gì&lt;/em&gt; và &lt;em&gt;Bước đầu với MNIST&lt;/em&gt; vẫn là nền tảng định nghĩa lĩnh vực. Bài tùy chọn này chỉ cập nhật &lt;em&gt;điểm khởi đầu thực tế&lt;/em&gt; vào năm 2026 — gồm trọng số tiền huấn luyện, kho mô hình và cách phân bổ ngân sách theo quy luật mở rộng — chứ không thay đổi khái niệm cốt lõi của mạng nơ-ron.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=LPZh9BOjkQs&quot;&gt;Large Language Models explained briefly&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Giới thiệu ngắn gọn về tiền huấn luyện, Transformer và RLHF, khớp với quy trình mặc định giai đoạn 2022–2026 trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Trình bày chi tiết hơn về toàn bộ quy trình từ dữ liệu, huấn luyện đến triển khai mô hình ngôn ngữ lớn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=N1fbskTpwZ0&quot;&gt;MIT 6.S191 (2024): Language Models and New Frontiers&lt;/a&gt; — Alexander Amini, tiếng Anh. Bài giảng năm 2024 của MIT về mô hình ngôn ngữ và các hướng phát triển mới, bổ sung góc nhìn thực tiễn cho các công trình được trích dẫn trong bài.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-98 Lộ trình luyện Deep Learning Interviews</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_98_Interviews_Practice_Track/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_98_Interviews_Practice_Track</id>
   <content type="html">&lt;p&gt;Chuẩn bị phỏng vấn Deep Learning mà chỉ học tủ danh sách câu hỏi rời rạc rất dễ rơi vào cảnh “gặp câu hỏi biến tấu một chút là đứng hình”. Lý do đơn giản là mọi câu hỏi phỏng vấn sắc bén đều bắt nguồn từ một hệ thống kiến thức liên thông: từ xác suất và giải tích (Chương 00), qua kiến trúc mạng và lan truyền ngược (Chương 02–03), đến tối ưu hóa, CNN, Transformer và thiết kế hệ thống ML. Bài học này thiết kế lộ trình đối chiếu từng chương của khóa học với các chủ đề trọng tâm của sách &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, giúp bạn tích lũy năng lực phỏng vấn song hành với tiến độ học hàng ngày.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nhóm-câu-hỏi-cốt-lõi-trong-phỏng-vấn-deep-learning&quot;&gt;Kiến thức cần nhớ: Bốn nhóm câu hỏi cốt lõi trong Phỏng vấn Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Nền tảng Toán &amp;amp; Thống kê (Ch 00–03)&lt;/strong&gt;:
Tự tay đạo hàm Softmax + Cross-Entropy, giải thích liên hệ MLE–MSE–Cross-Entropy, phân biệt L1/L2 Regularization, và phân tích nguyên nhân gradient biến mất/bùng nổ.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kiến trúc &amp;amp; Cơ chế Hiện đại (Ch 04–16)&lt;/strong&gt;:
Tính kích thước đầu ra tầng tích chập (Conv2D), so sánh BatchNorm vs. LayerNorm, giải thích cơ chế Scaled Dot-Product Attention \(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\) và lý do chia cho \(\sqrt{d_k}\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Gỡ lỗi Huấn luyện &amp;amp; Thực chiến (Training &amp;amp; Debugging)&lt;/strong&gt;:
Chẩn đoán các kịch bản quen thuộc: train loss giảm nhưng val loss tăng (overfitting), cả hai cùng cao (underfitting/bug), loss bất ngờ vọt lên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; (learning rate cao hoặc chia 0).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Thiết kế Hệ thống ML (ML System Design)&lt;/strong&gt;:
Biết chọn metric kinh doanh và metric mô hình, xử lý mất cân bằng dữ liệu, trôi phân phối (&lt;em&gt;data drift&lt;/em&gt;) và tối ưu độ trễ suy luận (&lt;em&gt;latency/throughput&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-áp-dụng-khung-trả-lời-4-bước-cho-một-câu-hỏi-phỏng-vấn-kinh-điển&quot;&gt;Giải thích: Áp dụng khung trả lời 4 bước cho một câu hỏi phỏng vấn kinh điển&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Đề bài mẫu&lt;/strong&gt;: &lt;em&gt;“Tại sao trong Scaled Dot-Product Attention ta phải chia tích vô hướng \(\mathbf{q} \cdot \mathbf{k}\) cho \(\sqrt{d_k}\) trước khi đưa vào Softmax?”&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giả định thống kê&lt;/strong&gt;: Giả sử các thành phần \(q_i, k_i\) độc lập, kỳ vọng \(0\), phương sai \(1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính tay phương sai của tích vô hướng&lt;/strong&gt;:
\(\text{Var}\!\left(\sum_{i=1}^{d_k} q_i k_i\right) = \sum_{i=1}^{d_k} \text{Var}(q_i)\text{Var}(k_i) = d_k.\)
Với \(d_k = 64\), độ lệch chuẩn là \(\sqrt{64} = 8\); với \(d_k = 512\), độ lệch chuẩn vọt lên \(\approx 22.6\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hệ quả nếu KHÔNG chia&lt;/strong&gt;: Các logit lớn tới \(\pm 20\) đẩy Softmax vào vùng bão hòa (một phần tử \(\approx 1\), mọi phần tử khác \(\approx 0\)), làm đạo hàm của Softmax gần bằng \(0\) (vanishing gradient).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu quả khi chia cho \(\sqrt{d_k}\)&lt;/strong&gt;:
\(\text{Var}\!\left(\frac{\mathbf{q}\cdot\mathbf{k}}{\sqrt{d_k}}\right) = \frac{d_k}{(\sqrt{d_k})^2} = 1,\)
giữ phương sai đầu vào Softmax luôn ổn định bằng \(1\) bất kể \(d_k\) lớn đến đâu! Trả lời đủ 4 bước định lượng này, bạn sẽ luôn thuyết phục được hội đồng phỏng vấn.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-lộ-trình-luyện-deep-learning-interviews&quot;&gt;Tùy chọn: Lộ trình luyện Deep Learning Interviews&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là phần &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế bất kỳ chương lý thuyết nào. Đây là bảng đối chiếu và kế hoạch học giúp bạn kết hợp một cuốn sách luyện phỏng vấn miễn phí như nguồn bài tập bổ sung sau khi đã học xong phần lý thuyết tương ứng trong khóa.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;giới-thiệu-cuốn-sách&quot;&gt;Giới thiệu cuốn sách&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Deep Learning Interviews&lt;/strong&gt; (ấn bản thứ hai) của &lt;strong&gt;Shlomo Kashani&lt;/strong&gt; và &lt;strong&gt;Amir Ivry&lt;/strong&gt; là tuyển tập các bài toán phỏng vấn và thi cử có lời giải chi tiết, bao phủ nhiều chủ đề cốt lõi của trí tuệ nhân tạo. Sách phù hợp cho học viên cao học và ứng viên cần trình bày rõ ràng dưới áp lực thời gian, đồng thời có thể dùng như danh mục kiểm tra kiến thức nền tảng cho nghiên cứu.&lt;/p&gt;

&lt;p&gt;Khóa học này &lt;strong&gt;không&lt;/strong&gt; sao chép lại nội dung sách. Bạn hãy truy cập trực tiếp các nguồn chính thức:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;PDF và tóm tắt: &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Kho mã nguồn kèm theo: &lt;a href=&quot;https://github.com/BoltzmannEntropy/interviews.ai&quot;&gt;github.com/BoltzmannEntropy/interviews.ai&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Trang của tác giả: &lt;a href=&quot;http://www.interviews.ai/&quot;&gt;interviews.ai&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hãy tải tệp PDF từ arXiv hoặc liên kết chính thức của tác giả, tuân thủ điều khoản sử dụng trên các trang đó và không dán các đoạn trích dài vào ghi chú, issue hay lời giải công khai.&lt;/p&gt;

&lt;h2 id=&quot;cách-kết-hợp-sách-với-khóa-học&quot;&gt;Cách kết hợp sách với khóa học&lt;/h2&gt;

&lt;p&gt;Hãy chọn một mục tiêu học phù hợp và giữ kỷ luật về thời gian:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Luyện phỏng vấn:&lt;/strong&gt; Sau khi hoàn thành mỗi chương, hãy tự trình bày &lt;em&gt;thành tiếng&lt;/em&gt; câu trả lời cho các câu hỏi gốc trong bài luyện tập bổ trợ của chương đó, rồi mở sách để làm thêm các bài khó hơn có lời giải cùng chủ đề.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra ngắn trên lớp:&lt;/strong&gt; Giảng viên có thể chọn 2–3 câu trong bài bổ trợ làm bài kiểm tra nhanh, dùng sách làm nguồn tham khảo lời giải hoặc bài tập về nhà mở rộng mà không sao chép trực tiếp thành phiếu bài tập.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Củng cố nền tảng nghiên cứu:&lt;/strong&gt; Trước khi đọc các bài báo dựa trên lý thuyết thông tin, vi phân tự động (&lt;em&gt;autodiff&lt;/em&gt;) hoặc ước lượng bất định, hãy rà soát phần chủ đề tương ứng trong sách (tránh đọc dàn trải cả chương) kết hợp với bài lý thuyết của khóa.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nguyên tắc chung là tự giải khi &lt;strong&gt;đóng sách&lt;/strong&gt; trước, sau đó xem phần gợi ý của khóa học, và chỉ mở tệp PDF sau cùng để đối chiếu thêm các câu hỏi–đáp có lời giải.&lt;/p&gt;

&lt;h2 id=&quot;kế-hoạch-học-đối-chiếu-chủ-đề-sách-với-chương-0026&quot;&gt;Kế hoạch học: đối chiếu chủ đề sách với Chương 00–26&lt;/h2&gt;

&lt;p&gt;Cuốn sách được sắp xếp theo nhóm chủ đề phỏng vấn chứ không theo thứ tự chương của khóa học. Bảng dưới đây giúp bạn tra cứu tương ứng; tên chủ đề chỉ là &lt;strong&gt;nhãn khái quát ở mức cao&lt;/strong&gt;, không phải mục lục sao chép từ sách.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Chương khóa&lt;/th&gt;
      &lt;th&gt;Chủ đề khóa&lt;/th&gt;
      &lt;th&gt;Chủ đề nên đọc trong sách (PDF)&lt;/th&gt;
      &lt;th&gt;Bài tùy chọn&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;00&lt;/td&gt;
      &lt;td&gt;Toán tiên quyết&lt;/td&gt;
      &lt;td&gt;Lý thuyết thông tin (entropy, phân kỳ KL, thông tin tương hỗ); giải tích và trực giác autodiff&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;00-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;01&lt;/td&gt;
      &lt;td&gt;Giới thiệu và hướng dẫn&lt;/td&gt;
      &lt;td&gt;Cách sử dụng sách; trang tổng hợp này&lt;/td&gt;
      &lt;td&gt;bài này&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;02&lt;/td&gt;
      &lt;td&gt;Nền tảng mạng nơ-ron&lt;/td&gt;
      &lt;td&gt;Perceptron, hàm kích hoạt, phần kiến trúc mở rộng của học sâu&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;02-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;03&lt;/td&gt;
      &lt;td&gt;Huấn luyện, hàm mất mát, lan truyền ngược&lt;/td&gt;
      &lt;td&gt;Vi phân thuật toán; trực giác ma trận Hessian; hồi quy logistic và phân loại&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;03-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;04&lt;/td&gt;
      &lt;td&gt;CNN&lt;/td&gt;
      &lt;td&gt;Phép tích chập, kiến trúc CNN, trích xuất đặc trưng ban đầu&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;04-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;05–08&lt;/td&gt;
      &lt;td&gt;RNN, LSTM, attention, Transformer&lt;/td&gt;
      &lt;td&gt;Tập I chưa có mục riêng — bám sát bài giảng khóa học; Tập II dự kiến đề cập NLP và chuỗi&lt;/td&gt;
      &lt;td&gt;chỉ trên trang này&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;09&lt;/td&gt;
      &lt;td&gt;Chính quy hóa&lt;/td&gt;
      &lt;td&gt;Quá khớp (&lt;em&gt;overfitting&lt;/em&gt;), kiểm định, kiểm soát dung lượng mô hình&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;09-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;10&lt;/td&gt;
      &lt;td&gt;Bộ tối ưu&lt;/td&gt;
      &lt;td&gt;Phương pháp thích nghi (Adam và các biến thể), siêu tham số, động lực học huấn luyện&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;10-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;11–14&lt;/td&gt;
      &lt;td&gt;Mô hình sinh (gồm VAE, GAN)&lt;/td&gt;
      &lt;td&gt;Tập I chưa có mục riêng — kế hoạch Tập II nhắc tới GAN và VAE; dùng bài giảng khóa học&lt;/td&gt;
      &lt;td&gt;chỉ trên trang này&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;15&lt;/td&gt;
      &lt;td&gt;Học chuyển giao&lt;/td&gt;
      &lt;td&gt;Trích xuất đặc trưng CNN, so sánh đóng băng &lt;em&gt;backbone&lt;/em&gt; và tinh chỉnh (&lt;em&gt;fine-tuning&lt;/em&gt;)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;15-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;16–23&lt;/td&gt;
      &lt;td&gt;SSL, CV, NLP, tiếng nói, RL, GNN, hiệu năng&lt;/td&gt;
      &lt;td&gt;Tập I chưa có mục riêng; Tập II dự kiến gồm phát hiện đối tượng, phân đoạn, NLP, RL — dùng các chương tương ứng của khóa&lt;/td&gt;
      &lt;td&gt;chỉ trên trang này&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;24&lt;/td&gt;
      &lt;td&gt;Giải thích mô hình&lt;/td&gt;
      &lt;td&gt;Chỉ đề cập ở mức liên quan; phần &lt;em&gt;bất định&lt;/em&gt; Bayesian nằm ở Chương 25&lt;/td&gt;
      &lt;td&gt;chỉ trên trang này&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;25&lt;/td&gt;
      &lt;td&gt;Chủ đề nâng cao&lt;/td&gt;
      &lt;td&gt;Học sâu Bayesian và tư duy xác suất&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;25-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;26&lt;/td&gt;
      &lt;td&gt;Mô hình ngôn ngữ lớn&lt;/td&gt;
      &lt;td&gt;Tập I chưa có mục riêng — dùng mục tổng hợp LLM của khóa (toán tiền huấn luyện, prompting, căn chỉnh, phục vụ, chưng cất, cơ chế nội tại)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;26-06&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;các-chủ-đề-không-có-chương-riêng&quot;&gt;Các chủ đề không có chương riêng&lt;/h3&gt;

&lt;p&gt;Những nội dung này được tóm tắt ngay tại đây thay vì tạo thêm chương bắt buộc mới.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tổ hợp mô hình (&lt;em&gt;ensemble&lt;/em&gt;: bagging / boosting / stacking):&lt;/strong&gt; Cuốn sách coi tổ hợp mạng nơ-ron là một chủ đề phỏng vấn quan trọng, dù khóa học không có chương riêng. Nếu được hỏi, bạn cần phân biệt rõ ba hướng chính:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bagging:&lt;/strong&gt; lấy trung bình nhiều mô hình huấn luyện độc lập để giảm phương sai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Boosting:&lt;/strong&gt; huấn luyện tuần tự các mô hình nhằm sửa phần dư của mô hình trước, giúp giảm độ chệch (&lt;em&gt;bias&lt;/em&gt;) mạnh hơn &lt;em&gt;bagging&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stacking:&lt;/strong&gt; dùng một mô hình tầng hai học cách kết hợp dự đoán của các mô hình cơ sở.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Câu hỏi thảo luận (do khóa biên soạn, không lấy từ sách):&lt;/strong&gt; Khi nào nên áp dụng &lt;em&gt;bagging&lt;/em&gt; với mười mạng CNN độc lập thay vì huấn luyện một mô hình lớn gấp mười lần? Điều gì sẽ xảy ra nếu các mô hình cơ sở có tương quan cao với nhau?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tập II (dự kiến):&lt;/strong&gt; Các tác giả đã phác thảo tập tiếp theo về CNN nâng cao, phát hiện đối tượng, phân đoạn ảnh, NLP, GAN, VAE và học tăng cường. Khi tập này chưa được đưa vào giáo trình, bạn hãy học các chủ đề đó qua Chương 11–21 của khóa học và dùng tệp PDF Tập I làm nguồn bài tập có lời giải theo bảng đối chiếu trên.&lt;/p&gt;

&lt;h2 id=&quot;ba-câu-khởi-động-gốc-chỉ-có-tại-trang-này&quot;&gt;Ba câu khởi động gốc (chỉ có tại trang này)&lt;/h2&gt;

&lt;p&gt;Ba câu hỏi dưới đây do khóa học tự soạn, không trích từ sách.&lt;/p&gt;

&lt;h3 id=&quot;h1-người-phỏng-vấn-đang-kiểm-tra-điều-gì&quot;&gt;H1. Người phỏng vấn đang kiểm tra điều gì?&lt;/h3&gt;

&lt;p&gt;Bạn được yêu cầu giải thích trong hai phút: “Vì sao bài toán phân loại 10 lớp thường dùng &lt;em&gt;cross-entropy&lt;/em&gt; thay vì MSE?” Hãy nêu rõ một lý do về &lt;em&gt;mô hình hóa&lt;/em&gt; và một lý do về &lt;em&gt;tối ưu hóa&lt;/em&gt;, rồi dừng lại.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý:&lt;/strong&gt; Liên hệ với hàm hợp lý (&lt;em&gt;likelihood&lt;/em&gt;) của phân phối phân loại (&lt;em&gt;categorical&lt;/em&gt;) và độ lớn của gradient khi mô hình dự đoán sai nhưng lại có độ tự tin rất cao.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận:&lt;/strong&gt; Về mô hình hóa, &lt;em&gt;softmax&lt;/em&gt; biểu diễn một phân phối xác suất rời rạc, và &lt;em&gt;cross-entropy&lt;/em&gt; chính là âm log-hợp lý (&lt;em&gt;negative log-likelihood&lt;/em&gt;) của phân phối đó. Về tối ưu hóa, MSE tính trên xác suất thường cho gradient nhỏ khi xác suất tập trung sai vào một lớp, trong khi &lt;em&gt;negative log-likelihood&lt;/em&gt; vẫn duy trì tín hiệu đẩy &lt;em&gt;logit&lt;/em&gt; của lớp đúng lên. Sau khi tự trả lời, bạn có thể mở tệp PDF để luyện thêm các câu về hàm mất mát và phân loại (không sao chép lại vào đây).&lt;/p&gt;

&lt;h3 id=&quot;h2-luyện-tập-đóng-sách-và-mở-sách&quot;&gt;H2. Luyện tập đóng sách và mở sách&lt;/h3&gt;

&lt;p&gt;Nếu bạn được phép tra cứu PDF trong bài làm tại nhà (&lt;em&gt;take-home&lt;/em&gt;) nhưng không được dùng tài liệu trong buổi phỏng vấn trực tiếp 45 phút, kế hoạch luyện tập hằng tuần nên thay đổi như thế nào?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý:&lt;/strong&gt; Phỏng vấn trực tiếp thường đánh giá khả năng biến đổi ngắn gọn ngay trên bảng (như đạo hàm hàm sigmoid, công thức kích thước đầu ra tầng tích chập, hay một bước cập nhật của Adam).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận:&lt;/strong&gt; Hãy bấm giờ khi làm các câu trong bài luyện tập bổ trợ, còn cuốn sách dùng để đào sâu và chuẩn hóa cách diễn đạt. Nếu một chủ đề chỉ giải được khi mở PDF, nghĩa là bạn chưa đủ sẵn sàng cho vòng phỏng vấn trực tiếp.&lt;/p&gt;

&lt;h3 id=&quot;h3-tổ-hợp-mô-hình-khi-khóa-không-có-chương-riêng&quot;&gt;H3. Tổ hợp mô hình khi khóa không có chương riêng&lt;/h3&gt;

&lt;p&gt;Trong một vòng tuyển dụng, bạn được yêu cầu giảm phương sai của một mạng ResNet đã tinh chỉnh tốt mà không thay đổi kiến trúc. Hãy nêu hai cách &lt;em&gt;không phải&lt;/em&gt; là “thu thập thêm dữ liệu có nhãn”.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý:&lt;/strong&gt; Một cách thay đổi cách sử dụng mô hình sẵn có; cách còn lại thay đổi cách sử dụng dữ liệu sẵn có.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận:&lt;/strong&gt; Có thể áp dụng &lt;em&gt;snapshot ensemble&lt;/em&gt; hoặc &lt;em&gt;bagging&lt;/em&gt; nhiều bản tinh chỉnh, tăng cường dữ liệu lúc suy luận (&lt;em&gt;test-time augmentation&lt;/em&gt;), hoặc dùng &lt;em&gt;dropout&lt;/em&gt; nhiều lần lúc kiểm thử như một dạng tổ hợp. Việc tăng kích thước mô hình làm thay đổi dung lượng chứ không phải tổ hợp giảm phương sai. Các bài toán tổ hợp mô hình có lời giải chi tiết hơn nằm trong sách, không lưu trong kho này.&lt;/p&gt;

&lt;h2 id=&quot;danh-mục-các-bài-luyện-tập-bổ-trợ&quot;&gt;Danh mục các bài luyện tập bổ trợ&lt;/h2&gt;

&lt;p&gt;Sau khi hoàn thành bài lý thuyết tương ứng, bạn có thể mở các bài sau:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;00-98&lt;/strong&gt; — lý thuyết thông tin, giải tích và vi phân tự động (&lt;em&gt;autodiff&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;02-98&lt;/strong&gt; — nơ-ron, hàm kích hoạt và cấu trúc MLP.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;03-98&lt;/strong&gt; — vi phân tự động, trực giác Hessian và phân loại logistic.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;04-98&lt;/strong&gt; — hình học phép tích chập và kiến trúc CNN.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;09-98&lt;/strong&gt; — quá khớp (&lt;em&gt;overfitting&lt;/em&gt;) và các kỹ thuật chính quy hóa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;10-98&lt;/strong&gt; — họ bộ tối ưu Adam.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;15-98&lt;/strong&gt; — trích xuất đặc trưng và học chuyển giao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;25-98&lt;/strong&gt; — học sâu Bayesian và bất định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;26-06&lt;/strong&gt; — mục tổng hợp LLM (toán tiền huấn luyện, phục vụ, cơ chế nội tại, chưng cất; chỉ gồm câu hỏi gốc).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mỗi bài bổ trợ gồm 3–6 câu hỏi &lt;strong&gt;gốc&lt;/strong&gt; kèm gợi ý ngắn, không viết lại phần lý thuyết đã học.&lt;/p&gt;

&lt;h2 id=&quot;ghi-công-và-lưu-ý-bản-quyền&quot;&gt;Ghi công và lưu ý bản quyền&lt;/h2&gt;

&lt;p&gt;Kashani, S., và Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;. arXiv:2201.00650. GitHub: &lt;a href=&quot;https://github.com/BoltzmannEntropy/interviews.ai&quot;&gt;BoltzmannEntropy/interviews.ai&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Ngân hàng câu hỏi có lời giải thuộc quyền tác giả của cuốn sách. Khóa học này chỉ dẫn tiêu đề, tên tác giả, mã arXiv và tên chủ đề khái quát, đồng thời bổ sung bộ câu hỏi luyện tập riêng. &lt;strong&gt;Người học tự tải sách từ arXiv&lt;/strong&gt; (hoặc trang GitHub / interviews.ai chính thức); không đưa tệp PDF vào kho lưu trữ này và không dán các đoạn trích nguyên văn lớn từ sách vào &lt;em&gt;pull request&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, tiếng Anh. Cung cấp khung đề cương tổng thể tương ứng với bản đồ các chủ đề phỏng vấn trong lộ trình này.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Bổ sung mảng kiến thức hiện đại về mô hình ngôn ngữ lớn — phần chưa có mặt khi các tài liệu phỏng vấn trước đây được biên soạn.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Hướng dẫn tự triển khai chi tiết thuật toán lan truyền ngược, hỗ trợ trực tiếp cho kỹ năng tự suy diễn công thức khi phỏng vấn.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-01 Vì sao học sâu?</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_01_Why_Deep_Learning/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_01_Why_Deep_Learning</id>
   <content type="html">&lt;p&gt;Nếu các thuật toán kinh điển như Random Forest, XGBoost hay SVM đã hoạt động xuất sắc suốt nhiều thập kỷ, vì sao thế giới lại đổ hàng trăm tỷ đô-la vào GPU và Học sâu? Câu trả lời không nằm ở sự cường điệu truyền thông, mà nằm ở &lt;strong&gt;nút thắt đặc trưng&lt;/strong&gt; (&lt;em&gt;feature bottleneck&lt;/em&gt;) trên dữ liệu phi cấu trúc: ảnh, video, âm thanh và ngôn ngữ tự nhiên. Bài tổng quan này định vị chính xác nơi Học sâu tạo ra bước nhảy vọt về chất, đồng thời giữ cho bạn cái đầu lạnh để chọn đúng công cụ cho đúng bài toán.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-lý-giải-vì-sao-học-sâu&quot;&gt;Kiến thức cần nhớ: Ba trụ cột lý giải “Vì sao Học sâu?”&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Giới hạn của Đặc trưng Thủ công (Hand-crafted Features)&lt;/strong&gt;:
Các bộ mô tả cổ điển như SIFT, HOG (ảnh) hay TF-IDF (văn bản) tốn công sức chuyên gia thiết kế, dễ gãy khi đổi ánh sáng, góc chụp hay ngữ cảnh ngôn ngữ, và không thể tinh chỉnh theo hàm mất mát cuối cùng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Định lý Biểu diễn Sâu vs. Nông (Depth Efficiency)&lt;/strong&gt;:
Nhiều hàm phức tạp đòi hỏi số nơ-ron tăng theo hàm mũ nếu chỉ dùng 1 tầng ẩn, nhưng chỉ cần số nơ-ron tuyến tính khi xếp nhiều tầng sâu tái sử dụng đặc trưng trung gian.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tiêu chí Chọn Công cụ Thực tế (DL vs. Classical ML)&lt;/strong&gt;:
Dữ liệu bảng (tabular) cỡ nhỏ–trung bình thường là sân nhà của Gradient Boosted Trees (XGBoost, LightGBM); còn dữ liệu phi cấu trúc quy mô lớn, đa phương thức (multimodal) là lãnh địa thống trị tuyệt đối của Học sâu.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-định-lượng-hai-bài-toán-thực-tế-để-quyết-định-có-dùng-deep-learning-hay-không&quot;&gt;Giải thích: So sánh định lượng hai bài toán thực tế để quyết định có dùng Deep Learning hay không&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Tiêu chí đánh giá&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Bài toán A: Dự đoán khách hàng rời bỏ (Bảng 20 cột, 8{,}000 dòng)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Bài toán B: Phân loại lỗi sản phẩm từ ảnh camera nhà máy (200{,}000 ảnh \(224\times 224\))&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Số chiều đầu vào thô&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(20\) đặc trưng đã có nghĩa rõ ràng&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(224 \times 224 \times 3 = 150{,}528\) điểm ảnh thô&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Khả năng kỹ sư tự tạo đặc trưng&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Cao (tỷ lệ dùng dịch vụ, số lần gọi CSKH)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Rất thấp (vết xước, vết nứt đổi góc sáng liên tục)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Lựa chọn tối ưu&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;XGBoost / LightGBM&lt;/strong&gt; (nhanh, chính xác, dễ giải thích SHAP)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Deep Learning (CNN / ViT pretrained)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Kỹ sư giỏi không phải người đem mạng nơ-ron 100 triệu tham số đi giải mọi bài toán, mà là người biết nhìn vào cấu trúc dữ liệu và số chiều để chọn vũ khí sắc nhất.&lt;/p&gt;

&lt;p&gt;Mục này giải thích lý do học sâu đạt hiệu quả cao và khi nào nên lựa chọn phương pháp này:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hạn chế của học máy truyền thống và điều làm học sâu khác biệt&lt;/strong&gt; — phân tích giới hạn của đặc trưng thủ công, biểu diễn cố định và lợi thế học biểu diễn phân cấp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khi nào dùng học sâu và hệ sinh thái&lt;/strong&gt; — các bài toán tiêu biểu, vai trò của dữ liệu và tính toán, quy trình triển khai, công cụ, tài liệu và xu hướng hiện nay.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=q6kJ71tEYqM&quot;&gt;Machine Learning vs Deep Learning&lt;/a&gt; — IBM Technology, tiếng Anh. So sánh những điểm học sâu bổ sung so với học máy cổ điển, trả lời trực tiếp câu hỏi trọng tâm của phần này.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, tiếng Anh. Phần mở đầu trình bày các yếu tố về quy mô dữ liệu và tính toán giúp học sâu phát triển, làm rõ bối cảnh của bài học.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Minh họa cách biểu diễn đặc trưng phân cấp giúp mạng sâu xử lý ảnh hiệu quả.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-01-02 Khi nào dùng học sâu và hệ sinh thái</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_01_02_When_to_Use_DL_and_Ecosystem/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_01_02_When_to_Use_DL_and_Ecosystem</id>
   <content type="html">&lt;p&gt;Có một câu nói nổi tiếng trong giới kỹ sư dữ liệu: &lt;em&gt;“Đừng dùng pháo đại bác để bắn chim sẻ.”&lt;/em&gt; Dù Học sâu đã chinh phục cờ vây, gập protein và ngôn ngữ tự nhiên, hàng nghìn hệ thống sản xuất thực tế trong ngân hàng, logistics và thương mại điện tử vẫn chạy nhanh hơn, rẻ hơn và chính xác hơn với hồi quy tuyến tính hoặc Gradient Boosted Trees. Bài học này cung cấp bộ khung ra quyết định thực dụng giữa Học sâu và Học máy truyền thống, đồng thời giới thiệu hệ sinh thái phần mềm—phần cứng (PyTorch, JAX, TensorFlow, CUDA, Hugging Face) đang vận hành ngành AI hiện nay.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trục-đánh-giá-khi-chọn-mô-hình-và-hệ-sinh-thái&quot;&gt;Kiến thức cần nhớ: Bốn trục đánh giá khi Chọn Mô hình và Hệ sinh thái&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Bản chất Dữ liệu (Phi cấu trúc vs. Bảng biểu)&lt;/strong&gt;:
Ảnh, âm thanh, văn bản, đồ thị phức tạp \(\to\) ưu tiên Deep Learning; bảng dữ liệu có cấu trúc với đặc trưng hỗn hợp (số + phân loại) cỡ nhỏ/trung bình \(\to\) ưu tiên XGBoost / LightGBM / CatBoost.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ràng buộc Độ trễ, Chi phí Phần cứng và Khả năng Giải thích&lt;/strong&gt;:
Triển khai trên vi điều khiển (Edge) hay ngành tài chính/y tế đòi hỏi giải trình từng quyết định cần cân nhắc mô hình gọn nhẹ, giải thích được, hoặc áp dụng chưng cất (&lt;em&gt;distillation&lt;/em&gt;) và lượng tử hóa (&lt;em&gt;quantization&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hạ tầng Tăng tốc Phần cứng (CPU vs. GPU / TPU)&lt;/strong&gt;:
CPU có ít nhân mạnh tối ưu cho xử lý tuần tự độ trễ thấp; GPU/TPU có hàng nghìn nhân tính toán song song thiết kế riêng cho phép nhân ma trận dày đặc (GEMM) và Tensor Cores.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hệ sinh thái Phần mềm Hiện đại&lt;/strong&gt;:
PyTorch thống trị nghiên cứu và phần lớn sản xuất nhờ đồ thị động trực quan; JAX mạnh về tính toán khoa học và biên dịch XLA; Hugging Face và ONNX/TensorRT kết nối mượt mà từ mã nguồn tới triển khai thực tế.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-tốc-độ-tính-toán-flops-và-lý-do-gpu-bỏ-xa-cpu-trong-deep-learning&quot;&gt;Giải thích: Tính tay tốc độ tính toán (FLOPs) và lý do GPU bỏ xa CPU trong Deep Learning&lt;/h3&gt;

&lt;p&gt;Xét một bước nhân ma trận đơn giản trong một lớp tuyến tính với mini-batch \(B = 64\), chiều vào \(d_{\text{in}} = 1024\), chiều ra \(d_{\text{out}} = 1024\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đếm số phép toán dấu phẩy động (FLOPs)&lt;/strong&gt;:
Mỗi phần tử đầu ra cần \(1024\) phép nhân và \(1024\) phép cộng (\(\approx 2 \times 1024\) FLOPs).
Với \(64 \times 1024\) phần tử đầu ra, tổng số phép toán là:
\(\text{FLOPs} = 2 \times 64 \times 1024 \times 1024 = 134{,}217{,}728 \approx 0.134\text{ GFLOPs}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;So sánh thời gian lý thuyết giữa CPU và GPU&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Một CPU văn phòng (~50 GFLOPs thực tế cho &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fp32&lt;/code&gt;): mất \(\frac{0.134}{50} \approx 2.68\text{ ms}\) cho riêng 1 lớp.&lt;/li&gt;
      &lt;li&gt;Một GPU hiện đại có Tensor Cores (~100{,}000 GFLOPs = 100 TFLOPs ở &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bf16&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fp16&lt;/code&gt;): chỉ mất \(\frac{0.134}{100{,}000} \approx 0.00134\text{ ms}\)—nhanh hơn về mặt tính toán tới &lt;strong&gt;2{,}000 lần&lt;/strong&gt;!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ý nghĩa thực tế&lt;/strong&gt;: Khi mạng có 100 lớp và huấn luyện trên 1 triệu mẫu, chênh lệch đó chính là khác biệt giữa &lt;strong&gt;chạy 1 buổi chiều&lt;/strong&gt; và &lt;strong&gt;chạy suốt 1 năm&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;khi-nào-nên-dùng-học-sâu&quot;&gt;Khi nào nên dùng học sâu&lt;/h2&gt;

&lt;h3 id=&quot;học-sâu-phát-huy-thế-mạnh-khi&quot;&gt;Học sâu phát huy thế mạnh khi:&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;✅ Có &lt;strong&gt;lượng dữ liệu lớn&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;✅ Cần học các &lt;strong&gt;mẫu phức tạp&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;✅ Dữ liệu đầu vào có &lt;strong&gt;số chiều cao&lt;/strong&gt; (ảnh, văn bản, âm thanh)&lt;/li&gt;
  &lt;li&gt;✅ Muốn &lt;strong&gt;học từ đầu đến cuối (&lt;em&gt;end-to-end&lt;/em&gt;)&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;✅ Có &lt;strong&gt;đủ tài nguyên tính toán&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;✅ Dữ liệu chứa các &lt;strong&gt;quan hệ phi tuyến&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;học-máy-truyền-thống-thường-phù-hợp-hơn-khi&quot;&gt;Học máy truyền thống thường phù hợp hơn khi:&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;⚠️ Tập dữ liệu nhỏ (&amp;lt; 1.000 mẫu)&lt;/li&gt;
  &lt;li&gt;⚠️ Yêu cầu cao về khả năng diễn giải (chẳng hạn một số quyết định hỗ trợ chẩn đoán y khoa)&lt;/li&gt;
  &lt;li&gt;⚠️ Tài nguyên tính toán hạn chế&lt;/li&gt;
  &lt;li&gt;⚠️ Bài toán đơn giản và đã hiểu rõ cấu trúc&lt;/li&gt;
  &lt;li&gt;⚠️ Cần thời gian huấn luyện nhanh&lt;/li&gt;
  &lt;li&gt;⚠️ Mô hình tuyến tính hoặc đặc trưng đơn giản đã đáp ứng đủ&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;một-số-dấu-mốc-ứng-dụng-tiêu-biểu&quot;&gt;Một số dấu mốc ứng dụng tiêu biểu&lt;/h2&gt;

&lt;h3 id=&quot;thị-giác-máy-tính-imagenet-2012&quot;&gt;Thị giác máy tính: ImageNet (2012)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;AlexNet&lt;/strong&gt; đạt tỷ lệ lỗi 15,3%, giảm mạnh so với mức khoảng 26% của các phương pháp truyền thống:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đánh dấu bước ngoặt của học sâu trong bài toán thị giác máy tính.&lt;/li&gt;
  &lt;li&gt;Thúc đẩy làn sóng nghiên cứu và ứng dụng mạng nơ-ron sâu.&lt;/li&gt;
  &lt;li&gt;Gồm kiến trúc CNN 8 tầng với khoảng 60 triệu tham số.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;xử-lý-ngôn-ngữ-tự-nhiên-dịch-máy&quot;&gt;Xử lý ngôn ngữ tự nhiên: dịch máy&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Google Neural Machine Translation (2016):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Giảm sai sót dịch thuật khoảng 60% so với hệ thống trước đó.&lt;/li&gt;
  &lt;li&gt;Vượt trội hơn các hệ thống dịch máy thống kê dựa trên cụm từ.&lt;/li&gt;
  &lt;li&gt;Nâng chất lượng bản dịch tiến gần hơn tới bản dịch của con người.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;trò-chơi-alphago-2016&quot;&gt;Trò chơi: AlphaGo (2016)&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Giành chiến thắng 4–1 trước kỳ thủ cờ vây hàng đầu thế giới Lee Sedol.&lt;/li&gt;
  &lt;li&gt;Kết hợp học sâu với thuật toán tìm kiếm cây Monte Carlo (&lt;em&gt;Monte Carlo Tree Search&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Chinh phục cờ vây — trò chơi có không gian trạng thái lớn hơn rất nhiều so với cờ vua.&lt;/li&gt;
  &lt;li&gt;Đưa ra nhiều nước đi mới mẻ ngoài các khuôn mẫu truyền thống.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;y-tế-phân-tích-ảnh-y-khoa&quot;&gt;Y tế: phân tích ảnh y khoa&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phát hiện ung thư da (2017):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mô hình học sâu đạt hiệu năng tương đương bác sĩ da liễu trên tập đánh giá.&lt;/li&gt;
  &lt;li&gt;Phân tích trực tiếp ảnh soi da (&lt;em&gt;dermoscopy&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Mở ra hướng hỗ trợ sàng lọc chuyên sâu ở quy mô rộng hơn.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tiếng-nói-trợ-lý-ảo&quot;&gt;Tiếng nói: trợ lý ảo&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Độ chính xác nhận dạng tiếng nói tiệm cận con người trong nhiều điều kiện.&lt;/li&gt;
  &lt;li&gt;Là thành phần cốt lõi trong Siri, Alexa và Google Assistant.&lt;/li&gt;
  &lt;li&gt;Hỗ trợ nhiều giọng đọc và ngôn ngữ khác nhau.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;hệ-thống-gợi-ý-luồng-video-ngắn-kiểu-tiktok&quot;&gt;Hệ thống gợi ý: luồng video ngắn (kiểu TikTok)&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_tiktok_title_nn.jpg&quot; alt=&quot;Thuật toán gợi ý và mạng neuron&quot; /&gt;
&lt;em&gt;Hình: Hệ thống gợi ý nội dung quy mô lớn dựa trên học máy và học sâu. (Minh họa từ video giải thích hệ thống gợi ý)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Đây là một ứng dụng quen thuộc hằng ngày của học máy và học sâu: tự động chọn video hoặc sản phẩm phù hợp cho từng người dùng. Một quy trình gợi ý điển hình thường gồm các thành phần sau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lọc cộng tác (&lt;em&gt;collaborative filtering&lt;/em&gt;):&lt;/strong&gt; Nếu nhiều người xem mục A cũng thích mục B, hệ thống sẽ gợi ý B cho người xem A mà không cần phân tích sâu nội dung của từng mục.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_collaborative_filtering.jpg&quot; alt=&quot;Lọc cộng tác: xem A gợi ý B&quot; /&gt;
&lt;em&gt;Hình: Khi người dùng xem mục A, hệ thống gợi ý các mục liên quan (B, …). (Minh họa từ video giải thích hệ thống gợi ý)&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gợi ý theo nội dung (&lt;em&gt;content-based&lt;/em&gt;):&lt;/strong&gt; So sánh đặc trưng của các mục (thẻ gắn, phong cách, mức giá, …) để tìm những mục có thuộc tính tương đồng.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_content_based_similar.jpg&quot; alt=&quot;Content-based: item A vs B&quot; /&gt;
&lt;em&gt;Hình: Tìm các mục tương tự dựa trên thuộc tính nội dung. (Minh họa từ video giải thích hệ thống gợi ý)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_item_feature_tags.jpg&quot; alt=&quot;Gán tag đặc trưng item&quot; /&gt;
&lt;em&gt;Hình: Mỗi mục được biểu diễn thông qua tập thẻ và đặc trưng. (Minh họa từ video giải thích hệ thống gợi ý)&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Khởi động lạnh (&lt;em&gt;cold start&lt;/em&gt;):&lt;/strong&gt; Khi người dùng hoặc nội dung mới chưa có lịch sử tương tác, lọc cộng tác kém hiệu quả nên hệ thống cần dựa vào đặc trưng nội dung, mức độ phổ biến chung hoặc khảo sát ngắn ban đầu.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_cold_start.jpg&quot; alt=&quot;Cold start: chưa có dữ liệu&quot; /&gt;
&lt;em&gt;Hình: Trạng thái chưa có lịch sử tương tác — bài toán khởi động lạnh (&lt;/em&gt;cold start&lt;em&gt;). (Minh họa từ video giải thích hệ thống gợi ý)&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Xếp hạng và tín hiệu tương tác:&lt;/strong&gt; Hệ thống sử dụng các tín hiệu như lượt thích, thời lượng xem hoặc hành động bỏ qua để chọn ra ứng viên phù hợp nhất trong thời gian rất ngắn.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_engagement_candidates.jpg&quot; alt=&quot;Ứng viên và tín hiệu engagement&quot; /&gt;
&lt;em&gt;Hình: Từ nhiều video ứng viên, hệ thống xếp hạng và chọn nội dung phù hợp theo hành vi xem. (Minh họa từ video giải thích hệ thống gợi ý)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Đây là ví dụ rõ nét về học sâu ở quy mô hàng tỷ người dùng: dữ liệu rất lớn, phản hồi theo thời gian thực và phải cân bằng đồng thời nhiều mục tiêu (mức độ gắn kết, tính đa dạng và an toàn nội dung). Chi tiết về &lt;em&gt;embedding&lt;/em&gt; và kiến trúc &lt;em&gt;two-tower&lt;/em&gt; được trình bày ở Chương 18; cơ chế khám phá như ε-greedy nằm ở Chương 20.&lt;/p&gt;

&lt;h2 id=&quot;lợi-thế-về-dữ-liệu&quot;&gt;Lợi thế về dữ liệu&lt;/h2&gt;

&lt;h3 id=&quot;vì-sao-thêm-dữ-liệu-giúp-cải-thiện-mô-hình&quot;&gt;Vì sao thêm dữ liệu giúp cải thiện mô hình&lt;/h3&gt;

&lt;p&gt;Học máy truyền thống thường bão hòa sau một ngưỡng dữ liệu:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Performance
    |     _______________
    |    /
    |   /
    |  /
    |_/________________
         Amount of Data
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Học sâu có khả năng tận dụng lượng dữ liệu ngày càng lớn:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Performance
    |              /
    |            /
    |          /
    |        /
    |      /
    |    /
    |__/________________
         Amount of Data
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;quy-luật-mở-rộng-scaling-law&quot;&gt;Quy luật mở rộng (&lt;em&gt;scaling law&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Quan sát thực nghiệm cho thấy sai số của mô hình học sâu thường giảm theo quy luật lũy thừa của kích thước dữ liệu:&lt;/p&gt;

\[\text{Error} \propto \frac{1}{(\text{Data size})^\alpha}\]

&lt;p&gt;trong đó \(\alpha \approx 0.5\) trên nhiều tác vụ.&lt;/p&gt;

&lt;div class=&quot;textbook-theorem&quot;&gt;
  &lt;p&gt;&lt;strong&gt;Hệ quả:&lt;/strong&gt;&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;Tăng dữ liệu gấp 4 lần → giảm sai số khoảng 2 lần.&lt;/li&gt;
    &lt;li&gt;Tăng dữ liệu gấp 100 lần → giảm sai số khoảng 10 lần.&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;

&lt;h2 id=&quot;yêu-cầu-về-tính-toán&quot;&gt;Yêu cầu về tính toán&lt;/h2&gt;

&lt;h3 id=&quot;vai-trò-của-gpu&quot;&gt;Vai trò của GPU&lt;/h3&gt;

&lt;p&gt;Việc huấn luyện mạng nơ-ron sâu trở nên khả thi trong thực tế phần lớn nhờ khả năng tính toán song song của GPU:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Phép toán&lt;/th&gt;
      &lt;th&gt;Thời gian CPU&lt;/th&gt;
      &lt;th&gt;Thời gian GPU&lt;/th&gt;
      &lt;th&gt;Mức tăng tốc&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Nhân ma trận (1000×1000)&lt;/td&gt;
      &lt;td&gt;100ms&lt;/td&gt;
      &lt;td&gt;5ms&lt;/td&gt;
      &lt;td&gt;20×&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Tầng Conv2D&lt;/td&gt;
      &lt;td&gt;1000ms&lt;/td&gt;
      &lt;td&gt;10ms&lt;/td&gt;
      &lt;td&gt;100×&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Huấn luyện mô hình đầy đủ&lt;/td&gt;
      &lt;td&gt;Ngày/Tuần&lt;/td&gt;
      &lt;td&gt;Giờ/Ngày&lt;/td&gt;
      &lt;td&gt;10–100×&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;hạ-tầng-tính-toán-hiện-đại&quot;&gt;Hạ tầng tính toán hiện đại&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Điện toán đám mây:&lt;/strong&gt; AWS, Google Cloud, Azure.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phần cứng chuyên dụng:&lt;/strong&gt; TPU và các bộ xử lý mạng nơ-ron (&lt;em&gt;Neural Processing Units&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Huấn luyện phân tán:&lt;/strong&gt; chạy song song trên nhiều GPU và nhiều máy chủ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ chính xác hỗn hợp (&lt;em&gt;mixed precision&lt;/em&gt;):&lt;/strong&gt; sử dụng định dạng FP16 để tăng tốc độ huấn luyện và tiết kiệm bộ nhớ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;quy-trình-xây-dựng-hệ-thống-học-sâu&quot;&gt;Quy trình xây dựng hệ thống học sâu&lt;/h2&gt;

&lt;p&gt;Một dự án học sâu điển hình trải qua 7 bước lặp lại:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Thu thập dữ liệu:&lt;/strong&gt; xây dựng tập dữ liệu đủ lớn, đảm bảo chất lượng và độ đa dạng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn bị dữ liệu:&lt;/strong&gt; làm sạch, tiền xử lý, chia tập huấn luyện/kiểm định/kiểm thử (&lt;em&gt;train/val/test&lt;/em&gt;) và tăng cường dữ liệu (&lt;em&gt;data augmentation&lt;/em&gt;) khi cần.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thiết kế mô hình:&lt;/strong&gt; lựa chọn kiến trúc, định nghĩa các tầng, kết nối và thiết lập siêu tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Huấn luyện:&lt;/strong&gt; khởi tạo tham số, chạy chu trình lan truyền xuôi → tính mất mát → lan truyền ngược → cập nhật trọng số và theo dõi chỉ số đánh giá.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đánh giá:&lt;/strong&gt; đo hiệu năng trên tập giữ lại, phân tích lỗi sai và trực quan hóa dự đoán.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lặp và cải tiến:&lt;/strong&gt; cải thiện chất lượng dữ liệu, điều chỉnh kiến trúc và tinh chỉnh siêu tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Triển khai:&lt;/strong&gt; tối ưu tốc độ suy luận, đưa vào môi trường vận hành (&lt;em&gt;production&lt;/em&gt;) và giám sát hiệu năng liên tục.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;công-cụ-và-framework&quot;&gt;Công cụ và framework&lt;/h2&gt;

&lt;h3 id=&quot;các-framework-học-sâu-phổ-biến&quot;&gt;Các framework học sâu phổ biến&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;PyTorch:&lt;/strong&gt; hỗ trợ đồ thị tính toán động, giao diện gần gũi với Python và rất phổ biến trong nghiên cứu lẫn thực tế.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;TensorFlow/Keras:&lt;/strong&gt; hệ sinh thái phong phú, sẵn sàng cho triển khai sản xuất (&lt;em&gt;production&lt;/em&gt;) với nhiều công cụ hỗ trợ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;JAX:&lt;/strong&gt; tiếp cận theo phong cách lập trình hàm, linh hoạt, hiệu năng cao và ngày càng được dùng rộng rãi trong nghiên cứu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;thư-viện-hỗ-trợ&quot;&gt;Thư viện hỗ trợ&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;NumPy:&lt;/strong&gt; tính toán mảng số học.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pandas:&lt;/strong&gt; xử lý và phân tích dữ liệu dạng bảng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matplotlib/Seaborn:&lt;/strong&gt; trực quan hóa dữ liệu và kết quả.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scikit-learn:&lt;/strong&gt; tiền xử lý dữ liệu, mô hình học máy cổ điển và các chỉ số đánh giá.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;sách-khuyến-nghị-cho-khóa-học&quot;&gt;Sách khuyến nghị cho khóa học&lt;/h2&gt;

&lt;p&gt;Để củng cố kiến thức, bạn có thể tham khảo các tài liệu sau:&lt;/p&gt;

&lt;h3 id=&quot;1-deep-learning--ian-goodfellow-yoshua-bengio-và-aaron-courville&quot;&gt;1. &lt;strong&gt;Deep Learning&lt;/strong&gt; — Ian Goodfellow, Yoshua Bengio và Aaron Courville&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Sách giáo khoa chuẩn mực, bao quát toàn diện cả nền tảng toán học lẫn lý thuyết học sâu.&lt;/li&gt;
  &lt;li&gt;Có bản đọc miễn phí trực tuyến tại &lt;a href=&quot;http://www.deeplearningbook.org/&quot;&gt;deeplearningbook.org&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phù hợp cho:&lt;/strong&gt; củng cố nền tảng toán học và chiều sâu lý thuyết.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-hands-on-machine-learning-with-scikit-learn-keras-and-tensorflow--aurélien-géron&quot;&gt;2. &lt;strong&gt;Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow&lt;/strong&gt; — Aurélien Géron&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Hướng dẫn thực hành từng bước với nhiều ví dụ mã nguồn và dự án hoàn chỉnh sử dụng Scikit-Learn, TensorFlow và Keras.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phù hợp cho:&lt;/strong&gt; kỹ năng cài đặt và triển khai dự án thực tế.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-understanding-deep-learning--simon-jd-prince&quot;&gt;3. &lt;strong&gt;Understanding Deep Learning&lt;/strong&gt; — Simon J.D. Prince&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Tài liệu nhập môn hiện đại, giải thích rõ ràng bằng trực giác và hình minh họa chất lượng, bao gồm cả các kiến trúc mới như Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phù hợp cho:&lt;/strong&gt; xây dựng trực giác và hiểu khái niệm một cách trực quan.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-mit-deep-learning-book&quot;&gt;4. &lt;strong&gt;MIT Deep Learning Book&lt;/strong&gt;&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Cách tiếp cận học thuật chặt chẽ, nhấn mạnh vào chứng minh, suy diễn toán học và góc nhìn nghiên cứu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phù hợp cho:&lt;/strong&gt; đào sâu lý thuyết và chuẩn bị cho công việc nghiên cứu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;5-deep-learning-interviews--shlomo-kashani-và-amir-ivry&quot;&gt;5. &lt;strong&gt;Deep Learning Interviews&lt;/strong&gt; — Shlomo Kashani và Amir Ivry&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Tuyển tập bài toán phỏng vấn và thi cử kèm lời giải miễn phí.&lt;/li&gt;
  &lt;li&gt;PDF: &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt; — GitHub: &lt;a href=&quot;https://github.com/BoltzmannEntropy/interviews.ai&quot;&gt;interviews.ai&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Khóa học này ánh xạ các &lt;em&gt;chủ đề&lt;/em&gt; trong sách (không sao chép lại câu hỏi) sang các bài &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;*-98&lt;/code&gt; tùy chọn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phù hợp cho:&lt;/strong&gt; luyện phỏng vấn sau khi học xong phần lý thuyết tương ứng; bắt đầu từ bài &lt;strong&gt;01-98&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;gợi-ý-lộ-trình-đọc-sách&quot;&gt;Gợi ý lộ trình đọc sách&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Người mới bắt đầu:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Đọc &lt;em&gt;Understanding Deep Learning&lt;/em&gt; để xây dựng trực giác.&lt;/li&gt;
  &lt;li&gt;Học theo cấu trúc của khóa học này.&lt;/li&gt;
  &lt;li&gt;Tra cứu &lt;em&gt;Hands-On ML&lt;/em&gt; khi thực hành cài đặt.&lt;/li&gt;
  &lt;li&gt;Đọc sâu &lt;em&gt;Deep Learning&lt;/em&gt; để củng cố lý thuyết.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Trình độ trung cấp:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Dùng khóa học này làm khung chính.&lt;/li&gt;
  &lt;li&gt;Tham khảo &lt;em&gt;Hands-On ML&lt;/em&gt; để nắm kinh nghiệm triển khai.&lt;/li&gt;
  &lt;li&gt;Đọc các chương tương ứng trong &lt;em&gt;Deep Learning&lt;/em&gt; để đào sâu.&lt;/li&gt;
  &lt;li&gt;Dùng &lt;em&gt;Understanding DL&lt;/em&gt; khi cần làm rõ trực giác.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Trình độ nâng cao:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Dùng khóa học này để rà soát hệ thống kiến thức.&lt;/li&gt;
  &lt;li&gt;Nghiên cứu &lt;em&gt;Deep Learning&lt;/em&gt; cho phần lý thuyết chặt chẽ.&lt;/li&gt;
  &lt;li&gt;Áp dụng kỹ thuật thực hành từ &lt;em&gt;Hands-On ML&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;Tham khảo thêm sách MIT cho các chi tiết hướng nghiên cứu.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;xu-hướng-hiện-tại-20242025&quot;&gt;Xu hướng hiện tại (2024–2025)&lt;/h2&gt;

&lt;h3 id=&quot;mô-hình-ngôn-ngữ-lớn-llm&quot;&gt;Mô hình ngôn ngữ lớn (LLM)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Các họ mô hình như GPT-4, Claude, Gemini.&lt;/li&gt;
  &lt;li&gt;Quy mô từ hàng tỷ đến hàng nghìn tỷ tham số.&lt;/li&gt;
  &lt;li&gt;Xuất hiện nhiều năng lực nổi (&lt;em&gt;emergent capabilities&lt;/em&gt;) khi tăng quy mô.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;mô-hình-đa-phương-thức-multimodal&quot;&gt;Mô hình đa phương thức (&lt;em&gt;multimodal&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;CLIP kết hợp thị giác và ngôn ngữ.&lt;/li&gt;
  &lt;li&gt;GPT-4V xử lý đồng thời văn bản và hình ảnh.&lt;/li&gt;
  &lt;li&gt;Hướng tới biểu diễn thống nhất qua nhiều dạng dữ liệu (&lt;em&gt;modality&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;ai-hiệu-quả&quot;&gt;AI hiệu quả&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Nén mô hình và lượng tử hóa (&lt;em&gt;quantization&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Tìm kiếm kiến trúc mạng (&lt;em&gt;neural architecture search&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Triển khai trên thiết bị biên (&lt;em&gt;edge devices&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;mô-hình-nền-tảng-foundation-models&quot;&gt;Mô hình nền tảng (&lt;em&gt;foundation models&lt;/em&gt;)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Tiền huấn luyện trên tập dữ liệu rất lớn.&lt;/li&gt;
  &lt;li&gt;Tinh chỉnh (&lt;em&gt;fine-tune&lt;/em&gt;) cho từng tác vụ cụ thể.&lt;/li&gt;
  &lt;li&gt;Ứng dụng học chuyển giao ở quy mô rộng.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;thách-thức-phía-trước&quot;&gt;Thách thức phía trước&lt;/h2&gt;

&lt;h3 id=&quot;thách-thức-kỹ-thuật&quot;&gt;Thách thức kỹ thuật&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu quả mẫu:&lt;/strong&gt; học tốt từ ít dữ liệu hơn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ bền vững:&lt;/strong&gt; duy trì hiệu năng khi phân phối dữ liệu thay đổi (&lt;em&gt;domain shift&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khả năng diễn giải:&lt;/strong&gt; hiểu rõ cơ sở đằng sau quyết định của mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chi phí tính toán:&lt;/strong&gt; giảm chi phí cho cả huấn luyện lẫn suy luận.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;thách-thức-xã-hội&quot;&gt;Thách thức xã hội&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Thiên lệch thuật toán và tính công bằng.&lt;/li&gt;
  &lt;li&gt;Bảo vệ quyền riêng tư dữ liệu.&lt;/li&gt;
  &lt;li&gt;Tác động môi trường từ tiêu thụ năng lượng.&lt;/li&gt;
  &lt;li&gt;Ảnh hưởng đến thị trường lao động.&lt;/li&gt;
  &lt;li&gt;Rủi ro thông tin sai lệch (như &lt;em&gt;deepfake&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;p&gt;Học sâu đạt hiệu quả cao nhờ:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;✅ Học đặc trưng tự động.&lt;/li&gt;
  &lt;li&gt;✅ Mở rộng tốt theo quy mô dữ liệu và tính toán.&lt;/li&gt;
  &lt;li&gt;✅ Xử lý hiệu quả dữ liệu nhiều chiều.&lt;/li&gt;
  &lt;li&gt;✅ Đạt kết quả hàng đầu trên nhiều bài toán phức tạp.&lt;/li&gt;
  &lt;li&gt;✅ Hỗ trợ học từ đầu đến cuối (&lt;em&gt;end-to-end&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nên cân nhắc dùng học sâu khi:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Có tập dữ liệu lớn.&lt;/li&gt;
  &lt;li&gt;Bài toán chứa các mẫu phức tạp.&lt;/li&gt;
  &lt;li&gt;Có đủ tài nguyên tính toán.&lt;/li&gt;
  &lt;li&gt;Yêu cầu cao về độ chính xác.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Lĩnh vực này tiếp tục phát triển nhanh với nhiều kiến trúc, kỹ thuật và ứng dụng mới.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tiếp theo:&lt;/strong&gt; Chương sau sẽ đi sâu vào nền tảng mạng nơ-ron để hiểu cơ chế hoạt động bên trong của chúng.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ video của kênh &lt;em&gt;Machine Learning Thực Chiến&lt;/em&gt;. Nguồn gốc để tra cứu:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1444915507374636&quot;&gt;Thuật toán gợi ý (TikTok-style recommendation)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qYNweeDHiyU&quot;&gt;AI, Machine Learning, Deep Learning and Generative AI Explained&lt;/a&gt; — IBM Technology, tiếng Anh. Giúp xác định một bài toán thực sự cần học sâu hay chỉ cần học máy cổ điển.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, tiếng Anh. Giới thiệu các framework và yêu cầu quy mô dữ liệu gắn với phần hệ sinh thái trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=q6kJ71tEYqM&quot;&gt;Machine Learning vs Deep Learning&lt;/a&gt; — IBM Technology, tiếng Anh. Cung cấp tiêu chí đối chiếu nhanh trước khi quyết định dùng mô hình sâu thay cho mô hình đơn giản hơn.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-01-01 Hạn chế của học máy truyền thống và điều làm học sâu khác biệt</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_01_01_Limitations_and_What_Makes_DL_Different/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_01_01_Limitations_and_What_Makes_DL_Different</id>
   <content type="html">&lt;p&gt;Trước năm 2012, một nhóm nghiên cứu muốn xây dựng hệ thống nhận diện khuôn mặt phải dành hàng năm trời thiết kế các bộ lọc toán học thủ công để dò sống mũi, khóe mắt, viền môi—nhưng chỉ cần đối tượng đeo kính râm hoặc xoay nghiêng đầu 30 độ, cả hệ thống lại sụp đổ. Đó là “bức tường kính” của Học máy truyền thống. Bài học này phân tích trực diện bốn hạn chế cố hữu của các mô hình cổ điển—từ thiết kế đặc trưng thủ công đến lời nguyền chiều cao (&lt;em&gt;curse of dimensionality&lt;/em&gt;)—và chỉ ra cách Học sâu phá vỡ từng bức tường đó.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-bức-tường-của-học-máy-cổ-điển-và-cách-học-sâu-vượt-qua&quot;&gt;Kiến thức cần nhớ: Bốn bức tường của Học máy Cổ điển và cách Học sâu vượt qua&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Nút thắt Thiết kế Đặc trưng (Feature Engineering Bottleneck)&lt;/strong&gt;:
Học máy truyền thống tách rời hai khâu &lt;em&gt;trích xuất đặc trưng&lt;/em&gt; (con người làm) và &lt;em&gt;phân loại&lt;/em&gt; (máy học). Học sâu hợp nhất cả hai vào cùng một mạng khả vi được tối ưu từ đầu đến cuối.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lời nguyền Chiều cao (Curse of Dimensionality)&lt;/strong&gt;:
Trong không gian hàng trăm nghìn chiều của điểm ảnh, các phương pháp dựa trên khoảng cách trực tiếp (như k-NN hay RBF-SVM) thất bại vì mọi điểm đều cách đều nhau một cách kỳ lạ; mạng sâu giải quyết bằng cách chiếu dữ liệu xuống các đa tạp (&lt;em&gt;manifold&lt;/em&gt;) chiều thấp giàu ngữ nghĩa.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đường cong Hiệu năng theo Quy mô Dữ liệu (Data Scaling)&lt;/strong&gt;:
Khi dữ liệu tăng từ \(10^4\) lên \(10^7\) mẫu, mô hình tuyến tính hay cây nông sớm bão hòa do dung lượng biểu diễn hữu hạn; mạng sâu có thể mở rộng dung lượng mượt mà để tiếp tục hấp thụ tri thức mới.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Học Chuyển giao (Transfer Learning)&lt;/strong&gt;:
Đặc trưng học được ở các tầng đầu của mạng sâu trên tập ảnh lớn có tính phổ quát cao, cho phép tái sử dụng cho bài toán y tế hay công nghiệp chỉ có vài trăm ảnh—điều gần như bất khả thi với cây quyết định.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-lời-nguyền-chiều-cao-trong-không-gian-lưới-đơn-vị&quot;&gt;Giải thích: Tính tay “Lời nguyền Chiều cao” trong không gian lưới đơn vị&lt;/h3&gt;

&lt;p&gt;Giả sử bạn muốn phủ kín một không gian đặc trưng chuẩn hóa \([0, 1]^d\) bằng các ô lưới có cạnh dài \(0.1\) (tức chia mỗi trục thành 10 khoảng) để đảm bảo mọi điểm test đều có ít nhất một điểm train nằm gần:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Với &lt;strong&gt;\(d = 1\) chiều&lt;/strong&gt; (1 đặc trưng): cần \(10^1 = 10\) mẫu.&lt;/li&gt;
  &lt;li&gt;Với &lt;strong&gt;\(d = 2\) chiều&lt;/strong&gt;: cần \(10^2 = 100\) mẫu.&lt;/li&gt;
  &lt;li&gt;Với &lt;strong&gt;\(d = 10\) chiều&lt;/strong&gt;: cần \(10^{10} = 10\text{ tỷ}\) mẫu!&lt;/li&gt;
  &lt;li&gt;Với một ảnh nhỏ &lt;strong&gt;\(28 \times 28 = 784\) chiều&lt;/strong&gt;: số ô lưới là \(10^{784}\) (lớn hơn tổng số nguyên tử trong vũ trụ quan sát được \(\approx 10^{80}\) gấp vô số lần!).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Con số khủng khiếp này chứng minh một sự thật sâu sắc: &lt;strong&gt;Học sâu thành công không phải vì nó phủ kín không gian \(\mathbb{R}^{784}\)&lt;/strong&gt;, mà vì ảnh thật chỉ nằm trên một bề mặt cong (manifold) cực mảnh có cấu trúc cục bộ và đối xứng mà mạng nhiều tầng khai thác được!&lt;/p&gt;

&lt;h2 id=&quot;lợi-thế-của-học-sâu&quot;&gt;Lợi thế của học sâu&lt;/h2&gt;

&lt;p&gt;Học sâu trở thành hướng tiếp cận chủ đạo trong nhiều bài toán trí tuệ nhân tạo vì nó giải quyết được những hạn chế cốt lõi của học máy truyền thống.&lt;/p&gt;

&lt;h2 id=&quot;hạn-chế-của-học-máy-truyền-thống&quot;&gt;Hạn chế của học máy truyền thống&lt;/h2&gt;

&lt;h3 id=&quot;1-thiết-kế-đặc-trưng-thủ-công&quot;&gt;1. Thiết kế đặc trưng thủ công&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Cách tiếp cận truyền thống:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Trích xuất đặc trưng thủ công cho phân loại ảnh
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;calculate_histogram&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detect_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;extract_textures&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;compute_color_moments&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Sau đó huấn luyện bộ phân loại trên các đặc trưng này
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_svm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Hạn chế:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đòi hỏi kiến thức chuyên sâu về từng miền bài toán.&lt;/li&gt;
  &lt;li&gt;Tốn nhiều thời gian thiết kế và tinh chỉnh.&lt;/li&gt;
  &lt;li&gt;Dễ bỏ sót các mẫu thông tin quan trọng.&lt;/li&gt;
  &lt;li&gt;Khó tái sử dụng hoặc mở rộng sang các miền bài toán khác.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Cách tiếp cận học sâu:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Học đầu-cuối
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;build_cnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Tự động học đặc trưng!
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;2-biểu-diễn-cố-định&quot;&gt;2. Biểu diễn cố định&lt;/h3&gt;

&lt;p&gt;Học máy truyền thống phụ thuộc vào các đặc trưng thiết kế sẵn, vốn có các nhược điểm:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Không tự thích nghi theo phân phối dữ liệu.&lt;/li&gt;
  &lt;li&gt;Có thể không tối ưu cho mục tiêu dự đoán cụ thể.&lt;/li&gt;
  &lt;li&gt;Phải thiết kế lại gần như từ đầu khi chuyển sang bài toán mới.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ngược lại, học sâu &lt;strong&gt;tự học biểu diễn phù hợp&lt;/strong&gt; cho từng tác vụ trực tiếp từ dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;3-hạn-chế-về-khả-năng-mở-rộng&quot;&gt;3. Hạn chế về khả năng mở rộng&lt;/h3&gt;

&lt;p&gt;Trong nhiều bài toán phức tạp, &lt;strong&gt;học máy truyền thống&lt;/strong&gt; thường sớm bão hòa khi lượng dữ liệu tăng lên, còn &lt;strong&gt;học sâu&lt;/strong&gt; tiếp tục cải thiện hiệu năng khi có thêm dữ liệu và năng lực tính toán:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Traditional ML:  _______________  (bão hòa)
                     /
Deep Learning:     /  (tiếp tục cải thiện)
                  /
                 |
              Performance
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;điều-gì-làm-học-sâu-khác-biệt&quot;&gt;Điều gì làm học sâu khác biệt?&lt;/h2&gt;

&lt;h3 id=&quot;1-học-đặc-trưng-phân-cấp&quot;&gt;1. Học đặc trưng phân cấp&lt;/h3&gt;

&lt;p&gt;Mạng nơ-ron sâu học đặc trưng ở nhiều mức trừu tượng khác nhau. Chẳng hạn, với bài toán &lt;strong&gt;nhận diện khuôn mặt&lt;/strong&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Layer 1 (Low-level):    Cạnh, màu, mẫu đơn giản
         ↓
Layer 2 (Mid-level):    Mắt, mũi, bộ phận miệng
         ↓
Layer 3 (High-level):   Khuôn mặt hoàn chỉnh, biểu cảm
         ↓
Output:                  Danh tính người
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Cấu trúc phân cấp này tương đồng với cách con người tiếp nhận thông tin thị giác — đi từ các chi tiết đơn giản đến khái niệm hoàn chỉnh.&lt;/p&gt;

&lt;h3 id=&quot;2-học-từ-đầu-đến-cuối-end-to-end-learning&quot;&gt;2. Học từ đầu đến cuối (&lt;em&gt;end-to-end learning&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Quy trình truyền thống:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Raw Data → Preprocessing → Feature Extraction → Feature Selection → Model → Output
         (Thủ công)       (Thủ công)           (Thủ công)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Quy trình học sâu:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Raw Data → Neural Network → Output
         (Tất cả được học tự động)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;3-bộ-xấp-xỉ-hàm-phổ-quát&quot;&gt;3. Bộ xấp xỉ hàm phổ quát&lt;/h3&gt;

&lt;p&gt;Theo &lt;strong&gt;định lý xấp xỉ phổ quát&lt;/strong&gt;, một mạng nơ-ron chỉ cần một tầng ẩn với đủ số lượng nơ-ron có thể xấp xỉ bất kỳ hàm liên tục nào trên một miền đóng và bị chặn với độ chính xác tùy ý. Nhờ khả năng biểu diễn linh hoạt này, mạng sâu có thể học xấp xỉ nhiều dạng ánh xạ phức tạp như:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Phép biến đổi trên ảnh.&lt;/li&gt;
  &lt;li&gt;Cấu trúc và quy luật ngôn ngữ.&lt;/li&gt;
  &lt;li&gt;Chiến lược trong trò chơi.&lt;/li&gt;
  &lt;li&gt;Mô phỏng các hệ thống vật lý.&lt;/li&gt;
  &lt;li&gt;Ranh giới quyết định phi tuyến phức tạp.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=q6kJ71tEYqM&quot;&gt;Machine Learning vs Deep Learning&lt;/a&gt; — IBM Technology, tiếng Anh. Phân tích sự khác biệt giữa thiết kế đặc trưng thủ công và học biểu diễn tự động.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=CqOfi41LfDw&quot;&gt;The Essential Main Ideas of Neural Networks&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Minh họa ví dụ dữ liệu mà mô hình tuyến tính không khớp được nhưng một mạng nơ-ron nhỏ có thể giải quyết, làm rõ hạn chế được nêu trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, tiếng Anh. Đặt sự khác biệt giữa học máy cổ điển và học sâu vào bức tranh tổng thể về dữ liệu, tính toán và độ sâu mô hình.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01 Giới thiệu về Học sâu</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_00_Introduction</id>
   <content type="html">&lt;p&gt;Năm 2012, tại cuộc thi nhận dạng ảnh ImageNet danh giá, một mạng nơ-ron tích chập tên gọi AlexNet đã cắt giảm tỷ lệ lỗi top-5 từ 26% xuống chỉ còn 15.3%—bỏ xa đối thủ xếp thứ hai hơn 10 điểm phần trăm trong sự ngỡ ngàng của cả giới thị giác máy tính. Khoảnh khắc ấy không chỉ mở màn cho kỷ nguyên Học sâu (&lt;em&gt;Deep Learning&lt;/em&gt;), mà còn thay đổi hoàn toàn cách con người xây dựng phần mềm: thay vì tự tay viết hàng nghìn dòng luật &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if-else&lt;/code&gt;, ta dạy máy tính tự khám phá quy luật từ dữ liệu. Chương 01 sẽ đưa bạn đi từ trực giác tổng quan đến mô hình MNIST đầu tiên và tiêu chí thực chiến để biết khi nào nên—và không nên—dùng Học sâu.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-mảnh-ghép-khởi-đầu-hành-trình-học-sâu&quot;&gt;Kiến thức cần nhớ: Bốn mảnh ghép khởi đầu hành trình Học sâu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Bản chất của Học biểu diễn (Representation Learning)&lt;/strong&gt;:
Hiểu sự dịch chuyển từ trích xuất đặc trưng thủ công sang hệ thống nhiều tầng tự động xây dựng khái niệm từ thấp lên cao (điểm ảnh \(\to\) cạnh \(\to\) bộ phận \(\to\) vật thể).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Quy trình huấn luyện đầu tiên trên MNIST&lt;/strong&gt;:
Nắm trọn vòng lặp cốt lõi của mọi dự án PyTorch: nạp dữ liệu (&lt;em&gt;DataLoader&lt;/em&gt;) \(\to\) lan truyền xuôi (&lt;em&gt;forward&lt;/em&gt;) \(\to\) tính mất mát (&lt;em&gt;loss&lt;/em&gt;) \(\to\) lan truyền ngược (&lt;em&gt;backward&lt;/em&gt;) \(\to\) cập nhật trọng số (&lt;em&gt;step&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ranh giới giữa Học máy truyền thống và Học sâu&lt;/strong&gt;:
Biết cân nhắc đánh đổi giữa lượng dữ liệu, cấu trúc dữ liệu (bảng biểu vs. ảnh/văn bản/âm thanh), chi phí GPU và yêu cầu giải thích mô hình (&lt;em&gt;interpretability&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lộ trình học tập và Hệ sinh thái hiện đại&lt;/strong&gt;:
Kết nối kiến thức nền tảng từ mạng MLP sơ khai đến các mô hình nền tảng (&lt;em&gt;foundation models&lt;/em&gt;) và lộ trình luyện phỏng vấn chuyên sâu.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-tay-chi-phí-và-độ-mở-rộng-của-hệ-thống-dựa-trên-luật-vs-mạng-học-sâu&quot;&gt;Giải thích: So sánh tay chi phí và độ mở rộng của hệ thống dựa trên luật vs. mạng Học sâu&lt;/h3&gt;

&lt;p&gt;Giả sử bạn cần nhận diện chữ số viết tay ảnh đen trắng kích thước \(28 \times 28\) pixel (bài toán MNIST):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kích thước không gian đầu vào&lt;/strong&gt;: Mỗi ảnh là một vector có \(28 \times 28 = 784\) số thực trong đoạn \([0, 1]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cách tiếp cận viết luật thủ công&lt;/strong&gt;: Một số “7” có thể nghiêng trái, nghiêng phải, có gạch ngang ở giữa hoặc không, nét đậm hoặc mảnh. Số cấu hình điểm ảnh hợp lệ lên tới hàng tỷ—không thể viết đủ điều kiện &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;if-else&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cách tiếp cận Học sâu (MLP 2 tầng ẩn 128–64–10)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Tầng 1: \(784 \times 128 + 128 = 100{,}480\) tham số (học các nét cơ bản).&lt;/li&gt;
      &lt;li&gt;Tầng 2: \(128 \times 64 + 64 = 8{,}256\) tham số (ghép nét thành vòng tròn, góc nhọn).&lt;/li&gt;
      &lt;li&gt;Tầng ra: \(64 \times 10 + 10 = 650\) tham số (chấm điểm 10 chữ số 0–9).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tổng cộng&lt;/strong&gt;: Chỉ \(109{,}386\) tham số (~0.44 MB ở &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt;), huấn luyện chưa đầy 1 phút trên CPU/GPU phổ thông đã đạt độ chính xác &amp;gt;97%!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chương này giới thiệu tổng quan về học sâu (&lt;em&gt;deep learning&lt;/em&gt;) và cách tiếp cận khóa học:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Học sâu là gì&lt;/strong&gt; — tổng quan khái niệm, nền tảng toán học và trực giác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước đầu với MNIST&lt;/strong&gt; — đoạn mã minh họa, các khái niệm liên quan và các bài báo nền tảng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hướng dẫn khóa học và cách học hiệu quả&lt;/strong&gt; — ứng dụng, thách thức, lộ trình, điều kiện tiên quyết và tư duy học tập.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (2022–2026):&lt;/strong&gt; Sau bài MNIST, bạn có thể xem thêm &lt;strong&gt;01-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; về quy trình làm việc với mô hình nền tảng (&lt;em&gt;foundation model&lt;/em&gt;), quy luật mở rộng Chinchilla và hệ sinh thái mô hình trọng số mở.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tùy chọn (luyện phỏng vấn):&lt;/strong&gt; Xem &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt; để tham khảo kế hoạch học kết hợp sách của Kashani &amp;amp; Ivry (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) cùng các bài luyện tập bổ trợ theo từng chương.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, tiếng Anh. Bài giảng MIT 2024 giới thiệu học sâu là gì và cách huấn luyện mạng nơ-ron đầu tiên.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Minh họa mạng nhận dạng chữ số viết tay, tương ứng với cấu trúc mạng được giới thiệu trong bài &lt;em&gt;Học sâu là gì&lt;/em&gt;.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qYNweeDHiyU&quot;&gt;AI, Machine Learning, Deep Learning and Generative AI Explained&lt;/a&gt; — IBM Technology, tiếng Anh. Phân biệt rõ AI, học máy, học sâu và AI tạo sinh, khớp với bức tranh tổng quan của chương.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-00-03 Hướng dẫn khóa học và cách học hiệu quả</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_00_03_Course_Guide_and_How_to_Succeed/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_00_03_Course_Guide_and_How_to_Succeed</id>
   <content type="html">&lt;p&gt;Rất nhiều người bắt đầu học Deep Learning với tinh thần hừng hực, xem liền tù tì hàng chục giờ video bài giảng, sao chép sạch sẽ các notebook có sẵn—nhưng hai tháng sau, khi đứng trước một tập dữ liệu mới hoàn toàn, họ lại không biết bắt đầu từ đâu và mất phương hướng trước hàng trăm siêu tham số. Học sâu là một kỹ năng kết hợp giữa &lt;strong&gt;tư duy toán học&lt;/strong&gt; và &lt;strong&gt;kỷ luật thực nghiệm kỹ thuật&lt;/strong&gt;. Bài hướng dẫn này trình bày bức tranh ứng dụng thực tế cùng chiến lược học tập chủ động để bạn biến kiến thức thụ động thành năng lực giải quyết bài toán thật.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-nguyên-tắc-vàng-để-làm-chủ-học-sâu-hiệu-quả&quot;&gt;Kiến thức cần nhớ: Bốn nguyên tắc vàng để làm chủ Học sâu hiệu quả&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Học theo vòng lặp Lý thuyết \(\leftrightarrow\) Cài đặt từ đầu \(\leftrightarrow\) Thực nghiệm&lt;/strong&gt;:
Đừng chỉ đọc công thức rồi bỏ qua, cũng đừng chỉ gọi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.fit()&lt;/code&gt; như hộp đen. Tự cài lại lan truyền ngược bằng NumPy một lần sẽ giúp bạn hiểu sâu hơn đọc mười bài blog.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kỹ năng Gỡ lỗi Khoa học (Systematic Debugging)&lt;/strong&gt;:
Luôn kiểm tra mô hình trên một tập cực nhỏ (ví dụ 10–32 mẫu) để chắc chắn mạng có thể &lt;em&gt;overfit&lt;/em&gt; tới loss \(\approx 0\) trước khi huấn luyện toàn tập—đây là bài test nhanh phát hiện 80% lỗi code.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Quản trị Thực nghiệm và Thước đo Baseline&lt;/strong&gt;:
Mọi thay đổi kiến trúc hay siêu tham số chỉ có ý nghĩa khi so sánh với một &lt;em&gt;baseline&lt;/em&gt; đơn giản (như hồi quy logistic hoặc MLP nhỏ) trên cùng tập validation cố định và cùng hạt giống ngẫu nhiên (&lt;em&gt;random seed&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kết nối Kiến trúc với Bản chất Dữ liệu&lt;/strong&gt;:
Nhìn thấy sợi dây xuyên suốt khóa học: MLP cho dữ liệu bảng/vector \(\to\) CNN cho ảnh có tính cục bộ không gian \(\to\) RNN/Transformer cho chuỗi và ngôn ngữ \(\to\) Mô hình sinh cho phân phối dữ liệu.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-nhanh-ngân-sách-học-tập-và-phép-thử-overfit-1-batch&quot;&gt;Giải thích: Tính nhanh ngân sách học tập và phép thử “Overfit 1 Batch”&lt;/h3&gt;

&lt;p&gt;Giả sử bạn có một tập dữ liệu phân loại 5 lớp gồm 10{,}000 mẫu và muốn kiểm chứng code huấn luyện mới viết có đúng không trước khi chạy 50 epoch tốn 2 giờ:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bước 1 — Thiết lập kỳ vọng toán học ở bước 0&lt;/strong&gt;:
Với 5 lớp cân bằng, dự đoán ngẫu nhiên có xác suất \(1/5 = 0.2\), nên loss ban đầu phải gần \(-\ln(0.2) = \ln(5) \approx 1.609\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 2 — Lấy đúng 1 mini-batch 16 mẫu và tắt Dropout/Weight Decay&lt;/strong&gt;:
Chạy 100 bước tối ưu chỉ trên đúng 16 mẫu này.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bước 3 — Chẩn đoán bằng con số&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Nếu loss giảm mượt từ \(\approx 1.61 \to 0.40 \to 0.02\) và độ chính xác trên 16 mẫu đạt \(16/16 = 100\%\): đồ thị tính toán, nhãn và gradient đều sạch!&lt;/li&gt;
      &lt;li&gt;Nếu loss đứng yên quanh \(1.61\): khả năng cao bạn quên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;optimizer.step()&lt;/code&gt;, learning rate quá nhỏ, hoặc lỡ truyền xác suất (đã qua Softmax) vào &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.CrossEntropyLoss&lt;/code&gt; (vốn nhận logits)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Thói quen dành 2 phút cho bài kiểm tra định lượng nhỏ này sẽ tiết kiệm cho bạn hàng chục giờ chạy GPU vô ích.&lt;/p&gt;

&lt;h2 id=&quot;ứng-dụng-của-học-sâu&quot;&gt;Ứng dụng của học sâu&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Deep_Learning_Applications.png/800px-Deep_Learning_Applications.png&quot; alt=&quot;Deep Learning Applications&quot; /&gt;
&lt;em&gt;Hình: Các ứng dụng của học sâu trong nhiều lĩnh vực. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;thị-giác-máy-tính&quot;&gt;Thị giác máy tính&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Phân loại ảnh&lt;/li&gt;
  &lt;li&gt;Phát hiện đối tượng&lt;/li&gt;
  &lt;li&gt;Phân đoạn ngữ nghĩa&lt;/li&gt;
  &lt;li&gt;Nhận diện khuôn mặt&lt;/li&gt;
  &lt;li&gt;Sinh ảnh&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;xử-lý-ngôn-ngữ-tự-nhiên&quot;&gt;Xử lý ngôn ngữ tự nhiên&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Dịch máy&lt;/li&gt;
  &lt;li&gt;Phân tích cảm xúc&lt;/li&gt;
  &lt;li&gt;Hỏi–đáp&lt;/li&gt;
  &lt;li&gt;Sinh văn bản (như họ mô hình GPT)&lt;/li&gt;
  &lt;li&gt;Hiểu ngôn ngữ (như BERT)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tiếng-nói-và-âm-thanh&quot;&gt;Tiếng nói và âm thanh&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Nhận dạng tiếng nói&lt;/li&gt;
  &lt;li&gt;Tổng hợp văn bản thành tiếng nói&lt;/li&gt;
  &lt;li&gt;Sinh nhạc&lt;/li&gt;
  &lt;li&gt;Nhân bản giọng nói&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;học-tăng-cường&quot;&gt;Học tăng cường&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Chơi trò chơi (cờ vua, cờ vây, Atari)&lt;/li&gt;
  &lt;li&gt;Điều khiển robot&lt;/li&gt;
  &lt;li&gt;Lái xe tự hành&lt;/li&gt;
  &lt;li&gt;Tối ưu hóa phân bổ tài nguyên&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;y-tế&quot;&gt;Y tế&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Hỗ trợ chẩn đoán bệnh từ ảnh y khoa&lt;/li&gt;
  &lt;li&gt;Khám phá thuốc&lt;/li&gt;
  &lt;li&gt;Dự đoán cấu trúc gập protein (AlphaFold)&lt;/li&gt;
  &lt;li&gt;Y học cá nhân hóa&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;các-lĩnh-vực-khác&quot;&gt;Các lĩnh vực khác&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Dự báo tài chính&lt;/li&gt;
  &lt;li&gt;Hệ thống gợi ý&lt;/li&gt;
  &lt;li&gt;Mô hình hóa khí hậu&lt;/li&gt;
  &lt;li&gt;Khám phá khoa học&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;thách-thức-và-hạn-chế&quot;&gt;Thách thức và hạn chế&lt;/h2&gt;

&lt;h3 id=&quot;thách-thức-hiện-tại&quot;&gt;Thách thức hiện tại&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Yêu cầu dữ liệu:&lt;/strong&gt; Thường cần tập dữ liệu có nhãn quy mô lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chi phí tính toán:&lt;/strong&gt; Huấn luyện các mô hình lớn đòi hỏi hạ tầng và chi phí cao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khả năng diễn giải:&lt;/strong&gt; Mô hình thường mang tính “hộp đen”, khó giải thích quyết định bên trong.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khả năng khái quát hóa:&lt;/strong&gt; Dễ gặp quá khớp (&lt;em&gt;overfitting&lt;/em&gt;) hoặc suy giảm hiệu năng khi phân phối dữ liệu thay đổi (&lt;em&gt;domain shift&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ bền vững:&lt;/strong&gt; Nhạy cảm với các mẫu đối kháng (&lt;em&gt;adversarial examples&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vấn đề đạo đức:&lt;/strong&gt; Thiên lệch dữ liệu, tính công bằng và quyền riêng tư.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;các-hướng-nghiên-cứu-đang-được-quan-tâm&quot;&gt;Các hướng nghiên cứu đang được quan tâm&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Học sâu hiệu quả:&lt;/strong&gt; nén mô hình, lượng tử hóa.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học ít mẫu (&lt;em&gt;few-shot learning&lt;/em&gt;):&lt;/strong&gt; học từ lượng dữ liệu hạn chế.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học chuyển giao:&lt;/strong&gt; tận dụng các mô hình tiền huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;AI có thể giải thích:&lt;/strong&gt; làm rõ cơ sở ra quyết định của mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học liên tục:&lt;/strong&gt; cập nhật kiến thức mới mà không quên kiến thức cũ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học đa phương thức:&lt;/strong&gt; kết hợp đồng thời thị giác, ngôn ngữ và các dạng dữ liệu khác.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;nội-dung-khóa-học&quot;&gt;Nội dung khóa học&lt;/h2&gt;

&lt;h3 id=&quot;phần-i-nền-tảng-chương-0003&quot;&gt;Phần I: Nền tảng (Chương 00–03)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Kiến thức toán học tiên quyết&lt;/li&gt;
  &lt;li&gt;Cơ sở về mạng nơ-ron&lt;/li&gt;
  &lt;li&gt;Kỹ thuật huấn luyện (lan truyền ngược, tối ưu hóa)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;phần-ii-kiến-trúc-cốt-lõi-chương-0408&quot;&gt;Phần II: Kiến trúc cốt lõi (Chương 04–08)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;CNN cho thị giác máy tính&lt;/li&gt;
  &lt;li&gt;RNN cho dữ liệu chuỗi&lt;/li&gt;
  &lt;li&gt;Cơ chế chú ý (&lt;em&gt;Attention&lt;/em&gt;) và Transformer&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;phần-iii-chủ-đề-nâng-cao-chương-0916&quot;&gt;Phần III: Chủ đề nâng cao (Chương 09–16)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Chính quy hóa và tối ưu hóa&lt;/li&gt;
  &lt;li&gt;Mô hình sinh (VAE, GAN)&lt;/li&gt;
  &lt;li&gt;Học chuyển giao và học tự giám sát&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;phần-iv-ứng-dụng-chương-1725&quot;&gt;Phần IV: Ứng dụng (Chương 17–25)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Ứng dụng thị giác máy tính&lt;/li&gt;
  &lt;li&gt;Xử lý ngôn ngữ tự nhiên&lt;/li&gt;
  &lt;li&gt;Học tăng cường&lt;/li&gt;
  &lt;li&gt;Các chủ đề chuyên biệt (GNN, hiệu năng, khả năng diễn giải)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;điều-kiện-tiên-quyết&quot;&gt;Điều kiện tiên quyết&lt;/h2&gt;

&lt;h3 id=&quot;bắt-buộc&quot;&gt;Bắt buộc&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lập trình:&lt;/strong&gt; Python cơ bản.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Toán học:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Đại số tuyến tính (vector, ma trận).&lt;/li&gt;
      &lt;li&gt;Giải tích (đạo hàm, quy tắc dây chuyền).&lt;/li&gt;
      &lt;li&gt;Xác suất (phân phối, kỳ vọng).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Học máy:&lt;/strong&gt; có hiểu biết nền tảng sẽ rất thuận lợi.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;nên-có&quot;&gt;Nên có&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Kinh nghiệm sử dụng NumPy và các thuật toán học máy cơ bản.&lt;/li&gt;
  &lt;li&gt;Quen thuộc với các thư viện học máy trong Python.&lt;/li&gt;
  &lt;li&gt;Nắm được các khái niệm tối ưu hóa cơ bản.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;cách-học-học-sâu-hiệu-quả&quot;&gt;Cách học học sâu hiệu quả&lt;/h2&gt;

&lt;h3 id=&quot;gợi-ý-thực-hành&quot;&gt;Gợi ý thực hành&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tự cài đặt từ đầu:&lt;/strong&gt; giúp nắm chắc cơ chế bên dưới.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thực hành với framework:&lt;/strong&gt; làm chủ PyTorch hoặc TensorFlow.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đọc bài báo khoa học:&lt;/strong&gt; cập nhật trực tiếp các ý tưởng nghiên cứu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thực hiện dự án thực tế:&lt;/strong&gt; áp dụng kiến thức vào bài toán cụ thể.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tham gia cộng đồng:&lt;/strong&gt; trao đổi, đặt câu hỏi và tham gia thi đấu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thử nghiệm và lặp lại:&lt;/strong&gt; học thông qua việc tự chạy thí nghiệm và phân tích kết quả.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;tài-nguyên-ngoài-khóa-học&quot;&gt;Tài nguyên ngoài khóa học&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bài báo:&lt;/strong&gt; ArXiv.org, Papers with Code.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khóa học:&lt;/strong&gt; Fast.ai, Stanford CS231n/CS224n.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sách:&lt;/strong&gt; &lt;em&gt;Deep Learning&lt;/em&gt; (Goodfellow), &lt;em&gt;Dive into Deep Learning&lt;/em&gt;, &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) — lộ trình luyện tập tùy chọn nằm ở &lt;strong&gt;01-98&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cuộc thi:&lt;/strong&gt; Kaggle, AIcrowd.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cộng đồng:&lt;/strong&gt; Reddit r/MachineLearning, Discord.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;tư-duy-khi-làm-việc-với-học-sâu&quot;&gt;Tư duy khi làm việc với học sâu&lt;/h2&gt;

&lt;h3 id=&quot;nguyên-tắc-then-chốt&quot;&gt;Nguyên tắc then chốt&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bắt đầu đơn giản:&lt;/strong&gt; dựng mô hình cơ bản trước rồi mới tăng dần độ phức tạp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trực quan hóa:&lt;/strong&gt; vẽ đường cong mất mát, bản đồ chú ý (&lt;em&gt;attention map&lt;/em&gt;) và đặc trưng trung gian.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gỡ lỗi có hệ thống:&lt;/strong&gt; kiểm tra lần lượt dữ liệu, kiến trúc và vòng lặp huấn luyện.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dùng mô hình cơ sở (&lt;em&gt;baseline&lt;/em&gt;):&lt;/strong&gt; luôn so sánh với một phương pháp đơn giản để đo mức cải thiện thực sự.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Theo dõi chỉ số đánh giá (&lt;em&gt;metric&lt;/em&gt;):&lt;/strong&gt; giám sát song song hiệu năng trên tập huấn luyện và tập kiểm định (&lt;em&gt;validation&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiên nhẫn:&lt;/strong&gt; quá trình huấn luyện và tinh chỉnh đòi hỏi thời gian và nhiều vòng lặp.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;lỗi-thường-gặp-cần-tránh&quot;&gt;Lỗi thường gặp cần tránh&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Tiền xử lý dữ liệu chưa kỹ.&lt;/li&gt;
  &lt;li&gt;Khởi tạo trọng số không phù hợp.&lt;/li&gt;
  &lt;li&gt;Chọn tốc độ học (&lt;em&gt;learning rate&lt;/em&gt;) sai.&lt;/li&gt;
  &lt;li&gt;Bỏ qua tập kiểm định (&lt;em&gt;validation&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Để mô hình quá khớp trên dữ liệu huấn luyện.&lt;/li&gt;
  &lt;li&gt;Dùng chỉ số đánh giá không phản ánh đúng mục tiêu bài toán.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;lộ-trình-phía-trước&quot;&gt;Lộ trình phía trước&lt;/h2&gt;

&lt;p&gt;Học sâu là lĩnh vực thay đổi nhanh chóng. Khóa học hướng tới việc trang bị:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Nền tảng vững chắc&lt;/strong&gt; về mạng nơ-ron.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỹ năng thực hành&lt;/strong&gt; xây dựng và huấn luyện mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiểu biết hệ thống&lt;/strong&gt; về các kiến trúc hiện đại.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sự chuẩn bị cần thiết&lt;/strong&gt; cho nghiên cứu và ứng dụng nâng cao.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sau khi hoàn thành khóa học, bạn sẽ có khả năng:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Xây dựng và huấn luyện mạng nơ-ron từ đầu.&lt;/li&gt;
  &lt;li&gt;Áp dụng học sâu vào các bài toán thực tế.&lt;/li&gt;
  &lt;li&gt;Đọc hiểu và cài đặt lại các bài báo nghiên cứu.&lt;/li&gt;
  &lt;li&gt;Tham gia đóng góp vào các dự án hoặc nghiên cứu trong lĩnh vực.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Học sâu:&lt;/strong&gt; sử dụng mạng nơ-ron nhiều tầng để học biểu diễn phân cấp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tác động thực tiễn:&lt;/strong&gt; mở rộng đáng kể phạm vi ứng dụng của AI trong nhiều lĩnh vực.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ý tưởng cốt lõi:&lt;/strong&gt; tự động học đặc trưng trực tiếp từ dữ liệu thô.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiến trúc tiêu biểu:&lt;/strong&gt; MLP, CNN, RNN, Transformer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ứng dụng:&lt;/strong&gt; thị giác máy tính, NLP, tiếng nói, trò chơi, y tế và nhiều lĩnh vực khác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mục tiêu khóa học:&lt;/strong&gt; nắm vững cả nền tảng lý thuyết lẫn kỹ năng thực hành học sâu.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;điểm-cần-ghi-nhớ&quot;&gt;Điểm cần ghi nhớ&lt;/h2&gt;

&lt;p&gt;Bài mở đầu này đặt nền tảng khái niệm cho toàn bộ hành trình học sâu phía trước:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Khái niệm cốt lõi:&lt;/strong&gt; Học sâu dùng mạng nơ-ron nhiều tầng để tự động học biểu diễn phân cấp từ dữ liệu, giảm sự phụ thuộc vào việc thiết kế đặc trưng thủ công.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Nền tảng toán học:&lt;/strong&gt; Mạng nơ-ron là bộ xấp xỉ hàm phổ quát, được huấn luyện bằng &lt;em&gt;gradient descent&lt;/em&gt; và lan truyền ngược; độ sâu mang lại lợi thế biểu diễn theo cấp số mũ đối với các hàm có cấu trúc hợp thành.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Hiệu quả thực tiễn:&lt;/strong&gt; Từ bài toán nhận dạng chữ số MNIST đạt trên 97% độ chính xác chỉ sau vài phút huấn luyện đến các hệ thống hiện đại xử lý nhiều tác vụ phức tạp, học sâu đã đưa AI từ phòng thí nghiệm vào ứng dụng thực tế.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Bối cảnh lịch sử:&lt;/strong&gt; Lĩnh vực phát triển qua nhiều giai đoạn thăng trầm, trong đó các đóng góp then chốt như lan truyền ngược, CNN và Transformer kế thừa lẫn nhau để tạo nên các hệ thống ngày nay.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Mối liên hệ rộng hơn:&lt;/strong&gt; Học sâu gắn kết chặt chẽ với học máy cổ điển, học chuyển giao và sự phối hợp giữa ba yếu tố kiến trúc, dữ liệu và tính toán.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Các bài báo nền tảng:&lt;/strong&gt; Nắm bối cảnh của những công trình kinh điển (nơ-ron McCulloch–Pitts, lan truyền ngược, LeNet, AlexNet, Transformer, ResNet) giúp hiểu rõ lý do hình thành của các thực hành hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;tiếp-theo-là-gì&quot;&gt;Tiếp theo là gì?&lt;/h2&gt;

&lt;p&gt;Ở chương tiếp theo, ta sẽ đi sâu vào &lt;strong&gt;Nền tảng mạng nơ-ron&lt;/strong&gt; để hiểu cách các nơ-ron nhân tạo phối hợp học từ dữ liệu. Các nội dung chính gồm:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Mô hình toán học của nơ-ron nhân tạo (&lt;em&gt;perceptron&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Cách kết nối các nơ-ron thành mạng theo từng tầng.&lt;/li&gt;
  &lt;li&gt;Hàm kích hoạt và vai trò của chúng trong việc học quan hệ phi tuyến.&lt;/li&gt;
  &lt;li&gt;Lan truyền xuôi: cách mạng tính toán đầu ra dự đoán.&lt;/li&gt;
  &lt;li&gt;Các lựa chọn kiến trúc định hình từng loại mạng khác nhau.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Khi kết hợp nền tảng khái niệm từ phần giới thiệu này với cơ chế chi tiết ở chương sau, bạn sẽ sẵn sàng tiếp cận thuật toán huấn luyện, tự cài đặt mô hình và phân tích các kiến trúc hiện đại.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ghi nhớ:&lt;/strong&gt; Về bản chất, học sâu để dữ liệu tự bộc lộ cấu trúc thay vì áp đặt các giả định thủ công của con người. Sự chuyển dịch từ đặc trưng thiết kế tay sang biểu diễn được học là điểm khác biệt cốt lõi giữa học sâu và các cách tiếp cận truyền thống. Nguyên lý này sẽ lặp lại dưới nhiều hình thức khác nhau xuyên suốt các chương của khóa học.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, tiếng Anh. Minh họa cách một khóa nhập môn bài bản sắp xếp kiến thức tiên quyết, hàm mất mát và quy trình huấn luyện, tương đồng với lộ trình trong hướng dẫn này.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qYNweeDHiyU&quot;&gt;AI, Machine Learning, Deep Learning and Generative AI Explained&lt;/a&gt; — IBM Technology, tiếng Anh. Giúp định vị rõ các nhóm ứng dụng (thị giác, ngôn ngữ, mô hình sinh) trước khi chọn hướng đi qua các chương.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Cung cấp bức tranh tổng quan về mô hình ngôn ngữ lớn — một trong những chủ đề trọng tâm ở các chương sau.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-00-02 Bước đầu với MNIST</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_00_02_First_MNIST_Walkthrough/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_00_02_First_MNIST_Walkthrough</id>
   <content type="html">&lt;p&gt;Mọi ngôn ngữ lập trình đều có bài mở đầu &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;Hello, World!&quot;&lt;/code&gt;, và trong thế giới Deep Learning, &lt;strong&gt;“Hello, World!” chính là nhận diện chữ số viết tay MNIST&lt;/strong&gt;. Bộ dữ liệu gồm 70{,}000 ảnh chữ số từ 0 đến 9 do Yann LeCun và cộng sự tập hợp từ cuối thập niên 1990 đủ nhỏ để chạy trong vài giây trên máy tính cá nhân, nhưng lại chứa đầy đủ mọi thành phần cốt lõi của một hệ thống Học sâu thực thụ: chuẩn hóa tensor, thiết kế kiến trúc nhiều tầng, tính Cross-Entropy và chạy vòng lặp tối ưu. Bài thực hành này dẫn bạn đi từng dòng code để thực sự “chạm tay” vào mạng nơ-ron đầu tiên.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-thành-phần-trong-một-pipeline-huấn-luyện-pytorch-chuẩn&quot;&gt;Kiến thức cần nhớ: Bốn thành phần trong một Pipeline Huấn luyện PyTorch chuẩn&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Dữ liệu và Tiền xử lý Tensor (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Dataset&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DataLoader&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Transforms&lt;/code&gt;)&lt;/strong&gt;:
Chuyển ảnh PIL từ giá trị nguyên \([0, 255]\) sang tensor thực \([0, 1]\), rồi chuẩn hóa về trung bình \(0\) và độ lệch chuẩn \(1\) (với MNIST là \(\mu \approx 0.1307, \sigma \approx 0.3081\)), đồng thời xáo trộn (&lt;em&gt;shuffle&lt;/em&gt;) và gom theo mini-batch.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Định nghĩa Kiến trúc (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Module&lt;/code&gt; &amp;amp; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;forward&lt;/code&gt;)&lt;/strong&gt;:
Trải phẳng ảnh \((B, 1, 28, 28)\) thành ma trận \((B, 784)\), đưa qua các lớp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Linear&lt;/code&gt; xen kẽ hàm kích hoạt phi tuyến &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ReLU&lt;/code&gt; để xuất ra 10 điểm số thô (&lt;em&gt;logits&lt;/em&gt;) tương ứng 10 chữ số.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hàm Mất mát và Bộ Tối ưu (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CrossEntropyLoss&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Adam&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SGD&lt;/code&gt;)&lt;/strong&gt;:
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.CrossEntropyLoss&lt;/code&gt; tự động kết hợp &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LogSoftmax&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NLLLoss&lt;/code&gt; (ổn định số học hơn việc tự tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Softmax&lt;/code&gt; rồi lấy &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log&lt;/code&gt;), còn optimizer giữ nhiệm vụ cập nhật trọng số dựa trên gradient.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vòng lặp Huấn luyện 5 bước kinh điển&lt;/strong&gt;:
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;optimizer.zero_grad()&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;outputs = model(x)&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss = criterion(outputs, y)&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss.backward()&lt;/code&gt; \(\to\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;optimizer.step()&lt;/code&gt;. Quên &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;zero_grad()&lt;/code&gt; sẽ khiến gradient cộng dồn qua các batch làm mô hình hỏng ngay lập tức!&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-theo-dõi-kích-thước-tensor-và-số-bước-cập-nhật-của-1-epoch-mnist&quot;&gt;Giải thích: Theo dõi kích thước Tensor và số bước cập nhật của 1 Epoch MNIST&lt;/h3&gt;

&lt;p&gt;Giả sử bạn huấn luyện trên tập train MNIST có \(60{,}000\) ảnh với &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_size = 64&lt;/code&gt; qua mạng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;784 -&amp;gt; 128 -&amp;gt; 64 -&amp;gt; 10&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Số bước cập nhật (iterations) trong 1 epoch&lt;/strong&gt;:
\(\left\lceil \frac{60{,}000}{64} \right\rceil = \lceil 937.5 \rceil = 938 \text{ bước}\) (937 batch đủ 64 ảnh, và batch cuối cùng gồm \(60{,}000 - 937 \times 64 = 32\) ảnh).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Truy vết kích thước (&lt;em&gt;shape&lt;/em&gt;) Tensor qua từng lớp ở một batch đầy đủ&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Đầu vào ảnh gốc: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64, 1, 28, 28)&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Sau &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x.view(-1, 784)&lt;/code&gt; (trải phẳng): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64, 784)&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Sau &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fc1&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(784, 128)&lt;/code&gt;) + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ReLU&lt;/code&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64, 128)&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Sau &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fc2&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(128, 64)&lt;/code&gt;) + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ReLU&lt;/code&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64, 64)&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Sau &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fc3&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(64, 10)&lt;/code&gt; — logits): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64, 10)&lt;/code&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra độ hợp lý của Loss ngay lúc khởi tạo ngẫu nhiên&lt;/strong&gt;:
Khi mạng chưa học gì, xác suất đoán cho cả 10 chữ số đều xấp xỉ \(1/10 = 0.1\). Khi đó Cross-Entropy kỳ vọng ở bước 0 phải xấp xỉ:
\(-\ln(0.1) = \ln(10) \approx 2.3026.\)
Mẹo thực chiến cực hay: nếu ở epoch 0 bạn thấy loss ban đầu vọt lên \(15\) hay tụt về \(0.01\), hãy dừng lại kiểm tra ngay bug ở chuẩn hóa dữ liệu hoặc hàm mất mát!&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-đoạn-mã-minh-họa&quot;&gt;4. Đoạn mã minh họa&lt;/h2&gt;

&lt;p&gt;Ta triển khai một ví dụ học sâu cơ bản để làm rõ các khái niệm đã nêu. Mục tiêu là xây dựng một mạng nơ-ron phân loại chữ số viết tay MNIST bằng PyTorch.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.utils.data&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DataLoader&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Định nghĩa mạng nơ-ron sâu đơn giản
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleDeepNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Mạng nơ-ron 3 tầng cho phân loại chữ số MNIST.
    
    Kiến trúc:
    - Đầu vào: 784 chiều (ảnh 28x28 làm phẳng)
    - Tầng ẩn 1: 128 nơ-ron với kích hoạt ReLU
    - Tầng ẩn 2: 64 nơ-ron với kích hoạt ReLU
    - Tầng đầu ra: 10 nơ-ron (một nơ-ron cho mỗi lớp chữ số)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SimpleDeepNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Tầng ẩn thứ nhất
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Tầng ẩn thứ hai
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;     &lt;span class=&quot;c1&quot;&gt;# Tầng đầu ra
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Làm phẳng ảnh 28x28 thành vector 784 chiều
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tầng 1: học đặc trưng mức thấp
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tầng 2: học tổ hợp đặc trưng mức trung
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Tầng đầu ra: phân loại vào 10 lớp chữ số
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Tải tập dữ liệu MNIST
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Compose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ToTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normalize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1307&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3081&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Chuẩn hóa theo mean/std của MNIST
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Khởi tạo mô hình, hàm mất mát và bộ tối ưu
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleDeepNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CrossEntropyLoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Kết hợp softmax + negative log likelihood
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vòng lặp huấn luyện
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Chuyển mô hình sang chế độ huấn luyện
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;total_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Lan truyền xuôi: tính dự đoán
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Lan truyền ngược: tính gradient
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Xóa gradient bước trước
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Lan truyền ngược
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Cập nhật trọng số
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Theo dõi độ chính xác
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Batch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
                  &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; Training: Avg Loss=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Accuracy=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vòng lặp đánh giá
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Chuyển mô hình sang chế độ đánh giá
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;test_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Tắt tính gradient để tăng hiệu năng
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;test_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;test_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Test: Avg Loss=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Accuracy=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Huấn luyện qua nhiều epoch
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Starting training...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Huấn luyện 5 epoch
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;test_accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Final test accuracy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_accuracy&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training complete! The network learned to recognize digits through:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Forward propagation (making predictions)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Loss computation (measuring errors)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;3. Backpropagation (computing gradients)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;4. Weight updates (learning from mistakes)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;phân-tích-đoạn-mã&quot;&gt;Phân tích đoạn mã&lt;/h3&gt;

&lt;p&gt;Ví dụ đơn giản này minh họa đầy đủ các nguyên lý cốt lõi của học sâu:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Thiết kế kiến trúc:&lt;/strong&gt; Ba tầng liên tiếp biến đổi đầu vào 784 chiều thành đầu ra 10 chiều thông qua các tầng biểu diễn trung gian.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Học đặc trưng tự động:&lt;/strong&gt; Ta không cần chỉ định trước mạng phải tìm đặc trưng nào — mô hình tự học các biểu diễn hữu ích từ dữ liệu điểm ảnh.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Vòng lặp huấn luyện chuẩn:&lt;/strong&gt; Chu trình lan truyền xuôi → tính mất mát → lan truyền ngược → cập nhật trọng số là khung vận hành chung của hầu hết quy trình học sâu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Vai trò của hàm kích hoạt phi tuyến:&lt;/strong&gt; Các hàm ReLU đặt giữa các tầng tuyến tính giúp mạng học được những ánh xạ phi tuyến phức tạp. Nếu bỏ qua chúng, nhiều tầng tuyến tính xếp chồng lên nhau sẽ chỉ tương đương một phép biến đổi tuyến tính duy nhất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Khả năng mở rộng:&lt;/strong&gt; Cùng cấu trúc mã nguồn này, khi điều chỉnh kiến trúc và dữ liệu phù hợp, có thể mở rộng sang các tập dữ liệu lớn hơn và những bài toán phức tạp hơn trong thị giác máy tính, xử lý ngôn ngữ tự nhiên và nhiều lĩnh vực khác.&lt;/p&gt;

&lt;p&gt;Chỉ sau 5 epoch (5 lượt duyệt qua 60.000 ảnh huấn luyện), mạng đơn giản này thường đạt độ chính xác khoảng 97%, cho thấy khả năng học trực tiếp từ dữ liệu của mạng nơ-ron.&lt;/p&gt;

&lt;h2 id=&quot;5-các-khái-niệm-liên-quan&quot;&gt;5. Các khái niệm liên quan&lt;/h2&gt;

&lt;p&gt;Để hiểu rõ học sâu, cần đặt nó trong mối liên hệ với các nhánh và khái niệm rộng hơn của học máy và trí tuệ nhân tạo.&lt;/p&gt;

&lt;h3 id=&quot;học-có-giám-sát-học-không-giám-sát-và-học-tăng-cường&quot;&gt;Học có giám sát, học không giám sát và học tăng cường&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Học có giám sát (&lt;em&gt;supervised learning&lt;/em&gt;)&lt;/strong&gt; — trọng tâm chính ở giai đoạn đầu — học từ các ví dụ có nhãn, tức các cặp đầu vào–đầu ra như (ảnh, nhãn lớp) hoặc (câu nguồn, bản dịch). Mạng học ánh xạ từ đầu vào sang đầu ra tương ứng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Học không giám sát (&lt;em&gt;unsupervised learning&lt;/em&gt;)&lt;/strong&gt; tìm kiếm cấu trúc ẩn trong dữ liệu chưa gán nhãn. Ví dụ, &lt;em&gt;autoencoder&lt;/em&gt; học biểu diễn nén, phân cụm (&lt;em&gt;clustering&lt;/em&gt;) nhóm các mẫu tương đồng, còn mô hình sinh học phân phối dữ liệu để tạo mẫu mới. Hướng tiếp cận này đặc biệt hữu ích khi việc gán nhãn tốn kém hoặc không khả thi.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Học tăng cường (&lt;em&gt;reinforcement learning&lt;/em&gt;)&lt;/strong&gt; học thông qua tương tác với môi trường: một tác tử (&lt;em&gt;agent&lt;/em&gt;) thực hiện hành động, nhận tín hiệu phần thưởng và học chính sách nhằm tối đa hóa phần thưởng tích lũy. Cách này phù hợp với các bài toán điều khiển hành vi (như chơi trò chơi hoặc điều khiển robot), nơi không thể chỉ định sẵn hành động đúng cho mọi trạng thái mà chỉ đánh giá qua kết quả dài hạn.&lt;/p&gt;

&lt;p&gt;Học sâu đã tạo ra bước tiến lớn ở cả ba hướng tiếp cận này, dù nguyên lý toán học của từng nhánh có nhiều điểm khác biệt. Khóa học này tập trung trước hết vào học có giám sát, sau đó mở rộng sang học không giám sát và học tăng cường ở các chương sau.&lt;/p&gt;

&lt;h3 id=&quot;học-máy-cổ-điển-so-với-học-sâu&quot;&gt;Học máy cổ điển so với học sâu&lt;/h3&gt;

&lt;p&gt;Học máy truyền thống (như SVM, cây quyết định, hồi quy logistic) thường có các đặc điểm sau:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đòi hỏi thiết kế đặc trưng thủ công.&lt;/li&gt;
  &lt;li&gt;Dựa trên các giả định mô hình tường minh (như tính tuyến tính hoặc độc lập).&lt;/li&gt;
  &lt;li&gt;Hoạt động hiệu quả với tập dữ liệu cỡ nhỏ đến vừa (vài trăm đến vài nghìn mẫu).&lt;/li&gt;
  &lt;li&gt;Dễ diễn giải hơn thông qua mức độ quan trọng của đặc trưng hoặc ranh giới quyết định.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Trong khi đó, học sâu:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tự động học đặc trưng theo hướng từ đầu đến cuối (&lt;em&gt;end-to-end&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Ít đặt giả định cứng nhắc hơn về cấu trúc dữ liệu.&lt;/li&gt;
  &lt;li&gt;Thường cần tập dữ liệu lớn (từ hàng nghìn đến hàng triệu mẫu).&lt;/li&gt;
  &lt;li&gt;Khó diễn giải trực tiếp hơn nhưng xử lý hiệu quả các mẫu phức tạp.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Không có phương pháp nào vượt trội trong mọi hoàn cảnh: học máy cổ điển thường phù hợp hơn với tập dữ liệu nhỏ, dữ liệu dạng bảng hoặc khi yêu cầu cao về khả năng giải thích; còn học sâu phát huy thế mạnh trên dữ liệu lớn, đầu vào nhiều chiều (ảnh, văn bản, âm thanh) và cấu trúc mẫu phức tạp.&lt;/p&gt;

&lt;h3 id=&quot;học-chuyển-giao-và-tiền-huấn-luyện&quot;&gt;Học chuyển giao và tiền huấn luyện&lt;/h3&gt;

&lt;p&gt;Một kỹ thuật quan trọng của học sâu là &lt;strong&gt;học chuyển giao (&lt;em&gt;transfer learning&lt;/em&gt;)&lt;/strong&gt;: huấn luyện mạng trên một tác vụ nguồn (chẳng hạn phân loại ImageNet) rồi điều chỉnh lại cho tác vụ liên quan (như phân tích ảnh y khoa hoặc nhận diện động vật hoang dã). Các biểu diễn đã học — bộ phát hiện cạnh, kết cấu, hình dạng — có thể tái sử dụng giữa nhiều miền dữ liệu.&lt;/p&gt;

&lt;p&gt;Quy trình &lt;strong&gt;tiền huấn luyện (&lt;em&gt;pre-training&lt;/em&gt;)&lt;/strong&gt; trên tập dữ liệu tổng quát quy mô lớn rồi &lt;strong&gt;tinh chỉnh (&lt;em&gt;fine-tuning&lt;/em&gt;)&lt;/strong&gt; cho tác vụ cụ thể đã trở thành chuẩn mực phổ biến. Các mô hình ngôn ngữ lớn như GPT hay BERT được tiền huấn luyện trên kho văn bản khổng lồ, sau đó tinh chỉnh cho từng ứng dụng với lượng dữ liệu chuyên biệt ít hơn nhiều, giúp giảm đáng kể chi phí thu thập và gán nhãn dữ liệu mới.&lt;/p&gt;

&lt;h3 id=&quot;vai-trò-của-kiến-trúc-dữ-liệu-và-tính-toán&quot;&gt;Vai trò của kiến trúc, dữ liệu và tính toán&lt;/h3&gt;

&lt;p&gt;Hiệu quả của học sâu hiện đại bắt nguồn từ sự kết hợp của ba yếu tố chính:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đổi mới kiến trúc:&lt;/strong&gt; Các kiến trúc như CNN, ResNet hay Transformer đưa vào thiên kiến quy nạp (&lt;em&gt;inductive bias&lt;/em&gt;) phù hợp với cấu trúc bài toán, giúp mô hình học hiệu quả hơn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quy mô dữ liệu:&lt;/strong&gt; Tập dữ liệu lớn, đa dạng và có chất lượng cao cung cấp thông tin cần thiết để mạng học được biểu diễn bền vững và khái quát tốt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Năng lực tính toán:&lt;/strong&gt; Phần cứng như GPU và TPU song song hóa các phép toán ma trận cốt lõi của mạng nơ-ron, rút ngắn thời gian huấn luyện từ nhiều tháng xuống còn vài giờ.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Những tiến bộ của học sâu trong thực tế là kết quả đồng thời của cả ba yếu tố: kiến trúc tốt hơn (như Transformer), dữ liệu lớn hơn (văn bản và ảnh quy mô web) và năng lực tính toán mạnh hơn (cụm GPU, TPU). Không một yếu tố đơn lẻ nào có thể giải thích trọn vẹn sự phát triển của lĩnh vực.&lt;/p&gt;

&lt;h2 id=&quot;6-các-bài-báo-nền-tảng&quot;&gt;6. Các bài báo nền tảng&lt;/h2&gt;

&lt;p&gt;Điểm lại một số công trình tiêu biểu giúp hình dung bối cảnh lịch sử hình thành nên thực hành học sâu hiện nay.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://link.springer.com/article/10.1007/BF02478259&quot;&gt;“A Logical Calculus of Ideas Immanent in Nervous Activity” (1943)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả:&lt;/em&gt; Warren McCulloch và Walter Pitts&lt;br /&gt;
Bài báo đề xuất mô hình toán học đầu tiên của nơ-ron nhân tạo, chứng minh rằng mạng gồm các đơn vị ngưỡng đơn giản có thể biểu diễn mọi hàm logic. Dù đơn giản hóa rất nhiều so với nơ-ron sinh học, công trình này đã đặt nền móng lý thuyết cho tính toán nơ-ron và ảnh hưởng lâu dài tới cả khoa học thần kinh lẫn trí tuệ nhân tạo.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.nature.com/articles/323533a0&quot;&gt;“Learning representations by back-propagating errors” (1986)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả:&lt;/em&gt; David Rumelhart, Geoffrey Hinton, Ronald Williams&lt;br /&gt;
Dù lan truyền ngược đã được phát hiện độc lập trước đó, bài báo này đưa kỹ thuật vào dòng chính và chứng minh hiệu quả của nó trong huấn luyện mạng nhiều tầng. Bằng cách áp dụng quy tắc dây chuyền để tính gradient qua hợp thành hàm, lan truyền ngược giúp việc huấn luyện mạng nhiều tầng trở nên khả thi trên thực tế.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf&quot;&gt;“Gradient-Based Learning Applied to Document Recognition” (1998)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả:&lt;/em&gt; Yann LeCun, Léon Bottou, Yoshua Bengio, Patrick Haffner&lt;br /&gt;
Bài báo giới thiệu kiến trúc LeNet-5, cho thấy mạng nơ-ron tích chập có thể giải quyết hiệu quả các bài toán thực tế như đọc séc và nhận dạng chữ số. Công trình này xác lập các nguyên lý cốt lõi — kết nối cục bộ, chia sẻ trọng số và gộp (&lt;em&gt;pooling&lt;/em&gt;) — vẫn giữ vai trò trung tâm trong thị giác máy tính hiện đại.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks&quot;&gt;“ImageNet Classification with Deep Convolutional Neural Networks” (2012)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả:&lt;/em&gt; Alex Krizhevsky, Ilya Sutskever, Geoffrey Hinton&lt;br /&gt;
Kết quả vượt trội của AlexNet tại cuộc thi ImageNet 2012 (tỷ lệ lỗi 15,3% so với 26,2% của đội đứng thứ hai) đã mở ra giai đoạn phát triển mạnh mẽ của học sâu hiện đại. Bằng cách kết hợp kiến trúc sâu hơn, hàm kích hoạt ReLU, chính quy hóa &lt;em&gt;dropout&lt;/em&gt; và huấn luyện trên GPU, bài báo chứng minh mạng nơ-ron có thể mở rộng hiệu quả sang các tập dữ liệu ảnh lớn và phức tạp.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;“Attention Is All You Need” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả:&lt;/em&gt; Ashish Vaswani và cộng sự (Google)&lt;br /&gt;
Bài báo giới thiệu kiến trúc Transformer — nền tảng của xử lý ngôn ngữ tự nhiên hiện đại và ngày càng mở rộng sang nhiều lĩnh vực khác. Bằng cách thay thế cơ chế hồi quy bằng cơ chế chú ý (&lt;em&gt;attention&lt;/em&gt;), Transformer cho phép song song hóa cao trong huấn luyện và nắm bắt tốt các phụ thuộc tầm xa, trở thành kiến trúc cốt lõi của BERT, GPT và phần lớn mô hình ngôn ngữ lớn ngày nay.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.03385&quot;&gt;“Deep Residual Learning for Image Recognition” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Tác giả:&lt;/em&gt; Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun&lt;br /&gt;
ResNet đưa ra kết nối tắt (&lt;em&gt;skip connection&lt;/em&gt;), tạo đường truyền trực tiếp cho gradient và nhờ đó cho phép huấn luyện mạng sâu hàng trăm tầng. Bên cạnh chiến thắng tại ImageNet 2015, công trình này làm rõ rằng để tăng độ sâu hiệu quả cần các đổi mới về kiến trúc và chuẩn hóa. Nguyên lý kết nối phần dư hiện có mặt trong hầu hết các kiến trúc sâu hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=gBw0u_5u0qU&quot;&gt;PyTorch Course (2022), Part 4: Image Classification (MNIST)&lt;/a&gt; — Mr. P Solver, tiếng Anh. Hướng dẫn trực tiếp cách chạy vòng lặp huấn luyện phân loại MNIST bằng PyTorch tương ứng với đoạn mã trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Trình bày mô hình trực giác của mạng nhận dạng chữ số đứng sau vòng lặp huấn luyện trên.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 4&lt;/td&gt;
          &lt;td&gt;Introduction to Neural Networks](https://www.youtube.com/watch?v=d14TUNcbn1k) — Stanford University School of Engineering, tiếng Anh. Bài giảng về mạng nơ-ron của Stanford, đặt bộ phân loại cơ bản vào khung lý thuyết của các bài học tiếp theo.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-00-01 Học sâu là gì</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_00_01_What_Is_Deep_Learning/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter01/01_00_01_What_Is_Deep_Learning</id>
   <content type="html">&lt;p&gt;Suốt nửa thế kỷ đầu của Trí tuệ Nhân tạo, các nhà khoa học tin rằng cách tốt nhất để máy tính thông minh là chép toàn bộ tri thức nhân loại vào cơ sở dữ liệu luật logic. Kết quả là máy có thể đánh thắng nhà vô địch cờ vua thế giới nhưng lại bó tay trước một việc đứa trẻ 3 tuổi làm trong chớp mắt: phân biệt con mèo với con chó trong ánh sáng mờ. &lt;strong&gt;Học sâu&lt;/strong&gt; (&lt;em&gt;Deep Learning&lt;/em&gt;) lật ngược hoàn toàn cách tiếp cận đó bằng cách cho phép mạng nơ-ron nhiều tầng tự học cấu trúc phân cấp của thế giới trực tiếp từ dữ liệu thô. Bài học này giải phẫu định nghĩa, bốn đặc trưng cốt lõi và sức mạnh biểu diễn của Học sâu.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-đặc-tính-định-hình-bản-sắc-của-học-sâu&quot;&gt;Kiến thức cần nhớ: Bốn đặc tính định hình bản sắc của Học sâu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân cấp khái niệm (Hierarchical Feature Learning)&lt;/strong&gt;:
Thay vì nhảy một bước từ điểm ảnh sang nhãn lớp, mạng xếp chồng nhiều phép biến đổi phi tuyến \(f(\mathbf{x}) = f_L(\dots f_2(f_1(\mathbf{x})))\), mỗi tầng chắt lọc mức trừu tượng cao hơn tầng trước.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tối ưu hóa Đầu-cuối (End-to-End Learning)&lt;/strong&gt;:
Mọi thành phần từ bộ trích xuất đặc trưng đến bộ phân loại cuối cùng đều được tối ưu đồng thời theo một hàm mất mát duy nhất, tránh lỗi tích lũy giữa các mô-đun rời rạc.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Biểu diễn Phân tán (Distributed Representations)&lt;/strong&gt;:
Nếu biểu diễn cục bộ (one-hot) cần \(N\) nơ-ron để mã hóa \(N\) khái niệm, thì biểu diễn phân tán nhị phân trên \(k\) nơ-ron có thể mã hóa tới \(2^k\) tổ hợp khái niệm khác nhau—tạo nên năng lực khái quát hóa vượt trội.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Định luật Mở rộng (Scaling Laws)&lt;/strong&gt;:
Hiệu năng Học sâu tiếp tục cải thiện một cách có quy luật khi tăng đồng thời dữ liệu (\(D\)), số tham số (\(N\)) và năng lực tính toán (\(C\)), thay vì sớm chạm trần như nhiều thuật toán cổ điển.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-sức-mạnh-tổ-hợp-của-biểu-diễn-phân-tán-vs-biểu-diễn-cục-bộ&quot;&gt;Giải thích: Tính tay sức mạnh tổ hợp của Biểu diễn Phân tán vs. Biểu diễn Cục bộ&lt;/h3&gt;

&lt;p&gt;Giả sử bạn muốn mô hình biểu diễn các vật thể theo 4 thuộc tính độc lập: &lt;em&gt;Màu sắc&lt;/em&gt; (Đỏ/Xanh), &lt;em&gt;Hình dạng&lt;/em&gt; (Tròn/Vuông), &lt;em&gt;Kích thước&lt;/em&gt; (Lớn/Nhỏ), &lt;em&gt;Chất liệu&lt;/em&gt; (Gỗ/Kim loại):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cách biểu diễn cục bộ (1 nơ-ron cho mỗi tổ hợp riêng biệt)&lt;/strong&gt;:
Số tổ hợp khác nhau là \(2 \times 2 \times 2 \times 2 = 2^4 = 16\). Bạn cần tới &lt;strong&gt;16 nơ-ron độc lập&lt;/strong&gt;, và nếu mô hình chưa từng thấy “Khối vuông màu xanh bằng gỗ cỡ nhỏ”, nó không biết bất kỳ thông tin gì về vật thể đó.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cách biểu diễn phân tán (4 nơ-ron đại diện cho 4 trục thuộc tính)&lt;/strong&gt;:
Bạn chỉ cần &lt;strong&gt;4 nơ-ron&lt;/strong&gt;, mỗi nơ-ron phụ trách một đặc trưng (ví dụ vector &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0, 1, 0, 1]&lt;/code&gt; = Xanh, Vuông, Nhỏ, Kim loại).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mở rộng lên 20 thuộc tính nhị phân&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Biểu diễn cục bộ cần \(2^{20} = 1{,}048{,}576\) nơ-ron (và hàng triệu mẫu cho từng tổ hợp).&lt;/li&gt;
      &lt;li&gt;Biểu diễn phân tán chỉ cần &lt;strong&gt;20 nơ-ron&lt;/strong&gt;—và có thể khái quát ngay sang tổ hợp chưa từng gặp! Đó là lý do toán học sâu xa khiến mạng nơ-ron hiểu được những tình huống mới ngoài tập huấn luyện.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;giới-thiệu-về-học-sâu&quot;&gt;Giới thiệu về Học sâu&lt;/h1&gt;

&lt;h2 id=&quot;1-tổng-quan-khái-niệm&quot;&gt;1. Tổng quan khái niệm&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/AI-ML-DL.svg/800px-AI-ML-DL.svg.png&quot; alt=&quot;Deep Learning Hierarchy&quot; /&gt;
&lt;em&gt;Hình: Mối quan hệ giữa AI, Học máy và Học sâu. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Về bản chất, &lt;strong&gt;học sâu&lt;/strong&gt; (&lt;em&gt;deep learning&lt;/em&gt;) là một nhánh của học máy (&lt;em&gt;machine learning&lt;/em&gt;) sử dụng mạng nơ-ron nhân tạo (&lt;em&gt;artificial neural networks&lt;/em&gt;) gồm nhiều tầng — do đó gọi là “sâu” — để tự động học các biểu diễn phân cấp của dữ liệu. Điểm tạo nên bước ngoặt của học sâu không chỉ nằm ở hiệu năng thực tế, mà còn ở việc nó thay đổi căn bản cách xây dựng các hệ thống thông minh.&lt;/p&gt;

&lt;p&gt;Để đánh giá đúng ý nghĩa của học sâu, cần nhìn lại giai đoạn trước đó. Học máy truyền thống đòi hỏi chuyên gia thiết kế thủ công các đặc trưng (&lt;em&gt;features&lt;/em&gt;) — những mẫu hoặc thuộc tính mà thuật toán dùng để ra quyết định. Với nhận dạng ảnh, điều này nghĩa là phải xây dựng thủ công các bộ phát hiện cạnh, bộ phân tích kết cấu (&lt;em&gt;texture&lt;/em&gt;) và bộ mô tả hình dạng. Với nhận dạng tiếng nói, người thiết kế phải xây dựng biểu diễn âm vị (&lt;em&gt;phoneme&lt;/em&gt;) và mô hình âm học dựa trên lý thuyết ngôn ngữ học. Việc thiết kế đặc trưng đòi hỏi kiến thức chuyên sâu về từng miền bài toán và thường cần nhiều năm tinh chỉnh lặp đi lặp lại.&lt;/p&gt;

&lt;p&gt;Học sâu khắc phục nút thắt này thông qua &lt;strong&gt;học biểu diễn&lt;/strong&gt; (&lt;em&gt;representation learning&lt;/em&gt;) — khả năng tự động khám phá các biểu diễn cần thiết cho việc phát hiện hoặc phân loại trực tiếp từ dữ liệu thô. Một mạng nơ-ron sâu học đặc trưng ở nhiều mức trừu tượng khác nhau: trong thị giác máy tính, tầng thứ nhất có thể học phát hiện cạnh; tầng thứ hai kết hợp các cạnh thành hình dạng đơn giản; tầng thứ ba ghép các hình dạng thành bộ phận của đối tượng; và các tầng sâu hơn nhận diện đối tượng hoàn chỉnh. Mạng tự hình thành hệ thống đặc trưng phân cấp này mà không cần hướng dẫn thủ công ngoài dữ liệu huấn luyện và mục tiêu tối ưu.&lt;/p&gt;

&lt;p&gt;Việc tự động hóa quá trình học đặc trưng mang lại nhiều hệ quả quan trọng. Học sâu có thể xử lý những bài toán mà con người khó thiết kế đặc trưng thủ công hiệu quả. Cùng một nhóm kiến trúc cơ bản — với các điều chỉnh phù hợp — có thể áp dụng cho nhiều tác vụ khác nhau như nhận diện khuôn mặt, dịch máy, sinh ảnh, chơi trò chơi hay dự đoán cấu trúc protein. Khi bổ sung thêm dữ liệu và năng lực tính toán, hiệu năng của mô hình tiếp tục cải thiện thay vì sớm bão hòa như nhiều hệ thống cổ điển phụ thuộc vào đặc trưng thủ công.&lt;/p&gt;

&lt;h3 id=&quot;các-đặc-trưng-then-chốt-của-học-sâu&quot;&gt;Các đặc trưng then chốt của học sâu&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Học đặc trưng phân cấp:&lt;/strong&gt; Mạng sâu học đặc trưng theo nhiều tầng trừu tượng. Các tầng thấp nắm bắt những mẫu đơn giản (cạnh, màu sắc, âm vị cơ bản), còn các tầng cao kết hợp chúng thành khái niệm phức tạp hơn (đối tượng, khuôn mặt, ngữ nghĩa). Cấu trúc phân cấp này tương đồng với cách thị giác và nhận thức sinh học xử lý thông tin — xây dựng hiểu biết từng lớp từ đơn giản đến phức tạp.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Học từ đầu đến cuối (&lt;em&gt;end-to-end learning&lt;/em&gt;):&lt;/strong&gt; Thay vì xây dựng một chuỗi mô-đun rời rạc trong đó từng thành phần được tối ưu riêng lẻ, học sâu cho phép tối ưu đồng thời toàn bộ hệ thống. Trong dịch máy, thay vì tách riêng các bước phân tích cú pháp, căn chỉnh và sinh câu, một mạng nơ-ron duy nhất có thể học ánh xạ trực tiếp từ ngôn ngữ nguồn sang ngôn ngữ đích, trong đó mọi thành phần đều được điều chỉnh cùng hướng tới chất lượng bản dịch cuối cùng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Khả năng mở rộng theo dữ liệu và tính toán:&lt;/strong&gt; Học máy truyền thống thường gặp hiện tượng lợi ích giảm dần — sau một ngưỡng nhất định, việc thêm dữ liệu không còn cải thiện đáng kể hiệu năng. Ngược lại, hiệu năng của học sâu tiếp tục tăng khi mở rộng dữ liệu và năng lực tính toán; đặc tính mở rộng (&lt;em&gt;scaling&lt;/em&gt;) này là nền tảng cho sự phát triển của các mô hình ngôn ngữ lớn và hệ thống thị giác máy tính hiện đại. Đây vừa là ưu thế (giúp mô hình đạt hiệu năng rất cao trên nhiều tác vụ) vừa là thách thức (đòi hỏi tập dữ liệu lớn và chi phí tính toán cao).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Biểu diễn phân tán (&lt;em&gt;distributed representations&lt;/em&gt;):&lt;/strong&gt; Mạng sâu biểu diễn mỗi khái niệm bằng một mẫu kích hoạt trải rộng trên nhiều nơ-ron, thay vì gán riêng một nơ-ron cho từng khái niệm. Cơ chế này hỗ trợ khả năng khái quát hóa: thông tin học được về “chó” có thể giúp mô hình nhận diện “sói” vì chúng chia sẻ nhiều đặc trưng biểu diễn. Đồng thời, biểu diễn phân tán tăng độ bền vững: nếu một số nơ-ron bị loại bỏ trong quá trình huấn luyện (chẳng hạn khi dùng &lt;em&gt;dropout&lt;/em&gt;), phần còn lại vẫn duy trì được thông tin biểu diễn.&lt;/p&gt;

&lt;h3 id=&quot;vì-sao-học-sâu-quan-trọng&quot;&gt;Vì sao học sâu quan trọng&lt;/h3&gt;

&lt;p&gt;Tác động của học sâu đã vượt xa phạm vi nghiên cứu học thuật, tạo ra thay đổi sâu rộng trong nhiều ngành công nghiệp và lĩnh vực đời sống:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Thị giác máy tính (&lt;em&gt;computer vision&lt;/em&gt;):&lt;/strong&gt; Phát triển từ các hệ thống nhận dạng chữ số còn hạn chế trong thập niên 1990 đến các mô hình vượt hiệu năng con người trên nhiều tác vụ thị giác, nhận diện hàng nghìn lớp đối tượng, sinh ảnh chân thực và hỗ trợ xe tự hành.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xử lý ngôn ngữ tự nhiên (&lt;em&gt;natural language processing&lt;/em&gt;):&lt;/strong&gt; Chuyển từ các hệ thống dựa trên luật cứng nhắc sang các mô hình ngôn ngữ nơ-ron có khả năng soạn thảo văn bản, trả lời câu hỏi, dịch thuật đa ngôn ngữ với chất lượng gần với con người và duy trì hội thoại mạch lạc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Y tế:&lt;/strong&gt; Hỗ trợ phát hiện bệnh từ ảnh y khoa với độ chính xác tiệm cận chuyên gia, dự báo diễn tiến bệnh nhân, rút ngắn quá trình khám phá thuốc và cá nhân hóa phác đồ điều trị.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khám phá khoa học:&lt;/strong&gt; Hỗ trợ tìm kiếm vật liệu mới, dự đoán cấu trúc protein (như AlphaFold giải quyết bài toán gập protein tồn tại nửa thế kỷ), đề xuất giả thuyết từ tài liệu khoa học và hỗ trợ thiết kế thí nghiệm.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bên cạnh đó, học sâu cũng giúp mở rộng khả năng tiếp cận công nghệ AI. Các thư viện mã nguồn mở như PyTorch và TensorFlow, cùng kho mô hình tiền huấn luyện công khai và tài liệu học tập phong phú, cho phép bất kỳ ai có máy tính cá nhân đều có thể thử nghiệm và nghiên cứu. Điều này thúc đẩy sự tham gia của đông đảo nhà nghiên cứu và kỹ sư trên toàn thế giới.&lt;/p&gt;

&lt;h2 id=&quot;2-nền-tảng-toán-học&quot;&gt;2. Nền tảng toán học&lt;/h2&gt;

&lt;p&gt;Về mặt toán học, học sâu là bài toán &lt;strong&gt;xấp xỉ hàm&lt;/strong&gt;. Cho tập huấn luyện \(\{(\mathbf{x}_1, y_1), (\mathbf{x}_2, y_2), \ldots, (\mathbf{x}_n, y_n)\}\), trong đó \(\mathbf{x}_i\) là đầu vào (ảnh, văn bản, tín hiệu cảm biến) và \(y_i\) là đầu ra mong muốn (nhãn, bản dịch, hành động), ta cần tìm hàm \(f_\theta\) tham số hóa bởi \(\theta\) sao cho ánh xạ từ đầu vào sang đầu ra đạt độ chính xác cao.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_function_approx_title.jpg&quot; alt=&quot;Mạng nơ-ron = bộ xấp xỉ hàm&quot; /&gt;
&lt;em&gt;Hình: “Hộp đen” mạng nơ-ron thực chất đang khớp một đường cong \(y = f(x)\) từ dữ liệu. (Minh họa từ video về bản chất mạng nơ-ron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_overview_network_vs_curve.jpg&quot; alt=&quot;Tổng quan: mạng vs đường cong mục tiêu&quot; /&gt;
&lt;em&gt;Hình: Cùng một mạng nơ-ron, khi thay đổi đầu vào \(x\), sẽ tạo ra các điểm nằm trên một đường cong phức tạp. (Minh họa từ video về bản chất mạng nơ-ron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Từ mô hình tuyến tính đến phi tuyến:&lt;/strong&gt; Hồi quy tuyến tính \(f(x)=xw+b\) chỉ biểu diễn được đường thẳng nên không đủ để khớp dữ liệu có dạng đường cong uốn lượn.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_linear_regression_formula.jpg&quot; alt=&quot;Công thức hồi quy tuyến tính&quot; /&gt;
&lt;em&gt;Hình: Nơ-ron tuyến tính là dạng mở rộng của hàm \(f(x)=xw+b\). (Minh họa từ video về bản chất mạng nơ-ron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_linear_fails_nonlinear.jpg&quot; alt=&quot;Tuyến tính thất bại trên dữ liệu phi tuyến&quot; /&gt;
&lt;em&gt;Hình: Mô hình tuyến tính có giới hạn rõ rệt — không thể khớp được đường cong phức tạp. (Minh họa từ video về bản chất mạng nơ-ron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Khi bổ sung hàm kích hoạt phi tuyến (chẳng hạn dạng sigmoid), mạng nơ-ron có thể khớp được các đường cong trơn và phức tạp hơn:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_sigmoid_curve_fit.jpg&quot; alt=&quot;Khớp đường cong dạng sigmoid&quot; /&gt;
&lt;em&gt;Hình: Ví dụ về hàm trơn mà mạng nơ-ron có thể xấp xỉ. (Minh họa từ video về bản chất mạng nơ-ron)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;định-lý-xấp-xỉ-phổ-quát&quot;&gt;Định lý xấp xỉ phổ quát&lt;/h3&gt;

&lt;p&gt;Một kết quả lý thuyết nền tảng khẳng định rằng mạng nơ-ron chỉ cần một tầng ẩn, nếu có đủ số nơ-ron, có thể xấp xỉ bất kỳ hàm liên tục nào trên một miền đóng và bị chặn với độ chính xác tùy ý. Về mặt toán học, với mọi hàm liên tục \(g: \mathbb{R}^n \to \mathbb{R}^m\) và mọi \(\epsilon &amp;gt; 0\), tồn tại mạng nơ-ron \(f_\theta\) sao cho:&lt;/p&gt;

\[\|f_\theta(\mathbf{x}) - g(\mathbf{x})\| &amp;lt; \epsilon \quad \text{for all } \mathbf{x}\]

&lt;p&gt;Kết quả này cho thấy mạng nơ-ron là &lt;strong&gt;bộ xấp xỉ hàm phổ quát&lt;/strong&gt; (&lt;em&gt;universal function approximators&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_conclusion_universal_approx.jpg&quot; alt=&quot;Kết luận: universal function approximator&quot; /&gt;
&lt;em&gt;Hình: Kết luận cốt lõi — mạng nơ-ron là bộ xấp xỉ hàm phổ quát. (Minh họa từ video về bản chất mạng nơ-ron)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Tuy nhiên, định lý này có những giới hạn quan trọng. Thứ nhất, nó chỉ khẳng định sự tồn tại của tham số \(\theta\) chứ không đảm bảo thuật toán &lt;em&gt;gradient descent&lt;/em&gt; sẽ tìm được tham số đó. Thứ hai, số lượng nơ-ron cần thiết ở tầng ẩn có thể tăng theo hàm mũ, điều không khả thi trong thực tế. Thứ ba, định lý xét mạng nông nên chưa giải thích được vì sao mạng sâu thường hiệu quả hơn khi áp dụng vào bài toán thực tiễn.&lt;/p&gt;

&lt;h3 id=&quot;vì-sao-độ-sâu-quan-trọng&quot;&gt;Vì sao độ sâu quan trọng&lt;/h3&gt;

&lt;p&gt;Dù mạng nông đủ mạnh về mặt lý thuyết, &lt;strong&gt;mạng sâu&lt;/strong&gt; thường tiết kiệm tham số hơn theo cấp số mũ đối với nhiều hàm thực tế. Xét một hàm có cấu trúc hợp thành gồm \(k\) mức: \(f = f_k \circ f_{k-1} \circ \cdots \circ f_1\). Một mạng nông có thể cần số nơ-ron tăng theo hàm mũ để xấp xỉ hàm này, trong khi mạng sâu có \(k\) tầng có thể biểu diễn tự nhiên với số tham số chỉ tăng theo đa thức.&lt;/p&gt;

&lt;p&gt;Trực giác toán học đằng sau điều này là nhiều hàm trong tự nhiên vốn có cấu trúc hợp thành. Để nhận diện khuôn mặt, hệ thống trước hết phát hiện các cạnh, sau đó ghép cạnh thành các bộ phận (mắt, mũi, miệng), rồi tổng hợp các bộ phận thành khuôn mặt hoàn chỉnh. Cấu trúc phân cấp đó được mô tả trực tiếp qua chuỗi phép biến đổi giữa các tầng:&lt;/p&gt;

&lt;p&gt;\(\mathbf{h}^{(1)} = \sigma(\mathbf{W}^{(1)}\mathbf{x} + \mathbf{b}^{(1)})\)
\(\mathbf{h}^{(2)} = \sigma(\mathbf{W}^{(2)}\mathbf{h}^{(1)} + \mathbf{b}^{(2)})\)
\(\vdots\)
\(\mathbf{y} = \mathbf{W}^{(L)}\mathbf{h}^{(L-1)} + \mathbf{b}^{(L)}\)&lt;/p&gt;

&lt;p&gt;trong đó \(\sigma\) là hàm kích hoạt phi tuyến (ReLU, sigmoid, tanh), \(\mathbf{W}^{(l)}\) là ma trận trọng số và \(\mathbf{b}^{(l)}\) là vector độ lệch (&lt;em&gt;bias&lt;/em&gt;) tại tầng \(l\).&lt;/p&gt;

&lt;h3 id=&quot;mục-tiêu-học&quot;&gt;Mục tiêu học&lt;/h3&gt;

&lt;p&gt;Huấn luyện mạng nơ-ron là quá trình tìm tập tham số \(\theta = \{\mathbf{W}^{(1)}, \mathbf{b}^{(1)}, \ldots, \mathbf{W}^{(L)}, \mathbf{b}^{(L)}\}\) nhằm cực tiểu hóa hàm mất mát \(\mathcal{L}(\theta)\) đo sai số dự đoán:&lt;/p&gt;

\[\theta^* = \arg\min_\theta \frac{1}{n}\sum_{i=1}^n \mathcal{L}(f_\theta(\mathbf{x}_i), y_i)\]

&lt;p&gt;Với bài toán phân loại, ta thường dùng hàm mất mát entropy chéo (&lt;em&gt;cross-entropy&lt;/em&gt;):
\(\mathcal{L}(\hat{\mathbf{y}}, \mathbf{y}) = -\sum_j y_j \log \hat{y}_j\)&lt;/p&gt;

&lt;p&gt;Với bài toán hồi quy, ta thường dùng sai số bình phương trung bình:
\(\mathcal{L}(\hat{y}, y) = \frac{1}{2}(y - \hat{y})^2\)&lt;/p&gt;

&lt;p&gt;Quá trình tối ưu được thực hiện bằng &lt;strong&gt;gradient descent&lt;/strong&gt;, tức cập nhật tham số lặp đi lặp lại theo hướng làm giảm hàm mất mát:&lt;/p&gt;

\[\theta \leftarrow \theta - \eta \nabla_\theta \mathcal{L}(\theta)\]

&lt;p&gt;trong đó \(\eta\) là tốc độ học (&lt;em&gt;learning rate&lt;/em&gt;). Khả năng tính gradient hiệu quả nhờ lan truyền ngược (&lt;em&gt;backpropagation&lt;/em&gt;) — áp dụng quy tắc dây chuyền qua từng tầng — là yếu tố giúp việc huấn luyện mạng sâu trở nên khả thi.&lt;/p&gt;

&lt;h3 id=&quot;vì-sao-học-sâu-hoạt-động-hiệu-quả-cân-bằng-biasvariance&quot;&gt;Vì sao học sâu hoạt động hiệu quả: cân bằng bias–variance&lt;/h3&gt;

&lt;p&gt;Thành công của học sâu có thể được nhìn qua lăng kính cân bằng độ chệch–phương sai (&lt;em&gt;bias–variance tradeoff&lt;/em&gt;) cổ điển. Độ chệch cao (&lt;em&gt;underfitting&lt;/em&gt;) xảy ra khi mô hình quá đơn giản để nắm bắt cấu trúc dữ liệu, còn phương sai cao (&lt;em&gt;overfitting&lt;/em&gt;) xảy ra khi mô hình khớp cả nhiễu thay vì quy luật thực. Mạng sâu có dung lượng biểu diễn rất lớn (độ chệch thấp), nhưng khi được chính quy hóa phù hợp lại có khả năng chống quá khớp tốt và giữ phương sai thấp ngay cả khi số tham số lên tới hàng triệu — thường lớn hơn nhiều so với số mẫu huấn luyện.&lt;/p&gt;

&lt;p&gt;Hiện tượng này thoạt nhìn mâu thuẫn với lý thuyết học thống kê cổ điển, vốn khuyến nghị mô hình nên đơn giản hơn dữ liệu. Các nghiên cứu lý thuyết gần đây về hiện tượng “giảm kép” (&lt;em&gt;double descent&lt;/em&gt;) và “chính quy hóa ngầm” (&lt;em&gt;implicit regularization&lt;/em&gt;) cho thấy các mạng thừa tham số (&lt;em&gt;overparameterized&lt;/em&gt;) khi huấn luyện bằng &lt;em&gt;gradient descent&lt;/em&gt; có xu hướng ưu tiên những hàm đơn giản hơn, tạo ra một cơ chế chính quy hóa tự động mà khung lý thuyết cổ điển chưa mô tả đầy đủ.&lt;/p&gt;

&lt;h2 id=&quot;3-ví-dụ-và-trực-giác&quot;&gt;3. Ví dụ và trực giác&lt;/h2&gt;

&lt;p&gt;Để hình dung cụ thể cách học sâu vận hành, ta xét bài toán kinh điển: huấn luyện mạng nhận dạng chữ số viết tay.&lt;/p&gt;

&lt;h3 id=&quot;bài-toán-nhận-dạng-chữ-số-mnist&quot;&gt;Bài toán: nhận dạng chữ số MNIST&lt;/h3&gt;

&lt;p&gt;Giả sử ta có các ảnh xám kích thước 28×28 của chữ số viết tay (từ 0 đến 9) và muốn xây dựng hệ thống nhận diện đúng chữ số trong từng ảnh. Mỗi ảnh có thể biểu diễn dưới dạng vector 784 chiều (28×28 = 784 điểm ảnh, mỗi điểm ảnh có cường độ sáng từ 0 đến 255).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cách tiếp cận truyền thống&lt;/strong&gt; đòi hỏi thiết kế đặc trưng thủ công, chẳng hạn:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đếm số vòng kín (0, 6, 8, 9 có vòng kín; 1 và 7 không có).&lt;/li&gt;
  &lt;li&gt;Phát hiện các nét dọc và nét ngang.&lt;/li&gt;
  &lt;li&gt;Đo tỷ lệ chiều cao trên chiều rộng.&lt;/li&gt;
  &lt;li&gt;Xác định các điểm đầu mút và giao điểm của nét.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cách làm này đòi hỏi nhiều công sức chuyên môn và khó khái quát hóa sang các bài toán tương tự (ví dụ chữ cái viết hoa hoặc các kiểu chữ khác).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cách tiếp cận học sâu&lt;/strong&gt; đưa trực tiếp toàn bộ 784 giá trị điểm ảnh vào mạng nơ-ron:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (784 pixels) → Hidden Layer 1 (128 neurons) → Hidden Layer 2 (64 neurons) → Output (10 classes)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Trong quá trình huấn luyện, mạng tự động học các tầng đặc trưng:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tầng 1:&lt;/strong&gt; hình thành các bộ phát hiện cạnh — những nơ-ron kích hoạt mạnh trước nét dọc, nét ngang hoặc đường cong tại các vị trí khác nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng 2:&lt;/strong&gt; kết hợp các cạnh thành mẫu nét phức tạp hơn — nét dọc dài (cho 1, 7), vòng tròn (cho 0, 6, 8, 9), hoặc các tổ hợp đường cong đặc trưng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tầng đầu ra:&lt;/strong&gt; tổng hợp các mẫu này để phân loại chữ số hoàn chỉnh.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;quá-trình-học-diễn-ra-như-thế-nào&quot;&gt;Quá trình học diễn ra như thế nào&lt;/h3&gt;

&lt;p&gt;Ban đầu, các trọng số được khởi tạo ngẫu nhiên. Khi đưa vào một ảnh chữ số “3”:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền xuôi (&lt;em&gt;forward pass&lt;/em&gt;):&lt;/strong&gt; Mạng đưa ra dự đoán ngẫu nhiên, chẳng hạn gán xác suất 70% cho chữ số “7”.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính sai số:&lt;/strong&gt; Nhãn đúng là “3” trong khi dự đoán là “7”, tạo ra giá trị mất mát lớn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lan truyền ngược (&lt;em&gt;backpropagation&lt;/em&gt;):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Tầng đầu ra xác định cần tăng mức kích hoạt của nơ-ron ứng với lớp “3” và giảm mức kích hoạt của nơ-ron ứng với lớp “7”.&lt;/li&gt;
      &lt;li&gt;Các tầng ẩn tính toán mức độ đóng góp của từng kích hoạt vào sai số để xác định hướng điều chỉnh trọng số tương ứng.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cập nhật trọng số:&lt;/strong&gt; Điều chỉnh nhẹ toàn bộ trọng số nhằm giảm sai số cho mẫu này.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lặp lại:&lt;/strong&gt; Sau khi xử lý hàng nghìn ảnh chữ số “3” với nhiều nét viết khác nhau, mạng dần rút ra các đặc trưng cốt lõi giúp nhận diện chữ số “3”.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Điểm đáng chú ý là quy trình tương đối đơn giản này — lan truyền xuôi, tính sai số, lan truyền ngược và cập nhật trọng số — khi lặp lại đủ nhiều lần trên dữ liệu sẽ tự hình thành các đặc trưng phân cấp cần thiết cho bài toán nhận dạng.&lt;/p&gt;

&lt;h3 id=&quot;vì-sao-học-phân-cấp-quan-trọng&quot;&gt;Vì sao học phân cấp quan trọng&lt;/h3&gt;

&lt;p&gt;Xét ví dụ bài toán nhận diện khuôn mặt:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đặc trưng mức thấp (Tầng 1):&lt;/strong&gt; phát hiện cạnh theo nhiều hướng và các vùng màu cơ bản.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đặc trưng mức trung (Tầng 2–3):&lt;/strong&gt; ghép cạnh thành hình dạng đơn giản như đường cong, góc và kết cấu bề mặt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đặc trưng mức cao (Tầng 4–5):&lt;/strong&gt; kết hợp hình dạng thành bộ phận khuôn mặt — mắt (cặp vùng tối kèm điểm sáng), mũi (vùng tam giác có đổ bóng), miệng (vùng tối nằm ngang, có thể kèm răng).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khái niệm hoàn chỉnh (Tầng đầu ra):&lt;/strong&gt; tổng hợp các bộ phận để xác định danh tính khuôn mặt.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mỗi tầng học một mức biểu diễn trừu tượng cao hơn, phản ánh tự nhiên bản chất hợp thành của nhận thức thị giác. Mạng nhận ra rằng mắt, mũi, miệng là những thành phần có thể tái sử dụng trên mọi khuôn mặt, tương tự như nét thẳng và đường cong là các thành phần dùng chung ở mọi chữ số.&lt;/p&gt;

&lt;p&gt;Biểu diễn phân cấp và phân tán này cũng giúp cải thiện hiệu quả sử dụng dữ liệu. Khi mạng đã học được các nơ-ron phát hiện cạnh hay vòng tròn từ bài toán chữ số, những nơ-ron đó có thể tiếp tục hữu ích cho việc nhận diện chữ cái, khuôn mặt hoặc vật thể khác — giúp &lt;strong&gt;học chuyển giao&lt;/strong&gt; (&lt;em&gt;transfer learning&lt;/em&gt;) hoạt động hiệu quả nhờ các đặc trưng mức thấp được chia sẻ.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;nguồn-video-tham-chiếu&quot;&gt;Nguồn video (tham chiếu)&lt;/h2&gt;

&lt;p&gt;Một số hình minh họa trong bài được trích từ video của kênh &lt;em&gt;Machine Learning Thực Chiến&lt;/em&gt;. Nguồn gốc để tra cứu:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/720970114372332&quot;&gt;Mạng nơ-ron là bộ xấp xỉ hàm&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, tiếng Anh. Giới thiệu trực quan mạng nơ-ron nhiều tầng như một bộ xấp xỉ hàm, sát với định nghĩa trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=CqOfi41LfDw&quot;&gt;The Essential Main Ideas of Neural Networks&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Trình bày chậm rãi về nút, trọng số và ý tưởng khớp đường cong, giải thích rõ từng đại lượng.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sWPNm_GhhCA&quot;&gt;Tất tần tật về Neural Network trong 12 phút&lt;/a&gt; — Việt Nguyễn AI, tiếng Việt. Giải thích cấu trúc mạng nơ-ron nhiều tầng bằng tiếng Việt, phù hợp để ôn nhanh khái niệm.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00 Giới thiệu</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_Introduction</id>
   <content type="html">&lt;p&gt;Nếu ví một mạng nơ-ron sâu như một chiếc phi thuyền liên hành tinh, thì toán học nền tảng chính là bản thiết kế động cơ và hệ thống dẫn đường giúp phi thuyền không bao giờ lạc quỹ đạo. Nhiều người học Deep Learning vội vàng lao ngay vào gọi hàm &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.backward()&lt;/code&gt; trong PyTorch, để rồi lúng túng mỗi khi hàm mất mát đột ngột bùng nổ thành &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; hay mô hình đứng yên không chịu hội tụ. Chương 00 được thiết kế như tấm bản đồ sinh tồn toán học, kết nối trực giác hình học của giải tích, đại số tuyến tính, tôpô và xác suất với những dòng code thực chiến bạn sẽ viết xuyên suốt khóa học.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-toán-học-nâng-đỡ-mọi-mô-hình-học-sâu&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột toán học nâng đỡ mọi mô hình Học sâu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Giải tích đa biến và tối ưu hóa (Calculus)&lt;/strong&gt;:
Cung cấp ngôn ngữ để đo độ nhạy của sai số theo hàng triệu trọng số thông qua đạo hàm riêng, vector gradient và chuỗi Taylor—trái tim của thuật toán lan truyền ngược (&lt;em&gt;backpropagation&lt;/em&gt;) và Gradient Descent.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đại số tuyến tính (Linear Algebra)&lt;/strong&gt;:
Biến dữ liệu (ảnh, câu chữ, âm thanh) thành vector và tensor, đồng thời mô tả mỗi lớp mạng nơ-ron như một phép biến đổi tuyến tính bằng phép nhân ma trận tốc độ cao trên GPU.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Giải tích thực và Tôpô (Real Analysis &amp;amp; Topology)&lt;/strong&gt;:
Đảm bảo các khái niệm tưởng chừng trừu tượng như tập compact, tính liên tục hay hội tụ thực sự bảo chứng cho sự tồn tại của nghiệm tối ưu và tính ổn định số học khi huấn luyện.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Xác suất và Thống kê (Probability &amp;amp; Statistics)&lt;/strong&gt;:
Giúp mạng nơ-ron không chỉ đoán bừa mà biết định lượng độ bất định, từ đó giải thích vì sao hàm Cross-Entropy hay MSE lại tự nhiên xuất phát từ nguyên lý Ước lượng Hợp lý Cực đại (MLE).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-một-bước-học-của-nơ-ron-đơn-nhìn-qua-cả-bốn-nhánh-toán-học&quot;&gt;Giải thích: Một bước học của nơ-ron đơn nhìn qua cả bốn nhánh toán học&lt;/h3&gt;

&lt;p&gt;Hãy theo dõi một nơ-ron cực nhỏ dự đoán giá trị \(y = 1\) từ đầu vào \(x = 2\) với trọng số khởi tạo \(w = 0.2\) và hàm mất mát bình phương \(L(w) = \frac{1}{2}(wx - y)^2\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đại số tuyến tính (Lan truyền xuôi)&lt;/strong&gt;: Nhân vô hướng đầu vào với trọng số: \(\hat{y} = wx = 0.2 \times 2 = 0.4\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất (Ý nghĩa hàm mất mát)&lt;/strong&gt;: Sai số bình phương \(L(0.2) = \frac{1}{2}(0.4 - 1)^2 = \frac{1}{2}(-0.6)^2 = 0.18\) tương ứng với âm log-likelihood của phân phối chuẩn có phương sai bằng \(1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giải tích (Tính gradient)&lt;/strong&gt;: Đạo hàm theo \(w\) là \(\frac{dL}{dw} = (wx - y)x = (0.4 - 1) \times 2 = -1.2\). Dấu âm cho biết cần tăng \(w\) để giảm sai số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tôpô &amp;amp; Hội tụ (Bước cập nhật)&lt;/strong&gt;: Với tốc độ học \(\eta = 0.1\), ta cập nhật \(w_{\text{mới}} = 0.2 - 0.1 \times (-1.2) = 0.32\). Khi đó \(\hat{y}_{\text{mới}} = 0.64\) và \(L(0.32) = \frac{1}{2}(0.64 - 1)^2 = 0.0648 &amp;lt; 0.18\). Chỉ một dòng code &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;w -= lr * grad&lt;/code&gt;, nhưng cả bốn trụ cột toán học đều đang vận hành đồng bộ phía sau!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Tối ưu hóa giữ vai trò trung tâm trong khoa học dữ liệu. Dù bạn đang huấn luyện mạng nơ-ron, cực tiểu hóa sai số trong mô hình hồi quy hay phân bổ tài nguyên trong hệ thống gợi ý, về bản chất bạn đều đang giải bài toán tìm nghiệm tốt nhất trong một không gian khả năng rất lớn. Để làm việc hiệu quả với các bài toán này, bạn cần nắm vững ngôn ngữ toán học nền tảng. Chương này ôn tập các khái niệm cốt lõi từ đại số tuyến tính, lý thuyết tập hợp, giải tích và xác suất, giúp bạn xử lý tốt gradient, ma trận, ràng buộc và yếu tố bất định trong các tác vụ tối ưu hóa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Đọc thêm (tùy chọn, 2022–2026):&lt;/strong&gt; Sau khi học xong phần toán nền tảng, bạn có thể xem bài &lt;strong&gt;00-99 Ứng dụng và cập nhật hiện đại&lt;/strong&gt; để tìm hiểu về trình biên dịch vi phân tự động (JAX, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;) cũng như cách gradient, ma trận và hàm hợp lý xuất hiện trong học máy khoa học (&lt;em&gt;scientific ML&lt;/em&gt;) và huấn luyện theo quy luật mở rộng (&lt;em&gt;scaling law&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Luyện phỏng vấn (tùy chọn):&lt;/strong&gt; Sau các bài về xác suất và giải tích, bạn có thể xem &lt;strong&gt;00-98 Luyện phỏng vấn&lt;/strong&gt; với các câu hỏi gốc về entropy, phân kỳ KL và vi phân tự động; bộ ngân hàng câu hỏi có lời giải đầy đủ được cung cấp miễn phí dưới dạng PDF trong &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=gq0m_2Glz0g&quot;&gt;MaDL - Introduction&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Video giới thiệu ngắn gọn các kiến thức đại số tuyến tính, giải tích và xác suất mà chương này giả định trước khi đi vào mạng nơ-ron.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Vectors&lt;/td&gt;
          &lt;td&gt;Chapter 1, Essence of linear algebra](https://www.youtube.com/watch?v=fNk_zzaMoSs) — 3Blue1Brown, tiếng Anh. Cách tiếp cận vector trong video này cũng là cách các bài sau biểu diễn trọng số, giá trị kích hoạt và điểm dữ liệu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pA83XtLeVig&quot;&gt;L01.4 Probability Axioms&lt;/a&gt; — MIT OpenCourseWare, tiếng Anh. Ba tiên đề xác suất trong bài giảng này là nền tảng xuyên suốt nửa sau của chương.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-98 Luyện phỏng vấn (lý thuyết thông tin và giải tích)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Trong các buổi phỏng vấn vị trí Machine Learning / Deep Learning Engineer tại những công ty công nghệ hàng đầu, người phỏng vấn hiếm khi hỏi bạn thuộc lòng cú pháp PyTorch. Thay vào đó, họ đặt ra những câu hỏi toán học sắc lẹm chỉ dài hai dòng—như &lt;em&gt;“Hãy phân tách Cross-Entropy thành Entropy và KL-Divergence”&lt;/em&gt; hay &lt;em&gt;“Điều gì xảy ra với Thông tin Tương hỗ của một bộ phân loại hoàn hảo?”&lt;/em&gt;—để kiểm tra xem bạn có thực sự hiểu bản chất đằng sau dòng code mình viết hay không. Bài luyện phỏng vấn này rèn cho bạn tư duy trả lời gọn, chặt chẽ và chạm đúng gốc rễ lý thuyết thông tin cùng giải tích.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-lý-thuyết-thông-tin--giải-tích-hay-gặp-nhất-khi-phỏng-vấn&quot;&gt;Kiến thức cần nhớ: Ba trụ cột Lý thuyết Thông tin &amp;amp; Giải tích hay gặp nhất khi Phỏng vấn&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Entropy (\(H(P)\)), Cross-Entropy (\(H(P, Q)\)) và KL-Divergence (\(D_{\text{KL}}(P \| Q)\))&lt;/strong&gt;:
Ba đại lượng gắn kết bằng đẳng thức vàng \(H(P, Q) = H(P) + D_{\text{KL}}(P \| Q)\). Vì \(H(P)\) cố định theo dữ liệu thật, tối thiểu hóa Cross-Entropy tương đương kéo phân phối dự đoán \(Q\) sát phân phối thật \(P\) theo khoảng cách KL.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Thông tin Tương hỗ (Mutual Information \(I(X; Y)\))&lt;/strong&gt;:
Đo lượng bất định về \(Y\) được giảm bớt khi biết \(X\): \(I(X; Y) = H(Y) - H(Y \mid X) = D_{\text{KL}}(P_{XY} \| P_X P_Y)\). Khác với hệ số tương quan tuyến tính, \(I(X; Y)\) phát hiện được cả quan hệ phi tuyến.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Giải tích trong Tối ưu hóa (Độ lồi, Bất đẳng thức Jensen, Điểm dừng)&lt;/strong&gt;:
Bất đẳng thức Jensen là vũ khí chứng minh nhanh \(D_{\text{KL}}(P \| Q) \ge 0\) (bất đẳng thức Gibbs) cũng như suy ra cận dưới ELBO trong Variational Autoencoder—những câu hỏi phỏng vấn cấp độ Senior/Research.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-entropy-cross-entropy-và-kl-divergence-trên-phân-phối-2-lớp&quot;&gt;Giải thích: Tính tay Entropy, Cross-Entropy và KL-Divergence trên phân phối 2 lớp&lt;/h3&gt;

&lt;p&gt;Giả sử phân phối nhãn thật của một bài toán là \(P = (0.8, 0.2)\) và mô hình của bạn dự đoán \(Q = (0.5, 0.5)\) (dùng log cơ số 2, đơn vị &lt;em&gt;bit&lt;/em&gt;):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Entropy của phân phối thật \(P\)&lt;/strong&gt; (độ bất định tối thiểu không thể vượt qua):
\(H(P) = -(0.8\log_2 0.8 + 0.2\log_2 0.2) \approx -(0.8 \times (-0.3219) + 0.2 \times (-2.3219)) = 0.2575 + 0.4644 = 0.7219\text{ bit}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-Entropy giữa \(P\) và \(Q\)&lt;/strong&gt;:
\(H(P, Q) = -(0.8\log_2 0.5 + 0.2\log_2 0.5) = -(0.8(-1) + 0.2(-1)) = 1.0000\text{ bit}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;KL-Divergence (lượng bit “phí phạm” do dùng mô hình \(Q\) thay vì \(P\))&lt;/strong&gt;:
\(D_{\text{KL}}(P \| Q) = 0.8\log_2\frac{0.8}{0.5} + 0.2\log_2\frac{0.2}{0.5} \approx 0.8(0.6781) + 0.2(-1.3219) = 0.5425 - 0.2644 = 0.2781\text{ bit}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng đẳng thức vàng&lt;/strong&gt;: \(H(P) + D_{\text{KL}}(P \| Q) = 0.7219 + 0.2781 = 1.0000 = H(P, Q)\). Khi phỏng vấn, chỉ cần trình bày đẳng thức này kèm ví dụ số gọn gàng như trên là bạn đã ghi điểm tuyệt đối!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-luyện-phỏng-vấn--lý-thuyết-thông-tin-và-giải-tích&quot;&gt;Tùy chọn: Luyện phỏng vấn — Lý thuyết thông tin và giải tích&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là phần &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế các bài học cốt lõi về giải tích, đại số tuyến tính và xác suất. Sau khi hoàn thành những bài đó, bạn có thể luyện tập với các câu hỏi dưới đây, rồi tham khảo thêm &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) để xem thêm ngân hàng câu hỏi đã có lời giải cùng chủ đề.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Chủ đề tương ứng trong sách (đọc trực tiếp trong bản PDF):&lt;/strong&gt; lý thuyết thông tin — entropy, phân kỳ KL, thông tin tương hỗ — cùng giải tích và trực giác về vi phân tự động (&lt;em&gt;automatic differentiation&lt;/em&gt;).&lt;/p&gt;

&lt;p&gt;Trang tổng hợp lộ trình: &lt;strong&gt;01-98 Lộ trình luyện Deep Learning Interviews&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;bộ-câu-hỏi-luyện-tập-biên-soạn-gốc&quot;&gt;Bộ câu hỏi luyện tập (biên soạn gốc)&lt;/h2&gt;

&lt;h3 id=&quot;q1-phân-tách-cross-entropy&quot;&gt;Q1. Phân tách cross-entropy&lt;/h3&gt;

&lt;p&gt;Cho \(p\) là nhãn one-hot trên \(K\) lớp và \(q\) là phân phối dự đoán từ softmax. Hãy chứng minh&lt;/p&gt;

\[\mathrm{CE}(p,q) = H(p) + D_{\mathrm{KL}}(p\|q)\]

&lt;p&gt;và giải thích vì sao \(H(p) = 0\) trong thiết lập học có giám sát thông thường.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Khai triển \(D_{\mathrm{KL}}(p\|q) = \sum_k p_k \log(p_k/q_k)\) và áp dụng quy ước \(0\log 0 := 0\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Ta có \(\mathrm{CE}(p,q) = -\sum_k p_k\log q_k\). Phân kỳ KL chênh lệch với cross-entropy đúng một lượng \(H(p) = -\sum_k p_k\log p_k\), và lượng này bằng 0 khi \(p\) là phân phối one-hot (tập trung toàn bộ xác suất tại một lớp). Do đó, dù ta cài đặt hàm mất mát là cross-entropy, quá trình huấn luyện thực chất đang cực tiểu hóa phân kỳ KL giữa phân phối dự đoán và phân phối thực nghiệm one-hot. Khi dùng nhãn mềm (như &lt;em&gt;label smoothing&lt;/em&gt;), \(H(p)\) là một hằng số dương — không ảnh hưởng đến gradient theo \(q\), nhưng cần lưu ý khi đọc giá trị cross-entropy báo cáo.&lt;/p&gt;

&lt;h3 id=&quot;q2-thông-tin-tương-hỗ-của-bộ-phân-loại-hoàn-hảo&quot;&gt;Q2. Thông tin tương hỗ của bộ phân loại hoàn hảo&lt;/h3&gt;

&lt;p&gt;Cho \(Y\) là nhãn nhị phân cân bằng và \(\hat Y\) là nhãn dự đoán cứng. Giá trị \(I(Y;\hat Y)\) bằng bao nhiêu nếu bộ phân loại dự đoán hoàn hảo, và bằng bao nhiêu nếu nó luôn dự đoán lớp đa số?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Dùng đẳng thức \(I(Y;\hat Y) = H(Y) - H(Y\mid\hat Y)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Khi bộ phân loại dự đoán hoàn hảo, biết \(\hat Y\) xác định hoàn toàn \(Y\) nên \(H(Y\mid\hat Y) = 0\), suy ra \(I(Y;\hat Y) = H(Y) = 1\) bit (vì \(Y\) cân bằng). Ngược lại, bộ dự đoán hằng độc lập với \(Y\) nên thông tin tương hỗ bằng \(0\). Trên tập dữ liệu mất cân bằng, độ chính xác (&lt;em&gt;accuracy&lt;/em&gt;) vẫn có thể rất cao dù \(I(Y;\hat Y)\) gần bằng 0 — đây là tình huống đối lập thường gặp trong phỏng vấn.&lt;/p&gt;

&lt;h3 id=&quot;q3-tính-gradient-bằng-quy-tắc-dây-chuyền&quot;&gt;Q3. Tính gradient bằng quy tắc dây chuyền&lt;/h3&gt;

&lt;p&gt;Cho \(f(\mathbf{w}) = \sigma(\mathbf{w}^\top\mathbf{x})\) với \(\sigma(z) = (1+e^{-z})^{-1}\) và \(\mathbf{x}\) cố định. Viết biểu thức \(\nabla_{\mathbf{w}} f\) dưới dạng gọn để cài đặt trực tiếp trong một dòng mã.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Sử dụng \(\sigma&apos;(z) = \sigma(z)\bigl(1-\sigma(z)\bigr)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Ta có \(\nabla_{\mathbf{w}} f = \sigma(\mathbf{w}^\top\mathbf{x})\bigl(1-\sigma(\mathbf{w}^\top\mathbf{x})\bigr)\,\mathbf{x}\). Hệ số đạo hàm cục bộ này cũng xuất hiện trong hồi quy logistic (Chương 03). Vi phân tự động chế độ ngược (&lt;em&gt;reverse-mode autodiff&lt;/em&gt;) tính gradient đi ngược từ đầu ra vô hướng \(f\) mà không cần dựng tường minh ma trận Jacobian theo \(\mathbf{w}\).&lt;/p&gt;

&lt;h3 id=&quot;q4-vì-sao-chế-độ-ngược-hiệu-quả-hơn-khi-hàm-mất-mát-là-vô-hướng&quot;&gt;Q4. Vì sao chế độ ngược hiệu quả hơn khi hàm mất mát là vô hướng&lt;/h3&gt;

&lt;p&gt;Xét một mạng nơ-ron ánh xạ \(\mathbb{R}^n\to\mathbb{R}\) (một giá trị mất mát duy nhất). Vì sao vi phân tự động chế độ ngược chỉ tốn chi phí cỡ “một lượt xuôi + một lượt ngược” và gần như không phụ thuộc \(n\), trong khi chế độ xuôi có chi phí tỉ lệ với \(n\)?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Chế độ xuôi lan truyền từng hướng đầu vào một; chế độ ngược lan truyền từ đầu ra vô hướng duy nhất.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Chế độ xuôi (&lt;em&gt;forward-mode&lt;/em&gt;) tính tích Jacobian–vector \(J\mathbf{v}\). Để thu đủ mọi đạo hàm riêng của một hàm vô hướng theo \(n\) biến đầu vào, cần thực hiện \(n\) lượt tính với các vector cơ sở chuẩn. Ngược lại, chế độ ngược (&lt;em&gt;reverse-mode&lt;/em&gt;) tính tích vector–Jacobian \(\mathbf{u}^\top J\); với \(\mathbf{u}=1\), chỉ cần một lượt quét ngược là thu được toàn bộ vector gradient. Đây là lý do các framework học sâu cài đặt chế độ ngược (lan truyền ngược). Chế độ xuôi chỉ lợi thế hơn khi số đầu ra lớn hơn nhiều so với số đầu vào.&lt;/p&gt;

&lt;h3 id=&quot;q5-ma-trận-hessian-và-độ-cong-cục-bộ&quot;&gt;Q5. Ma trận Hessian và độ cong cục bộ&lt;/h3&gt;

&lt;p&gt;Với \(f(\mathbf{x}) = \tfrac12\mathbf{x}^\top A\mathbf{x}\) và \(A\) là ma trận đối xứng xác định dương, ma trận Hessian \(\nabla^2 f\) bằng gì? Số điều kiện \(\kappa(A)\) lớn ảnh hưởng thế nào đến thuật toán gradient descent?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gợi ý.&lt;/strong&gt; Liên hệ với khai triển Taylor bậc hai trong bài giải tích: Hessian là ma trận của số hạng bậc hai.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Thảo luận.&lt;/strong&gt; Ta có \(\nabla^2 f = A\). Khi số điều kiện \(\kappa(A)=\lambda_{\max}/\lambda_{\min}\) lớn, các đường mức bị kéo dài thành thung lũng hẹp khiến gradient descent dao động zic-zac: độ dài bước đủ an toàn để không phân kỳ theo trục dốc lại quá nhỏ để tiến nhanh dọc theo trục phẳng. Trong phỏng vấn, câu trả lời mang trực giác hình học này thường là bước đệm trước khi chuyển sang các câu hỏi về Adam hoặc phương pháp Newton.&lt;/p&gt;

&lt;h2 id=&quot;ghi-công&quot;&gt;Ghi công&lt;/h2&gt;

&lt;p&gt;Kashani, S., và Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Bạn có thể tải bản PDF từ arXiv để xem đầy đủ bộ câu hỏi và lời giải. Trang này là bài luyện tập biên soạn riêng cho khóa học, không phải bản sao lại từ sách.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pXh53lqPkHs&quot;&gt;MaDL - Information and Entropy&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Trình bày khái niệm entropy dùng trực tiếp trong các câu hỏi lý thuyết thông tin của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vPvnpC0PNVQ&quot;&gt;MaDL - Kullback-Leibler Divergence&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Giải thích phân kỳ KL — đại lượng lý thuyết thông tin trọng tâm thứ hai trong bài luyện tập.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[The paradox of the derivative&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of calculus](https://www.youtube.com/watch?v=9vKqVkMQHKk) — 3Blue1Brown, tiếng Anh. Củng cố trực giác về đạo hàm, nền tảng cho các câu hỏi giải tích và vi phân tự động.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-05 Bài tập trắc nghiệm - Khái niệm cơ bản</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_05_Quiz_Basic_Concepts/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_05_Quiz_Basic_Concepts</id>
   <content type="html">&lt;p&gt;Đọc hiểu một công thức toán học trên màn hình thường tạo ra một ảo giác rất ngọt ngào: ta thấy “có lý” và nghĩ mình đã nắm vững, cho đến khi tự tay giải một bài toán trắc nghiệm bẫy và phát hiện mình vẫn nhầm giữa liên tục đều với Lipschitz, hay giữa độc lập với xung khắc. Bài kiểm tra tổng hợp này là trạm kiểm định chất lượng cho toàn bộ Chương 00—giúp bạn tự soi lại lỗ hổng kiến thức trên cả bốn mảng Giải tích, Đại số tuyến tính, Tôpô và Xác suất trước khi bước vào thế giới mạng nơ-ron.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-cụm-năng-lực-được-kiểm-tra-trong-bộ-trắc-nghiệm-chương-00&quot;&gt;Kiến thức cần nhớ: Bốn cụm năng lực được kiểm tra trong Bộ Trắc nghiệm Chương 00&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Giải tích &amp;amp; Tối ưu hóa (Đạo hàm, Gradient, Chuỗi Taylor, Lipschitz)&lt;/strong&gt;:
Kiểm tra khả năng tính nhanh đạo hàm riêng, đọc hướng tăng/giảm nhanh nhất từ vector gradient và nhận diện điều kiện áp dụng xấp xỉ Taylor.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đại số tuyến tính (Vector, Ma trận, Hạng, Giá trị riêng)&lt;/strong&gt;:
Kiểm tra tư duy về chiều ma trận hợp lệ, tính không giao hoán, ý nghĩa hình học của định thức và cách giá trị riêng quyết định hành vi của phép nhân ma trận lặp.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tập hợp &amp;amp; Tôpô trong \(\mathbb{R}^n\) (Tập mở, Đóng, Compact, Lồi)&lt;/strong&gt;:
Kiểm tra các phản ví dụ kinh điển—nơi trực giác dễ đánh lừa nhất như tập không mở cũng không đóng, hay hàm liên tục trên tập mở không có cực trị.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Xác suất &amp;amp; Thống kê (Tiên đề, Bayes, Phân phối, MLE)&lt;/strong&gt;:
Kiểm tra phân biệt biến cố xung khắc vs. độc lập, tính xác suất có điều kiện bằng định lý Bayes và lập hàm log-likelihood để tìm ước lượng MLE.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-chiến-thuật-giải-nhanh-2-câu-bẫy-kinh-điển-trước-khi-làm-bài&quot;&gt;Giải thích: Chiến thuật giải nhanh 2 câu bẫy kinh điển trước khi làm bài&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Bẫy 1 — Phân biệt “Xung khắc” (Mutually Exclusive) và “Độc lập” (Independent):&lt;/strong&gt;
Giả sử hai biến cố \(A, B\) đều có xác suất dương: \(P(A) = 0.4, P(B) = 0.5\). Nếu \(A\) và \(B\) &lt;strong&gt;xung khắc&lt;/strong&gt;, chúng có độc lập không?&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Vì xung khắc nên \(P(A \cap B) = 0\).&lt;/li&gt;
  &lt;li&gt;Nếu độc lập thì phải có \(P(A \cap B) = P(A)P(B) = 0.4 \times 0.5 = 0.2 \ne 0\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kết luận&lt;/strong&gt;: Hai biến cố có xác suất dương mà xung khắc thì &lt;strong&gt;chắc chắn phụ thuộc mạnh&lt;/strong&gt; (biết \(A\) xảy ra là biết ngay \(B\) không thể xảy ra!).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Bẫy 2 — Kiểm tra nhanh kích thước phép nhân ma trận trong mạng nơ-ron:&lt;/strong&gt;
Nếu đầu vào mini-batch \(\mathbf{X}\) có kích thước \((32 \times 784)\) và lớp ẩn có \(128\) nơ-ron với phép tính \(\mathbf{Z} = \mathbf{X}\mathbf{W} + \mathbf{b}\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Để nhân được với \((32 \times 784)\), số hàng của \(\mathbf{W}\) phải bằng \(784\), số cột bằng \(128 \implies \mathbf{W} \in \mathbb{R}^{784 \times 128}\), kết quả \(\mathbf{Z} \in \mathbb{R}^{32 \times 128}\).
Hãy giữ thói quen kiểm tra bằng ví dụ số nhỏ như vậy với mọi câu hỏi trắc nghiệm bên dưới!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bài tập trắc nghiệm này giúp bạn kiểm tra mức độ nắm vững các khái niệm nền tảng của giải tích, đại số tuyến tính và xác suất — cơ sở trực tiếp cho tối ưu hóa và học sâu.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;-ôn-tập-lý-thuyết&quot;&gt;📚 Ôn tập lý thuyết&lt;/h2&gt;

&lt;p&gt;Trước khi làm bài tập, hãy ôn lại các khái niệm chính trong chương này:&lt;/p&gt;

&lt;h3 id=&quot;-giải-tích-cơ-bản&quot;&gt;🔢 &lt;strong&gt;Giải tích cơ bản&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm và đạo hàm riêng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đạo hàm: \(f&apos;(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}\)&lt;/li&gt;
  &lt;li&gt;Đạo hàm riêng: \(\frac{\partial f}{\partial x_i}\) — đạo hàm theo \(x_i\) khi giữ cố định các biến còn lại&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Gradient và đạo hàm có hướng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Gradient: \(\nabla f = \begin{pmatrix} \frac{\partial f}{\partial x_1} \\ \vdots \\ \frac{\partial f}{\partial x_n} \end{pmatrix}\) — vector chỉ hướng tăng nhanh nhất của hàm số&lt;/li&gt;
  &lt;li&gt;Đạo hàm có hướng: \(D_{\mathbf{u}}f = \nabla f \cdot \mathbf{u} = \|\nabla f\| \cos \theta\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Chuỗi Taylor:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Bậc 1: \(f(\mathbf{x}) \approx f(\mathbf{x}_0) + \nabla f(\mathbf{x}_0)^T (\mathbf{x} - \mathbf{x}_0)\)&lt;/li&gt;
  &lt;li&gt;Bậc 2: \(f(\mathbf{x}) \approx f(\mathbf{x}_0) + \nabla f(\mathbf{x}_0)^T (\mathbf{x} - \mathbf{x}_0) + \frac{1}{2} (\mathbf{x} - \mathbf{x}_0)^T \nabla^2 f(\mathbf{x}_0) (\mathbf{x} - \mathbf{x}_0)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-đại-số-tuyến-tính&quot;&gt;📐 &lt;strong&gt;Đại số tuyến tính&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Vector và không gian vector:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Vector: danh sách có thứ tự các số \(\mathbf{v} = \begin{pmatrix} v_1 \\ \vdots \\ v_n \end{pmatrix}\)&lt;/li&gt;
  &lt;li&gt;Không gian \(\mathbb{R}^n\): tập tất cả vector có \(n\) thành phần&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Các phép toán vector:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Cộng vector: \(\mathbf{u} + \mathbf{v} = \begin{pmatrix} u_1 + v_1 \\ \vdots \\ u_n + v_n \end{pmatrix}\)&lt;/li&gt;
  &lt;li&gt;Nhân vô hướng: \(c\mathbf{v} = \begin{pmatrix} cv_1 \\ \vdots \\ cv_n \end{pmatrix}\)&lt;/li&gt;
  &lt;li&gt;Tích vô hướng: \(\mathbf{u} \cdot \mathbf{v} = \sum_{i=1}^n u_i v_i = \|\mathbf{u}\| \|\mathbf{v}\| \cos \theta\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Chuẩn vector:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chuẩn L2 (Euclid): \(\|\mathbf{x}\|_2 = \sqrt{\sum_{i=1}^n x_i^2}\)&lt;/li&gt;
  &lt;li&gt;Chuẩn L1 (Manhattan): \(\|\mathbf{x}\|_1 = \sum_{i=1}^n \lvert x_i \rvert\)&lt;/li&gt;
  &lt;li&gt;Chuẩn L∞ (Max): \(\|\mathbf{x}\|_\infty = \max_i \lvert x_i \rvert\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ma trận:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Phép nhân ma trận: \((AB)_{ij} = \sum_{k} A_{ik} B_{kj}\)&lt;/li&gt;
  &lt;li&gt;Ma trận nghịch đảo: \(AA^{-1} = I\) (nếu tồn tại)&lt;/li&gt;
  &lt;li&gt;Định thức: \(\det(A)\) — đo hệ số thay đổi thể tích của phép biến đổi tuyến tính&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Giá trị riêng (&lt;em&gt;eigenvalue&lt;/em&gt;) và vector riêng (&lt;em&gt;eigenvector&lt;/em&gt;):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(A\mathbf{v} = \lambda \mathbf{v}\) với \(\mathbf{v} \neq \mathbf{0}\)&lt;/li&gt;
  &lt;li&gt;\(\lambda\): giá trị riêng, \(\mathbf{v}\): vector riêng tương ứng&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-lý-thuyết-tập-hợp-và-giải-tích-thực&quot;&gt;📊 &lt;strong&gt;Lý thuyết tập hợp và giải tích thực&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tập hợp cơ bản:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tập mở: mọi điểm đều có lân cận nằm trong tập&lt;/li&gt;
  &lt;li&gt;Tập đóng: chứa tất cả điểm biên&lt;/li&gt;
  &lt;li&gt;Tập compact: đóng và bị chặn trong \(\mathbb{R}^n\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Tính liên tục:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Hàm liên tục tại \(x_0\): \(\lim_{x \to x_0} f(x) = f(x_0)\)&lt;/li&gt;
  &lt;li&gt;Liên tục đều: \(\forall \epsilon &amp;gt; 0, \exists \delta &amp;gt; 0\) sao cho \(\lvert x-y \rvert &amp;lt; \delta \Rightarrow \lvert f(x)-f(y) \rvert &amp;lt; \epsilon\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;-xác-suất-cơ-bản&quot;&gt;🎲 &lt;strong&gt;Xác suất cơ bản&lt;/strong&gt;&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Khái niệm cơ bản:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Xác suất: \(P(A) \in [0,1]\), \(P(\Omega) = 1\)&lt;/li&gt;
  &lt;li&gt;Biến ngẫu nhiên: ánh xạ từ không gian mẫu vào tập số thực&lt;/li&gt;
  &lt;li&gt;Kỳ vọng: \(E[X] = \int x f(x) dx\) (liên tục) hoặc \(E[X] = \sum x P(X=x)\) (rời rạc)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phân phối thông dụng:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Chuẩn: \(X \sim N(\mu, \sigma^2)\)&lt;/li&gt;
  &lt;li&gt;Đều: \(X \sim U(a,b)\)&lt;/li&gt;
  &lt;li&gt;Bernoulli: \(X \sim \text{Ber}(p)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;p&gt;💡 &lt;strong&gt;Gợi ý ôn tập:&lt;/strong&gt; Những khái niệm trên là nền tảng trực tiếp của tối ưu hóa: gradient chỉ hướng tăng nhanh nhất, ma trận Hessian mô tả độ cong, còn khai triển Taylor giúp xấp xỉ hàm số trong vùng lân cận.&lt;/p&gt;

&lt;hr /&gt;

&lt;div id=&quot;quiz-container&quot;&gt;
    &lt;div id=&quot;quiz-header&quot;&gt;
        &lt;h2&gt;Bài tập trắc nghiệm: Khái niệm cơ bản&lt;/h2&gt;
        &lt;p&gt;Chọn đáp án đúng nhất cho mỗi câu hỏi. Bạn sẽ nhận được kết quả ngay sau khi hoàn thành.&lt;/p&gt;
        &lt;div id=&quot;progress-bar&quot;&gt;
            &lt;div id=&quot;progress-fill&quot;&gt;&lt;/div&gt;
        &lt;/div&gt;
        &lt;p id=&quot;progress-text&quot;&gt;Câu hỏi 1/25&lt;/p&gt;
    &lt;/div&gt;

    &lt;div id=&quot;quiz-questions&quot;&gt;
        &lt;!-- Câu hỏi 1: Đạo hàm cơ bản --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q1&quot;&gt;
            &lt;h3&gt;Câu 1: Đạo hàm của hàm số $$f(x) = x^3 + 2x^2 - 5x + 1$$ tại $$x = 1$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q1&quot; value=&quot;a&quot; /&gt; A) $$4$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q1&quot; value=&quot;b&quot; /&gt; B) $$2$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q1&quot; value=&quot;c&quot; /&gt; C) $$-1$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q1&quot; value=&quot;d&quot; /&gt; D) $$6$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: B) $$2$$&lt;/strong&gt;&lt;br /&gt;
                $$f&apos;(x) = 3x^2 + 4x - 5$$&lt;br /&gt;
                $$f&apos;(1) = 3(1)^2 + 4(1) - 5 = 3 + 4 - 5 = 2$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 2: Đạo hàm riêng --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q2&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 2: Cho $$f(x,y) = x^2y + 3xy^2$$. Đạo hàm riêng $$\frac{\partial f}{\partial x}$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q2&quot; value=&quot;a&quot; /&gt; A) $$2xy + 3y^2$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q2&quot; value=&quot;b&quot; /&gt; B) $$x^2 + 6xy$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q2&quot; value=&quot;c&quot; /&gt; C) $$2xy + 6xy$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q2&quot; value=&quot;d&quot; /&gt; D) $$x^2 + 3y^2$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$2xy + 3y^2$$&lt;/strong&gt;&lt;br /&gt;
                Khi tính đạo hàm riêng theo $$x$$, ta coi $$y$$ là hằng số:&lt;br /&gt;
                $$\frac{\partial f}{\partial x} = \frac{\partial}{\partial x}(x^2y + 3xy^2) = 2xy + 3y^2$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 3: Gradient --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q3&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 3: Gradient của hàm $$f(x,y) = x^2 + 2xy + y^2$$ tại điểm $$(1,1)$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q3&quot; value=&quot;a&quot; /&gt; A) $$\begin{pmatrix} 4 \\ 4 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q3&quot; value=&quot;b&quot; /&gt; B) $$\begin{pmatrix} 2 \\ 2 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q3&quot; value=&quot;c&quot; /&gt; C) $$\begin{pmatrix} 3 \\ 3 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q3&quot; value=&quot;d&quot; /&gt; D) $$\begin{pmatrix} 1 \\ 1 \end{pmatrix}$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$\begin{pmatrix} 4 \\ 4 \end{pmatrix}$$&lt;/strong&gt;&lt;br /&gt;
                $$\frac{\partial f}{\partial x} = 2x + 2y$$, $$\frac{\partial f}{\partial y} = 2x + 2y$$&lt;br /&gt;
                Tại $$(1,1)$$: $$\nabla f(1,1) = \begin{pmatrix} 2(1) + 2(1) \\ 2(1) + 2(1) \end{pmatrix} = \begin{pmatrix} 4 \\ 4 \end{pmatrix}$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 4: Đạo hàm có hướng --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q4&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 4: Cho gradient $$\nabla f = \begin{pmatrix} 3 \\ 4 \end{pmatrix}$$ và vector đơn vị $$\mathbf{u} = \begin{pmatrix} 0.6 \\ 0.8 \end{pmatrix}$$. Đạo hàm có hướng $$D_{\mathbf{u}}f$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q4&quot; value=&quot;a&quot; /&gt; A) $$5$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q4&quot; value=&quot;b&quot; /&gt; B) $$4.2$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q4&quot; value=&quot;c&quot; /&gt; C) $$3.2$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q4&quot; value=&quot;d&quot; /&gt; D) $$7$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$5$$&lt;/strong&gt;&lt;br /&gt;
                $$D_{\mathbf{u}}f = \nabla f \cdot \mathbf{u} = 3(0.6) + 4(0.8) = 1.8 + 3.2 = 5$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 5: Hướng tăng dốc nhất --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q5&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 5: Hướng tăng dốc nhất của hàm số luôn là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q5&quot; value=&quot;a&quot; /&gt; A) Hướng của vector gradient&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q5&quot; value=&quot;b&quot; /&gt; B) Hướng ngược với vector gradient&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q5&quot; value=&quot;c&quot; /&gt; C) Hướng vuông góc với vector gradient&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q5&quot; value=&quot;d&quot; /&gt; D) Hướng của trục x&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) Hướng của vector gradient&lt;/strong&gt;&lt;br /&gt;
                Gradient luôn chỉ theo hướng tăng dốc nhất của hàm số. Đây là một tính chất cơ bản của gradient.
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 6: Phép cộng vector --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q6&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 6: Cho $$\mathbf{u} = \begin{pmatrix} 2 \\ -1 \\ 3 \end{pmatrix}$$ và $$\mathbf{v} = \begin{pmatrix} 1 \\ 4 \\ -2 \end{pmatrix}$$. Vector $$\mathbf{u} + \mathbf{v}$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q6&quot; value=&quot;a&quot; /&gt; A) $$\begin{pmatrix} 3 \\ 3 \\ 1 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q6&quot; value=&quot;b&quot; /&gt; B) $$\begin{pmatrix} 1 \\ -5 \\ 5 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q6&quot; value=&quot;c&quot; /&gt; C) $$\begin{pmatrix} 2 \\ 4 \\ -6 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q6&quot; value=&quot;d&quot; /&gt; D) $$\begin{pmatrix} 3 \\ -3 \\ 1 \end{pmatrix}$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$\begin{pmatrix} 3 \\ 3 \\ 1 \end{pmatrix}$$&lt;/strong&gt;&lt;br /&gt;
                $$\mathbf{u} + \mathbf{v} = \begin{pmatrix} 2+1 \\ -1+4 \\ 3+(-2) \end{pmatrix} = \begin{pmatrix} 3 \\ 3 \\ 1 \end{pmatrix}$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 7: Tích vô hướng --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q7&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 7: Tích vô hướng của $$\mathbf{a} = \begin{pmatrix} 1 \\ 2 \\ 3 \end{pmatrix}$$ và $$\mathbf{b} = \begin{pmatrix} 4 \\ 5 \\ 6 \end{pmatrix}$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q7&quot; value=&quot;a&quot; /&gt; A) $$32$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q7&quot; value=&quot;b&quot; /&gt; B) $$14$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q7&quot; value=&quot;c&quot; /&gt; C) $$18$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q7&quot; value=&quot;d&quot; /&gt; D) $$24$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$32$$&lt;/strong&gt;&lt;br /&gt;
                $$\mathbf{a} \cdot \mathbf{b} = 1 \cdot 4 + 2 \cdot 5 + 3 \cdot 6 = 4 + 10 + 18 = 32$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 8: Chuẩn Euclid --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q8&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 8: Chuẩn Euclid của vector $$\mathbf{v} = \begin{pmatrix} 3 \\ 4 \end{pmatrix}$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q8&quot; value=&quot;a&quot; /&gt; A) $$5$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q8&quot; value=&quot;b&quot; /&gt; B) $$7$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q8&quot; value=&quot;c&quot; /&gt; C) $$25$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q8&quot; value=&quot;d&quot; /&gt; D) $$\sqrt{7}$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$5$$&lt;/strong&gt;&lt;br /&gt;
                $$\|\mathbf{v}\|_2 = \sqrt{3^2 + 4^2} = \sqrt{9 + 16} = \sqrt{25} = 5$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 9: Vector trực giao --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q9&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 9: Hai vector $$\mathbf{u}$$ và $$\mathbf{v}$$ được gọi là trực giao khi:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q9&quot; value=&quot;a&quot; /&gt; A) $$\mathbf{u} \cdot \mathbf{v} = 0$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q9&quot; value=&quot;b&quot; /&gt; B) $$\mathbf{u} \cdot \mathbf{v} = 1$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q9&quot; value=&quot;c&quot; /&gt; C) $$\|\mathbf{u}\| = \|\mathbf{v}\|$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q9&quot; value=&quot;d&quot; /&gt; D) $$\mathbf{u} + \mathbf{v} = \mathbf{0}$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$\mathbf{u} \cdot \mathbf{v} = 0$$&lt;/strong&gt;&lt;br /&gt;
                Hai vector trực giao (vuông góc) khi và chỉ khi tích vô hướng của chúng bằng 0.
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 10: Phép nhân ma trận --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q10&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 10: Tích của hai ma trận $$\begin{pmatrix} 1 &amp;amp; 2 \\ 3 &amp;amp; 4 \end{pmatrix} \begin{pmatrix} 2 &amp;amp; 0 \\ 1 &amp;amp; 3 \end{pmatrix}$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q10&quot; value=&quot;a&quot; /&gt; A) $$\begin{pmatrix} 4 &amp;amp; 6 \\ 10 &amp;amp; 12 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q10&quot; value=&quot;b&quot; /&gt; B) $$\begin{pmatrix} 4 &amp;amp; 3 \\ 10 &amp;amp; 12 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q10&quot; value=&quot;c&quot; /&gt; C) $$\begin{pmatrix} 2 &amp;amp; 0 \\ 3 &amp;amp; 12 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q10&quot; value=&quot;d&quot; /&gt; D) $$\begin{pmatrix} 2 &amp;amp; 6 \\ 10 &amp;amp; 14 \end{pmatrix}$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$\begin{pmatrix} 4 &amp;amp; 6 \\ 10 &amp;amp; 12 \end{pmatrix}$$&lt;/strong&gt;&lt;br /&gt;
                Phần tử $$(1,1)$$: $$1 \cdot 2 + 2 \cdot 1 = 4$$&lt;br /&gt;
                Phần tử $$(1,2)$$: $$1 \cdot 0 + 2 \cdot 3 = 6$$&lt;br /&gt;
                Phần tử $$(2,1)$$: $$3 \cdot 2 + 4 \cdot 1 = 10$$&lt;br /&gt;
                Phần tử $$(2,2)$$: $$3 \cdot 0 + 4 \cdot 3 = 12$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 11: Ma trận đơn vị --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q11&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 11: Ma trận đơn vị $$2 \times 2$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q11&quot; value=&quot;a&quot; /&gt; A) $$\begin{pmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q11&quot; value=&quot;b&quot; /&gt; B) $$\begin{pmatrix} 0 &amp;amp; 1 \\ 1 &amp;amp; 0 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q11&quot; value=&quot;c&quot; /&gt; C) $$\begin{pmatrix} 1 &amp;amp; 1 \\ 1 &amp;amp; 1 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q11&quot; value=&quot;d&quot; /&gt; D) $$\begin{pmatrix} 2 &amp;amp; 0 \\ 0 &amp;amp; 2 \end{pmatrix}$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$\begin{pmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{pmatrix}$$&lt;/strong&gt;&lt;br /&gt;
                Ma trận đơn vị có các phần tử trên đường chéo chính bằng 1 và các phần tử khác bằng 0.
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 12: Ma trận chuyển vị --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q12&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 12: Chuyển vị của ma trận $$\begin{pmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 4 &amp;amp; 5 &amp;amp; 6 \end{pmatrix}$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q12&quot; value=&quot;a&quot; /&gt; A) $$\begin{pmatrix} 1 &amp;amp; 4 \\ 2 &amp;amp; 5 \\ 3 &amp;amp; 6 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q12&quot; value=&quot;b&quot; /&gt; B) $$\begin{pmatrix} 6 &amp;amp; 5 &amp;amp; 4 \\ 3 &amp;amp; 2 &amp;amp; 1 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q12&quot; value=&quot;c&quot; /&gt; C) $$\begin{pmatrix} 4 &amp;amp; 1 \\ 5 &amp;amp; 2 \\ 6 &amp;amp; 3 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q12&quot; value=&quot;d&quot; /&gt; D) $$\begin{pmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 4 &amp;amp; 5 &amp;amp; 6 \end{pmatrix}$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$\begin{pmatrix} 1 &amp;amp; 4 \\ 2 &amp;amp; 5 \\ 3 &amp;amp; 6 \end{pmatrix}$$&lt;/strong&gt;&lt;br /&gt;
                Chuyển vị của ma trận được tạo bằng cách hoán đổi hàng và cột.
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 13: Định thức 2x2 --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q13&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 13: Định thức của ma trận $$\begin{pmatrix} 3 &amp;amp; 1 \\ 2 &amp;amp; 4 \end{pmatrix}$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q13&quot; value=&quot;a&quot; /&gt; A) $$10$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q13&quot; value=&quot;b&quot; /&gt; B) $$14$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q13&quot; value=&quot;c&quot; /&gt; C) $$2$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q13&quot; value=&quot;d&quot; /&gt; D) $$12$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$10$$&lt;/strong&gt;&lt;br /&gt;
                $$\det\begin{pmatrix} 3 &amp;amp; 1 \\ 2 &amp;amp; 4 \end{pmatrix} = 3 \cdot 4 - 1 \cdot 2 = 12 - 2 = 10$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 14: Độc lập tuyến tính --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q14&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 14: Hai vector $$\mathbf{v}_1 = \begin{pmatrix} 1 \\ 2 \end{pmatrix}$$ và $$\mathbf{v}_2 = \begin{pmatrix} 2 \\ 4 \end{pmatrix}$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q14&quot; value=&quot;a&quot; /&gt; A) Độc lập tuyến tính&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q14&quot; value=&quot;b&quot; /&gt; B) Phụ thuộc tuyến tính&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q14&quot; value=&quot;c&quot; /&gt; C) Trực giao&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q14&quot; value=&quot;d&quot; /&gt; D) Không thể xác định&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: B) Phụ thuộc tuyến tính&lt;/strong&gt;&lt;br /&gt;
                $$\mathbf{v}_2 = 2\mathbf{v}_1$$, do đó hai vector này phụ thuộc tuyến tính.
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 15: Chuẩn Manhattan --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q15&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 15: Chuẩn Manhattan (L1) của vector $$\mathbf{v} = \begin{pmatrix} -2 \\ 3 \\ -1 \end{pmatrix}$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q15&quot; value=&quot;a&quot; /&gt; A) $$6$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q15&quot; value=&quot;b&quot; /&gt; B) $$0$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q15&quot; value=&quot;c&quot; /&gt; C) $$4$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q15&quot; value=&quot;d&quot; /&gt; D) $$\sqrt{14}$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$6$$&lt;/strong&gt;&lt;br /&gt;
                $$\|\mathbf{v}\|_1 = |-2| + |3| + |-1| = 2 + 3 + 1 = 6$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 16: Quy tắc dây chuyền --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q16&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 16: Cho $$z = x^2 + y^2$$ với $$x = 2t$$ và $$y = 3t$$. Đạo hàm $$\frac{dz}{dt}$$ tại $$t = 1$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q16&quot; value=&quot;a&quot; /&gt; A) $$26$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q16&quot; value=&quot;b&quot; /&gt; B) $$13$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q16&quot; value=&quot;c&quot; /&gt; C) $$10$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q16&quot; value=&quot;d&quot; /&gt; D) $$5$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$26$$&lt;/strong&gt;&lt;br /&gt;
                $$\frac{dz}{dt} = \frac{\partial z}{\partial x}\frac{dx}{dt} + \frac{\partial z}{\partial y}\frac{dy}{dt} = 2x \cdot 2 + 2y \cdot 3$$&lt;br /&gt;
                Tại $$t = 1$$: $$x = 2, y = 3$$, nên $$\frac{dz}{dt} = 2(2)(2) + 2(3)(3) = 8 + 18 = 26$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 17: Điểm tới hạn --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q17&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 17: Điểm tới hạn của hàm số là điểm mà:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q17&quot; value=&quot;a&quot; /&gt; A) Gradient bằng vector không&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q17&quot; value=&quot;b&quot; /&gt; B) Hàm số đạt giá trị lớn nhất&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q17&quot; value=&quot;c&quot; /&gt; C) Hàm số đạt giá trị nhỏ nhất&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q17&quot; value=&quot;d&quot; /&gt; D) Hàm số không xác định&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) Gradient bằng vector không&lt;/strong&gt;&lt;br /&gt;
                Điểm tới hạn là điểm mà gradient của hàm số bằng vector không, tức là $$\nabla f = \mathbf{0}$$.
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 18: Ma trận nghịch đảo --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q18&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 18: Ma trận $$\begin{pmatrix} 2 &amp;amp; 1 \\ 1 &amp;amp; 1 \end{pmatrix}$$ có nghịch đảo là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q18&quot; value=&quot;a&quot; /&gt; A) $$\begin{pmatrix} 1 &amp;amp; -1 \\ -1 &amp;amp; 2 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q18&quot; value=&quot;b&quot; /&gt; B) $$\begin{pmatrix} 1 &amp;amp; 1 \\ 1 &amp;amp; 2 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q18&quot; value=&quot;c&quot; /&gt; C) $$\begin{pmatrix} 2 &amp;amp; -1 \\ -1 &amp;amp; 1 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q18&quot; value=&quot;d&quot; /&gt; D) $$\begin{pmatrix} 0.5 &amp;amp; 0.5 \\ 0.5 &amp;amp; 1 \end{pmatrix}$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$\begin{pmatrix} 1 &amp;amp; -1 \\ -1 &amp;amp; 2 \end{pmatrix}$$&lt;/strong&gt;&lt;br /&gt;
                $$\det(A) = 2 \cdot 1 - 1 \cdot 1 = 1$$&lt;br /&gt;
                $$A^{-1} = \frac{1}{1}\begin{pmatrix} 1 &amp;amp; -1 \\ -1 &amp;amp; 2 \end{pmatrix} = \begin{pmatrix} 1 &amp;amp; -1 \\ -1 &amp;amp; 2 \end{pmatrix}$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 19: Đường mức --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q19&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 19: Gradient của hàm số tại một điểm luôn:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q19&quot; value=&quot;a&quot; /&gt; A) Vuông góc với đường mức tại điểm đó&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q19&quot; value=&quot;b&quot; /&gt; B) Song song với đường mức tại điểm đó&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q19&quot; value=&quot;c&quot; /&gt; C) Tạo góc 45° với đường mức&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q19&quot; value=&quot;d&quot; /&gt; D) Không có mối quan hệ với đường mức&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) Vuông góc với đường mức tại điểm đó&lt;/strong&gt;&lt;br /&gt;
                Gradient luôn vuông góc với đường mức vì đường mức là tập hợp các điểm có cùng giá trị hàm số.
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 20: Ứng dụng trong tối ưu hóa --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q20&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 20: Trong thuật toán gradient descent, chúng ta di chuyển theo hướng:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q20&quot; value=&quot;a&quot; /&gt; A) Ngược với hướng gradient&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q20&quot; value=&quot;b&quot; /&gt; B) Cùng hướng với gradient&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q20&quot; value=&quot;c&quot; /&gt; C) Vuông góc với gradient&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q20&quot; value=&quot;d&quot; /&gt; D) Hướng ngẫu nhiên&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) Ngược với hướng gradient&lt;/strong&gt;&lt;br /&gt;
                Gradient descent di chuyển theo hướng $$-\nabla f$$ để tìm điểm cực tiểu của hàm số.
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 21: Tính toán đạo hàm bậc hai --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q21&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 21: Đạo hàm bậc hai của hàm $$f(x) = 3x^4 - 2x^3 + x^2 - 5x + 1$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q21&quot; value=&quot;a&quot; /&gt; A) $$36x^2 - 12x + 2$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q21&quot; value=&quot;b&quot; /&gt; B) $$12x^3 - 6x^2 + 2x - 5$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q21&quot; value=&quot;c&quot; /&gt; C) $$36x^2 - 12x + 1$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q21&quot; value=&quot;d&quot; /&gt; D) $$12x^2 - 6x + 2$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$36x^2 - 12x + 2$$&lt;/strong&gt;&lt;br /&gt;
                $$f&apos;(x) = 12x^3 - 6x^2 + 2x - 5$$&lt;br /&gt;
                $$f&apos;&apos;(x) = 36x^2 - 12x + 2$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 22: Ứng dụng ma trận Hessian --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q22&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 22: Cho $$f(x,y) = x^2 + 2xy + 3y^2$$. Ma trận Hessian tại điểm $$(1,1)$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q22&quot; value=&quot;a&quot; /&gt; A) $$\begin{pmatrix} 2 &amp;amp; 2 \\ 2 &amp;amp; 6 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q22&quot; value=&quot;b&quot; /&gt; B) $$\begin{pmatrix} 1 &amp;amp; 2 \\ 2 &amp;amp; 3 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q22&quot; value=&quot;c&quot; /&gt; C) $$\begin{pmatrix} 2 &amp;amp; 1 \\ 1 &amp;amp; 6 \end{pmatrix}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q22&quot; value=&quot;d&quot; /&gt; D) $$\begin{pmatrix} 4 &amp;amp; 4 \\ 4 &amp;amp; 8 \end{pmatrix}$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$\begin{pmatrix} 2 &amp;amp; 2 \\ 2 &amp;amp; 6 \end{pmatrix}$$&lt;/strong&gt;&lt;br /&gt;
                $$\frac{\partial^2 f}{\partial x^2} = 2$$, $$\frac{\partial^2 f}{\partial y^2} = 6$$, $$\frac{\partial^2 f}{\partial x \partial y} = 2$$&lt;br /&gt;
                Ma trận Hessian không phụ thuộc vào điểm cụ thể trong trường hợp này.
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 23: Tính toán thực tế với vector --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q23&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 23: Khoảng cách từ điểm $$A(1,2)$$ đến điểm $$B(4,6)$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q23&quot; value=&quot;a&quot; /&gt; A) $$5$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q23&quot; value=&quot;b&quot; /&gt; B) $$7$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q23&quot; value=&quot;c&quot; /&gt; C) $$\sqrt{13}$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q23&quot; value=&quot;d&quot; /&gt; D) $$3$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$5$$&lt;/strong&gt;&lt;br /&gt;
                Khoảng cách = $$\sqrt{(4-1)^2 + (6-2)^2} = \sqrt{9 + 16} = \sqrt{25} = 5$$
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 24: Ứng dụng eigenvalue --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q24&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 24: Các giá trị riêng (eigenvalue) của ma trận $$A = \begin{pmatrix} 3 &amp;amp; 1 \\ 0 &amp;amp; 2 \end{pmatrix}$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q24&quot; value=&quot;a&quot; /&gt; A) $$\lambda_1 = 3, \lambda_2 = 2$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q24&quot; value=&quot;b&quot; /&gt; B) $$\lambda_1 = 3, \lambda_2 = 1$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q24&quot; value=&quot;c&quot; /&gt; C) $$\lambda_1 = 1, \lambda_2 = 5$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q24&quot; value=&quot;d&quot; /&gt; D) $$\lambda_1 = 0, \lambda_2 = 5$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$\lambda_1 = 3, \lambda_2 = 2$$&lt;/strong&gt;&lt;br /&gt;
                Đối với ma trận tam giác trên, các giá trị riêng chính là các phần tử nằm trên đường chéo chính.
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- Câu hỏi 25: Tối ưu hóa đơn giản --&gt;
        &lt;div class=&quot;question&quot; id=&quot;q25&quot; style=&quot;display: none;&quot;&gt;
            &lt;h3&gt;Câu 25: Điểm cực tiểu của hàm $$f(x) = x^2 - 4x + 5$$ là:&lt;/h3&gt;
            &lt;div class=&quot;options&quot;&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q25&quot; value=&quot;a&quot; /&gt; A) $$x = 2$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q25&quot; value=&quot;b&quot; /&gt; B) $$x = -2$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q25&quot; value=&quot;c&quot; /&gt; C) $$x = 4$$&lt;/label&gt;
                &lt;label&gt;&lt;input type=&quot;radio&quot; name=&quot;q25&quot; value=&quot;d&quot; /&gt; D) $$x = 0$$&lt;/label&gt;
            &lt;/div&gt;
            &lt;div class=&quot;explanation&quot; style=&quot;display: none;&quot;&gt;
                &lt;strong&gt;Đáp án đúng: A) $$x = 2$$&lt;/strong&gt;&lt;br /&gt;
                $$f&apos;(x) = 2x - 4 = 0 \Rightarrow x = 2$$&lt;br /&gt;
                $$f&apos;&apos;(x) = 2 &amp;gt; 0$$, nên $$x = 2$$ là điểm cực tiểu.
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;div id=&quot;quiz-navigation&quot;&gt;
        &lt;button id=&quot;prev-btn&quot; onclick=&quot;previousQuestion()&quot; disabled=&quot;&quot;&gt;Câu trước&lt;/button&gt;
        &lt;button id=&quot;next-btn&quot; onclick=&quot;nextQuestion()&quot;&gt;Câu tiếp&lt;/button&gt;
        &lt;button id=&quot;submit-btn&quot; onclick=&quot;submitQuiz()&quot; style=&quot;display: none;&quot;&gt;Nộp bài&lt;/button&gt;
    &lt;/div&gt;

    &lt;div id=&quot;quiz-results&quot; style=&quot;display: none;&quot;&gt;
        &lt;h3&gt;Kết quả bài tập&lt;/h3&gt;
        &lt;div id=&quot;score-display&quot;&gt;&lt;/div&gt;
        &lt;div id=&quot;detailed-results&quot;&gt;&lt;/div&gt;
        &lt;button onclick=&quot;restartQuiz()&quot;&gt;Làm lại&lt;/button&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;style&gt;
#quiz-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    font-family: &apos;Segoe UI&apos;, Tahoma, Geneva, Verdana, sans-serif;
}

#quiz-header {
    text-align: center;
    margin-bottom: 30px;
}

#progress-bar {
    width: 100%;
    height: 10px;
    background-color: #e0e0e0;
    border-radius: 5px;
    margin: 20px 0;
    overflow: hidden;
}

#progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #4CAF50, #45a049);
    width: 5%;
    transition: width 0.3s ease;
}

.question {
    background: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 25px;
    margin-bottom: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.question h3 {
    color: #333;
    margin-bottom: 20px;
    font-size: 1.1em;
    line-height: 1.4;
}

.options {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.options label {
    display: flex;
    align-items: center;
    padding: 12px;
    background: white;
    border: 2px solid #e0e0e0;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 1em;
}

.options label:hover {
    border-color: #4CAF50;
    background-color: #f0f8f0;
}

.options input[type=&quot;radio&quot;] {
    margin-right: 12px;
    transform: scale(1.2);
}

.options label.selected {
    border-color: #4CAF50;
    background-color: #e8f5e8;
}

.explanation {
    margin-top: 20px;
    padding: 15px;
    background-color: #e3f2fd;
    border-left: 4px solid #2196F3;
    border-radius: 4px;
    font-size: 0.95em;
    line-height: 1.5;
}

.explanation strong {
    color: #1976D2;
}

#quiz-navigation {
    text-align: center;
    margin: 30px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

#quiz-navigation button {
    background: #4CAF50;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    cursor: pointer;
    font-size: 1em;
    transition: background-color 0.2s ease;
}

#quiz-navigation button:hover:not(:disabled) {
    background: #45a049;
}

#quiz-navigation button:disabled {
    background: #cccccc;
    cursor: not-allowed;
}

#quiz-results {
    text-align: center;
    padding: 30px;
    background: #f0f8f0;
    border-radius: 8px;
    border: 2px solid #4CAF50;
}

#score-display {
    font-size: 1.5em;
    font-weight: bold;
    margin: 20px 0;
    color: #2E7D32;
}

#detailed-results {
    text-align: left;
    margin: 20px 0;
    max-height: 400px;
    overflow-y: auto;
}

.result-item {
    padding: 10px;
    margin: 5px 0;
    border-radius: 4px;
    border-left: 4px solid;
}

.result-item.correct {
    background-color: #e8f5e8;
    border-left-color: #4CAF50;
}

.result-item.incorrect {
    background-color: #ffebee;
    border-left-color: #f44336;
}

@media (max-width: 600px) {
    #quiz-container {
        padding: 10px;
    }
    
    .question {
        padding: 15px;
    }
    
    #quiz-navigation {
        flex-direction: column;
        gap: 10px;
    }
    
    #quiz-navigation button {
        width: 100%;
    }
}
&lt;/style&gt;

&lt;script&gt;
let currentQuestion = 1;
const totalQuestions = 25;
let userAnswers = {};
let quizSubmitted = false;

// Đáp án đúng cho từng câu hỏi
const correctAnswers = {
    q1: &apos;b&apos;, q2: &apos;a&apos;, q3: &apos;a&apos;, q4: &apos;a&apos;, q5: &apos;a&apos;,
    q6: &apos;a&apos;, q7: &apos;a&apos;, q8: &apos;a&apos;, q9: &apos;a&apos;, q10: &apos;a&apos;,
    q11: &apos;a&apos;, q12: &apos;a&apos;, q13: &apos;a&apos;, q14: &apos;b&apos;, q15: &apos;a&apos;,
    q16: &apos;a&apos;, q17: &apos;a&apos;, q18: &apos;a&apos;, q19: &apos;a&apos;, q20: &apos;a&apos;,
    q21: &apos;a&apos;, q22: &apos;a&apos;, q23: &apos;a&apos;, q24: &apos;a&apos;, q25: &apos;a&apos;
};

/**
 * Cập nhật thanh tiến trình và hiển thị câu hỏi hiện tại
 */
function updateProgress() {
    const progressFill = document.getElementById(&apos;progress-fill&apos;);
    const progressText = document.getElementById(&apos;progress-text&apos;);
    
    const percentage = (currentQuestion / totalQuestions) * 100;
    progressFill.style.width = percentage + &apos;%&apos;;
    progressText.textContent = `Câu hỏi ${currentQuestion}/${totalQuestions}`;
}

/**
 * Hiển thị câu hỏi theo số thứ tự
 */
function showQuestion(questionNum) {
    // Ẩn tất cả câu hỏi
    for (let i = 1; i &lt;= totalQuestions; i++) {
        document.getElementById(`q${i}`).style.display = &apos;none&apos;;
    }
    
    // Hiển thị câu hỏi hiện tại
    document.getElementById(`q${questionNum}`).style.display = &apos;block&apos;;
    
    // Cập nhật trạng thái nút điều hướng
    document.getElementById(&apos;prev-btn&apos;).disabled = (questionNum === 1);
    document.getElementById(&apos;next-btn&apos;).style.display = (questionNum === totalQuestions) ? &apos;none&apos; : &apos;inline-block&apos;;
    document.getElementById(&apos;submit-btn&apos;).style.display = (questionNum === totalQuestions) ? &apos;inline-block&apos; : &apos;none&apos;;
    
    updateProgress();
}

/**
 * Chuyển đến câu hỏi tiếp theo
 */
function nextQuestion() {
    if (currentQuestion &lt; totalQuestions) {
        currentQuestion++;
        showQuestion(currentQuestion);
    }
}

/**
 * Quay lại câu hỏi trước
 */
function previousQuestion() {
    if (currentQuestion &gt; 1) {
        currentQuestion--;
        showQuestion(currentQuestion);
    }
}

/**
 * Lưu đáp án của người dùng
 */
function saveAnswer(questionId, answer) {
    userAnswers[questionId] = answer;
    
    // Cập nhật giao diện để hiển thị đáp án đã chọn
    const labels = document.querySelectorAll(`#${questionId} .options label`);
    labels.forEach(label =&gt; {
        label.classList.remove(&apos;selected&apos;);
        if (label.querySelector(&apos;input&apos;).value === answer) {
            label.classList.add(&apos;selected&apos;);
        }
    });
}

/**
 * Nộp bài và hiển thị kết quả
 */
function submitQuiz() {
    if (quizSubmitted) return;
    
    quizSubmitted = true;
    let correctCount = 0;
    let detailedResults = &apos;&apos;;
    
    // Tính điểm và tạo báo cáo chi tiết
    for (let i = 1; i &lt;= totalQuestions; i++) {
        const questionId = `q${i}`;
        const userAnswer = userAnswers[questionId];
        const correctAnswer = correctAnswers[questionId];
        const isCorrect = userAnswer === correctAnswer;
        
        if (isCorrect) correctCount++;
        
        // Hiển thị giải thích cho tất cả câu hỏi
        const explanation = document.querySelector(`#${questionId} .explanation`);
        if (explanation) {
            explanation.style.display = &apos;block&apos;;
        }
        
        // Tạo báo cáo chi tiết
        detailedResults += `
            &lt;div class=&quot;result-item ${isCorrect ? &apos;correct&apos; : &apos;incorrect&apos;}&quot;&gt;
                &lt;strong&gt;Câu ${i}:&lt;/strong&gt; ${isCorrect ? &apos;Đúng&apos; : &apos;Sai&apos;}
                ${!isCorrect ? `&lt;br&gt;&lt;small&gt;Đáp án của bạn: ${userAnswer || &apos;Chưa trả lời&apos;} | Đáp án đúng: ${correctAnswer}&lt;/small&gt;` : &apos;&apos;}
            &lt;/div&gt;
        `;
    }
    
    // Hiển thị kết quả
    const scorePercentage = Math.round((correctCount / totalQuestions) * 100);
    document.getElementById(&apos;score-display&apos;).innerHTML = `
        &lt;div&gt;Điểm số: ${correctCount}/${totalQuestions} (${scorePercentage}%)&lt;/div&gt;
        &lt;div style=&quot;margin-top: 10px; font-size: 0.9em;&quot;&gt;
            ${scorePercentage &gt;= 80 ? &apos;🎉 Xuất sắc!&apos; : 
              scorePercentage &gt;= 60 ? &apos;👍 Khá tốt!&apos; : 
              scorePercentage &gt;= 40 ? &apos;📚 Cần ôn tập thêm&apos; : &apos;💪 Hãy cố gắng hơn!&apos;}
        &lt;/div&gt;
    `;
    
    document.getElementById(&apos;detailed-results&apos;).innerHTML = detailedResults;
    document.getElementById(&apos;quiz-results&apos;).style.display = &apos;block&apos;;
    document.getElementById(&apos;quiz-navigation&apos;).style.display = &apos;none&apos;;
    
    // Cuộn đến kết quả
    document.getElementById(&apos;quiz-results&apos;).scrollIntoView({ behavior: &apos;smooth&apos; });
}

/**
 * Khởi động lại bài tập
 */
function restartQuiz() {
    currentQuestion = 1;
    userAnswers = {};
    quizSubmitted = false;
    
    // Ẩn kết quả và hiển thị lại điều hướng
    document.getElementById(&apos;quiz-results&apos;).style.display = &apos;none&apos;;
    document.getElementById(&apos;quiz-navigation&apos;).style.display = &apos;flex&apos;;
    
    // Ẩn tất cả giải thích
    document.querySelectorAll(&apos;.explanation&apos;).forEach(exp =&gt; {
        exp.style.display = &apos;none&apos;;
    });
    
    // Xóa tất cả lựa chọn
    document.querySelectorAll(&apos;input[type=&quot;radio&quot;]&apos;).forEach(input =&gt; {
        input.checked = false;
    });
    
    document.querySelectorAll(&apos;.options label&apos;).forEach(label =&gt; {
        label.classList.remove(&apos;selected&apos;);
    });
    
    // Hiển thị câu hỏi đầu tiên
    showQuestion(1);
    
    // Cuộn lên đầu
    document.getElementById(&apos;quiz-header&apos;).scrollIntoView({ behavior: &apos;smooth&apos; });
}

// Khởi tạo bài tập khi trang được tải
document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    showQuestion(1);
    
    // Thêm event listener cho tất cả radio button
    document.querySelectorAll(&apos;input[type=&quot;radio&quot;]&apos;).forEach(input =&gt; {
        input.addEventListener(&apos;change&apos;, function() {
            const questionId = this.name;
            const answer = this.value;
            saveAnswer(questionId, answer);
        });
    });
    
    // Render MathJax sau khi DOM được tải
    if (window.MathJax) {
        MathJax.typesetPromise();
    }
});

// Xử lý phím tắt
document.addEventListener(&apos;keydown&apos;, function(event) {
    if (quizSubmitted) return;
    
    switch(event.key) {
        case &apos;ArrowLeft&apos;:
            if (currentQuestion &gt; 1) previousQuestion();
            break;
        case &apos;ArrowRight&apos;:
            if (currentQuestion &lt; totalQuestions) nextQuestion();
            break;
        case &apos;Enter&apos;:
            if (currentQuestion === totalQuestions) submitQuiz();
            break;
    }
});
&lt;/script&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Continuity at a point&lt;/td&gt;
          &lt;td&gt;Limits and continuity&lt;/td&gt;
          &lt;td&gt;AP Calculus AB&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=3KMqU5j7irw) — Khan Academy, tiếng Anh. Phù hợp để ôn lại khái niệm giới hạn và tính liên tục tại một điểm.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Vectors&lt;/td&gt;
          &lt;td&gt;Chapter 1, Essence of linear algebra](https://www.youtube.com/watch?v=fNk_zzaMoSs) — 3Blue1Brown, tiếng Anh. Trực quan hóa bản chất của vector trong không gian \(\mathbb{R}^n\) để hỗ trợ các câu hỏi đại số tuyến tính.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pA83XtLeVig&quot;&gt;L01.4 Probability Axioms&lt;/a&gt; — MIT OpenCourseWare, tiếng Anh. Ôn lại các tiên đề xác suất cơ bản trước khi làm các câu hỏi phần xác suất.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04 Xác Suất và Thống Kê</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_Probability_and_Statistics/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_Probability_and_Statistics</id>
   <content type="html">&lt;p&gt;Thế giới thực không bao giờ sạch sẽ như sách giáo khoa: cảm biến camera luôn có nhiễu hạt, chữ viết tay của hai người cho cùng số “7” có thể hoàn toàn khác nhau, và cùng một câu hỏi có thể có nhiều câu trả lời đúng. Nếu chỉ dùng hàm tất định cứng nhắc, AI sẽ gãy vụn trước sự bất định ấy. &lt;strong&gt;Xác suất và Thống kê&lt;/strong&gt; là ngôn ngữ giúp mạng nơ-ron không chỉ đưa ra dự đoán, mà còn biết mức độ tự tin của mình—đồng thời biến bài toán huấn luyện thành bài toán tìm phân phối xác suất khớp nhất với dữ liệu quan sát được.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-xác-suất--thống-kê-trong-học-sâu&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột Xác suất &amp;amp; Thống kê trong Học sâu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Không gian mẫu, Tiên đề và Định lý Bayes&lt;/strong&gt;:
Đặt nền móng logic chặt chẽ cho việc cập nhật niềm tin (&lt;em&gt;posterior&lt;/em&gt;) khi có thêm dữ liệu quan sát mới (&lt;em&gt;likelihood&lt;/em&gt;) kết hợp với tri thức ban đầu (&lt;em&gt;prior&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Biến ngẫu nhiên và Các phân phối kinh điển&lt;/strong&gt;:
Bernoulli/Categorical mô hình hóa bài toán phân loại; phân phối Chuẩn (Gaussian) mô hình hóa nhiễu hồi quy và khởi tạo trọng số (Xavier/He); phân phối đa biến mô tả tương quan giữa các đặc trưng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ước lượng Hợp lý Cực đại (MLE) và MAP&lt;/strong&gt;:
Cầu nối kỳ diệu nối xác suất với tối ưu hóa: tối đa hóa log-likelihood của dữ liệu cho ra ngay hàm mất mát MSE (với nhiễu Gaussian) và Cross-Entropy (với phân phối Categorical); thêm prior Gaussian cho ra ngay \(L_2\) Regularization!&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kỳ vọng, Phương sai và Luật số lớn&lt;/strong&gt;:
Giải thích vì sao Mini-Batch Stochastic Gradient Descent (SGD) chỉ dùng 32 hoặc 64 mẫu mỗi bước vẫn cho ước lượng không chệch của gradient toàn tập dữ liệu hàng triệu mẫu.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-kiểm-chứng-bằng-tay-ước-lượng-không-chệch-của-mini-batch&quot;&gt;Giải thích: Kiểm chứng bằng tay ước lượng không chệch của Mini-Batch&lt;/h3&gt;

&lt;p&gt;Giả sử toàn tập dữ liệu chỉ có 4 mẫu với gradient riêng lẻ tại tham số hiện tại là: \(g_1 = 2, g_2 = 6, g_3 = -2, g_4 = 10\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gradient thực trên toàn tập (Batch GD)&lt;/strong&gt;:
\(g_{\text{true}} = \frac{2 + 6 + (-2) + 10}{4} = \frac{16}{4} = 4.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lấy ngẫu nhiên mini-batch cỡ 2&lt;/strong&gt; (có \(\binom{4}{2} = 6\) cặp đồng khả năng):
    &lt;ul&gt;
      &lt;li&gt;\(\{1, 2\} \to \frac{2+6}{2} = 4\); \(\{1, 3\} \to \frac{2-2}{2} = 0\); \(\{1, 4\} \to \frac{2+10}{2} = 6\);&lt;/li&gt;
      &lt;li&gt;\(\{2, 3\} \to \frac{6-2}{2} = 2\); \(\{2, 4\} \to \frac{6+10}{2} = 8\); \(\{3, 4\} \to \frac{-2+10}{2} = 4\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính kỳ vọng của ước lượng mini-batch&lt;/strong&gt;:
\(\mathbb{E}[\hat{g}] = \frac{4 + 0 + 6 + 2 + 8 + 4}{6} = \frac{24}{6} = 4 = g_{\text{true}}.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mỗi bước mini-batch có thể dao động quanh \(4\) (từ \(0\) đến \(8\)), nhưng &lt;strong&gt;trung bình đúng bằng gradient thật&lt;/strong&gt;—chính tính chất thống kê này cho phép huấn luyện LLM trên hàng nghìn tỷ token mà không bao giờ phải cộng dồn toàn bộ dataset trong một bước!&lt;/p&gt;

&lt;h2 id=&quot;xác-suất-và-thống-kê-cho-tối-ưu-hóa-lồi&quot;&gt;Xác suất và thống kê cho tối ưu hóa lồi&lt;/h2&gt;

&lt;p&gt;Xác suất và thống kê là nền tảng quan trọng để hiểu nhiều bài toán tối ưu hóa, đặc biệt trong học máy và khoa học dữ liệu. Phần này giới thiệu các khái niệm xác suất thiết yếu thường xuất hiện trong tối ưu hóa lồi, từ ước lượng hợp lý cực đại đến tối ưu hóa Bayes.&lt;/p&gt;

&lt;h3 id=&quot;vì-sao-xác-suất-quan-trọng-trong-tối-ưu-hóa&quot;&gt;Vì sao xác suất quan trọng trong tối ưu hóa&lt;/h3&gt;

&lt;p&gt;Nhiều bài toán tối ưu hóa bắt nguồn trực tiếp từ mô hình hóa thống kê:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ước lượng hợp lý cực đại (MLE):&lt;/strong&gt; tìm tham số cực đại hóa độ hợp lý của dữ liệu quan sát.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tối ưu hóa Bayes:&lt;/strong&gt; dùng mô hình xác suất để định hướng tìm kiếm nghiệm tối ưu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tối ưu hóa ngẫu nhiên:&lt;/strong&gt; xử lý yếu tố bất định và nhiễu ngẫu nhiên trong hàm mục tiêu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điều chuẩn (&lt;em&gt;Regularization&lt;/em&gt;):&lt;/strong&gt; đưa phân phối tiên nghiệm (&lt;em&gt;prior&lt;/em&gt;) vào mô hình nhằm hạn chế quá khớp (&lt;em&gt;overfitting&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cực tiểu hóa rủi ro:&lt;/strong&gt; cực tiểu hóa giá trị kỳ vọng của hàm mất mát trên một phân phối xác suất.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;các-chủ-đề-chính&quot;&gt;Các chủ đề chính&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lý thuyết xác suất cơ bản:&lt;/strong&gt; không gian mẫu, biến cố và tiên đề xác suất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Các phân phối xác suất thông dụng:&lt;/strong&gt; phân phối chuẩn, phân phối mũ và các phân phối quan trọng khác.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kỳ vọng và phương sai:&lt;/strong&gt; cách tính và tối ưu hóa các đại lượng đặc trưng của biến ngẫu nhiên.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định lý Bayes:&lt;/strong&gt; nền tảng cho suy luận và tối ưu hóa Bayes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ước lượng thống kê:&lt;/strong&gt; cầu nối giữa mô hình xác suất và bài toán tối ưu hóa.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;liên-hệ-với-tối-ưu-hóa-lồi&quot;&gt;Liên hệ với tối ưu hóa lồi&lt;/h3&gt;

&lt;p&gt;Nắm vững xác suất giúp bạn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mô hình hóa bài toán:&lt;/strong&gt; chuyển yếu tố bất định thực tế thành bài toán tối ưu hóa toán học.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chọn hàm mục tiêu:&lt;/strong&gt; lựa chọn hàm mất mát phù hợp dựa trên giả định xác suất của dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diễn giải kết quả:&lt;/strong&gt; hiểu khoảng tin cậy và ý nghĩa thống kê của nghiệm thu được.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xử lý nhiễu:&lt;/strong&gt; làm việc hiệu quả với sai số đo lường và quá trình ngẫu nhiên.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thiết kế thuật toán:&lt;/strong&gt; xây dựng phương pháp tối ưu ổn định trước yếu tố bất định.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Nền tảng này sẽ được sử dụng xuyên suốt khi ta khảo sát cách các mô hình xác suất dẫn đến bài toán tối ưu hóa lồi trong học máy, thống kê và các ứng dụng kỹ thuật.&lt;/p&gt;

&lt;div style=&quot;background: #e8f4fd; padding: 15px; border-left: 4px solid #2196F3; margin: 20px 0;&quot;&gt;
&lt;strong&gt;💡 Lộ trình học:&lt;/strong&gt; Hãy bắt đầu từ các khái niệm xác suất cơ bản, sau đó tìm hiểu cách chúng gắn với tối ưu hóa qua ước lượng hợp lý cực đại và suy luận Bayes. Mỗi bài học đều hướng tới việc làm rõ cách yếu tố bất định hình thành nên bài toán tối ưu hóa.
&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pA83XtLeVig&quot;&gt;L01.4 Probability Axioms&lt;/a&gt; — MIT OpenCourseWare, tiếng Anh. Các tiên đề xác suất là nền tảng cho toàn bộ các phân phối trong phần này.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=bvBukLjHZh8&quot;&gt;MaDL - Random Variables and Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Trình bày biến ngẫu nhiên và phân phối xác suất theo ký hiệu chuẩn dùng trong học sâu.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NbzVwvE_syQ&quot;&gt;MaDL - Common Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Giới thiệu các họ phân phối thông dụng (từ Bernoulli đến Gauss) sẽ được phân tích kỹ ở các bài tiếp theo.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-03 Likelihood và Ước Lượng Hợp Lý Tối Đa (MLE)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_03_Likelihood_and_Maximum_Likelihood_Estimation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_03_Likelihood_and_Maximum_Likelihood_Estimation</id>
   <content type="html">&lt;p&gt;Một trong những khoảnh khắc “vỡ òa” lớn nhất khi học Deep Learning là nhận ra rằng những hàm mất mát tưởng như được nghĩ ra một cách tùy hứng—MSE cho hồi quy, Binary Cross-Entropy cho phân loại nhị phân, Categorical Cross-Entropy cho đa lớp—thực chất đều là &lt;strong&gt;cùng một nguyên lý duy nhất&lt;/strong&gt; đội những chiếc mặt nạ khác nhau: &lt;strong&gt;Ước lượng Hợp lý Cực đại (Maximum Likelihood Estimation — MLE)&lt;/strong&gt;. Bài học này mở khóa chiếc cầu nối vĩ đại giữa thống kê và tối ưu hóa, giúp bạn hiểu sâu &lt;em&gt;tại sao&lt;/em&gt; ta lại huấn luyện mạng nơ-ron bằng chính các hàm mất mát đó.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-hàm-hợp-lý-và-mle&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Hàm Hợp lý và MLE&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Xác suất vs. Hàm Hợp lý (Probability vs. Likelihood)&lt;/strong&gt;:
Xác suất cố định tham số \(\theta\) và hỏi dữ liệu \(x\) nào dễ xảy ra (\(P(x \mid \theta)\)); ngược lại, hàm hợp lý cố định dữ liệu \(x\) đã quan sát và xoay tham số \(\theta\) để xem mô hình nào giải thích dữ liệu tốt nhất (\(\mathcal{L}(\theta \mid x)\)).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Chuyển từ Tích sang Tổng nhờ Log-Likelihood&lt;/strong&gt;:
Với \(N\) mẫu độc lập, tích \(\prod_{i=1}^N P(x_i \mid \theta)\) rất nhanh chạm ngưỡng \(0\) trên máy tính (underflow). Lấy logarit tự nhiên biến tích thành tổng \(\sum_{i=1}^N \ln P(x_i \mid \theta)\) mà không làm đổi vị trí cực đại, vì \(\ln\) là hàm đồng biến chặt.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Âm Log-Likelihood (NLL) chính là Hàm Mất mát&lt;/strong&gt;:
Cực đại hóa \(\ln \mathcal{L}(\theta)\) tương đương cực tiểu hóa \(-\ln \mathcal{L}(\theta)\):
    &lt;ul&gt;
      &lt;li&gt;Giả định nhiễu Gaussian \(\implies\) NLL trở thành &lt;strong&gt;MSE&lt;/strong&gt;.&lt;/li&gt;
      &lt;li&gt;Giả định nhãn Bernoulli/Categorical \(\implies\) NLL trở thành &lt;strong&gt;Cross-Entropy&lt;/strong&gt;.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Từ MLE đến MAP (Maximum A Posteriori) và Regularization&lt;/strong&gt;:
Khi nhân thêm phân phối tiên nghiệm \(P(\theta)\) lên tham số (ví dụ Gaussian \(\mathcal{N}(0, \tau^2)\)), âm log hậu nghiệm tự động sinh ra số hạng phạt \(\lambda \|\theta\|_2^2\)—chính là &lt;strong&gt;L2 Regularization (Weight Decay)&lt;/strong&gt;!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tự-tay-suy-ra-công-thức-mle-cho-10-lần-tung-đồng-xu-và-liên-hệ-cross-entropy&quot;&gt;Giải thích: Tự tay suy ra công thức MLE cho 10 lần tung đồng xu và liên hệ Cross-Entropy&lt;/h3&gt;

&lt;p&gt;Giả sử bạn tung một đồng xu lạ 10 lần và thu được 7 lần Ngửa (\(y=1\)), 3 lần Sấp (\(y=0\)). Ta muốn tìm xác suất ra Ngửa \(p \in (0, 1)\) hợp lý nhất:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lập hàm hợp lý&lt;/strong&gt;:
\(\mathcal{L}(p) = p^7 (1 - p)^3.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lấy Log-Likelihood&lt;/strong&gt;:
\(\ell(p) = \ln \mathcal{L}(p) = 7\ln p + 3\ln(1 - p).\)
(Chú ý rằng \(-\frac{1}{10}\ell(p) = -\big[0.7\ln p + 0.3\ln(1-p)\big]\) chính là &lt;strong&gt;Binary Cross-Entropy&lt;/strong&gt;!)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đạo hàm theo \(p\) và cho bằng 0&lt;/strong&gt;:
\(\frac{d\ell}{dp} = \frac{7}{p} - \frac{3}{1 - p} = 0 \iff 7(1 - p) = 3p \iff 7 = 10p \iff \hat{p}_{\text{MLE}} = 0.7.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng số tại hai điểm&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Tại \(p = 0.7\): \(\ell(0.7) = 7\ln(0.7) + 3\ln(0.3) \approx 7(-0.3567) + 3(-1.2040) = -6.1086\).&lt;/li&gt;
      &lt;li&gt;Tại \(p = 0.5\): \(\ell(0.5) = 10\ln(0.5) \approx -6.9315 &amp;lt; -6.1086\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Kết quả \(\hat{p}_{\text{MLE}} = 0.7\) vừa khớp trực giác tần suất, vừa chứng minh việc tối thiểu hóa Cross-Entropy chính là đi tìm tham số làm dữ liệu huấn luyện có khả năng xảy ra cao nhất!&lt;/p&gt;

&lt;h2 id=&quot;hàm-hợp-lý-likelihood-và-ước-lượng-hợp-lý-cực-đại-mle&quot;&gt;Hàm hợp lý (&lt;em&gt;Likelihood&lt;/em&gt;) và Ước lượng hợp lý cực đại (MLE)&lt;/h2&gt;

&lt;p&gt;Trong xác suất thống kê, &lt;strong&gt;hàm hợp lý&lt;/strong&gt; (&lt;em&gt;likelihood&lt;/em&gt;) đo mức độ phù hợp của một mô hình hoặc một bộ tham số với dữ liệu đã quan sát. Dù được xây dựng từ công thức xác suất, hàm hợp lý không phải là một phân phối xác suất theo tham số, mà là hàm đánh giá xem từng giá trị tham số giải thích dữ liệu quan sát tốt đến mức nào.&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa-hàm-hợp-lý&quot;&gt;Định nghĩa hàm hợp lý&lt;/h3&gt;

&lt;p&gt;Hàm hợp lý của tham số \(\theta\) ứng với dữ liệu quan sát \(x\) được định nghĩa là xác suất (hoặc mật độ xác suất) thu được dữ liệu \(x\) khi giả sử tham số \(\theta\) là đúng, ký hiệu là \(L(\theta \mid x)\):&lt;/p&gt;

\[L(\theta \mid x) = P(x \mid \theta)\]

&lt;p&gt;Trong biểu thức này, dữ liệu \(x\) được giữ cố định, còn \(\theta\) là biến số thay đổi.&lt;/p&gt;

&lt;h3 id=&quot;khác-biệt-giữa-xác-suất-và-hàm-hợp-lý&quot;&gt;Khác biệt giữa xác suất và hàm hợp lý&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất&lt;/strong&gt; cố định tham số đã biết và mô tả khả năng xuất hiện của các kết quả dữ liệu trong tương lai.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hàm hợp lý&lt;/strong&gt; cố định dữ liệu đã quan sát và so sánh mức độ phù hợp giữa các giá trị tham số khác nhau.&lt;/li&gt;
&lt;/ul&gt;

&lt;div style=&quot;background: #fff3cd; padding: 15px; border-left: 4px solid #ffc107; margin: 20px 0;&quot;&gt;
&lt;strong&gt;⚠️ Lưu ý quan trọng:&lt;/strong&gt; Hàm hợp lý không phải là phân phối xác suất của tham số θ, vì tổng hoặc tích phân của nó theo θ không nhất thiết bằng 1.
&lt;/div&gt;

&lt;h3 id=&quot;ví-dụ-minh-họa-tung-đồng-xu&quot;&gt;Ví dụ minh họa: Tung đồng xu&lt;/h3&gt;

&lt;p&gt;Giả sử bạn tung một đồng xu 5 lần và thu được 3 lần mặt sấp (S), 2 lần mặt ngửa (N), và muốn ước lượng xác suất ra mặt sấp \(p\).&lt;/p&gt;

&lt;p&gt;Hàm hợp lý của \(p\) là xác suất quan sát đúng kết quả (3 sấp, 2 ngửa) ứng với tham số \(p\):&lt;/p&gt;

\[L(p \mid \text{dữ liệu}) = P(\text{3 sấp, 2 ngửa} \mid p) = \binom{5}{3} p^3 (1-p)^2\]

&lt;p&gt;trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\binom{5}{3}\) là hệ số nhị thức,&lt;/li&gt;
  &lt;li&gt;\(p^3\) là xác suất cho 3 lần sấp,&lt;/li&gt;
  &lt;li&gt;\((1-p)^2\) là xác suất cho 2 lần ngửa.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Thử tính với hai giá trị của \(p\):&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Với \(p = 0.6\):
\(L(0.6 \mid \text{dữ liệu}) = \binom{5}{3} (0.6)^3 (0.4)^2 = 10 \times 0.216 \times 0.16 = 0.3456\)&lt;/p&gt;

&lt;p&gt;Với \(p = 0.5\):
\(L(0.5 \mid \text{dữ liệu}) = \binom{5}{3} (0.5)^3 (0.5)^2 = 10 \times 0.125 \times 0.25 = 0.3125\)&lt;/p&gt;

&lt;p&gt;Giá trị hàm hợp lý tại \(p = 0.6\) cao hơn tại \(p = 0.5\), cho thấy \(p = 0.6\) giải thích dữ liệu quan sát tốt hơn.&lt;/p&gt;

&lt;h3 id=&quot;minh-họa-tương-tác-tung-đồng-xu&quot;&gt;Minh họa tương tác: Tung đồng xu&lt;/h3&gt;

&lt;div id=&quot;coin-flip-example&quot; style=&quot;border: 1px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 8px;&quot;&gt;
    &lt;h4&gt;Phép thử tung đồng xu&lt;/h4&gt;
    
    &lt;div style=&quot;margin: 15px 0;&quot;&gt;
        &lt;label for=&quot;p-slider&quot;&gt;Xác suất mặt sấp (p): &lt;span id=&quot;p-value&quot;&gt;0.5&lt;/span&gt;&lt;/label&gt;&lt;br /&gt;
        &lt;input type=&quot;range&quot; id=&quot;p-slider&quot; min=&quot;0.01&quot; max=&quot;0.99&quot; step=&quot;0.01&quot; value=&quot;0.5&quot; style=&quot;width: 300px;&quot; /&gt;
    &lt;/div&gt;
    
    &lt;div style=&quot;margin: 15px 0;&quot;&gt;
        &lt;label for=&quot;heads-input&quot;&gt;Số lần sấp: &lt;/label&gt;
        &lt;input type=&quot;number&quot; id=&quot;heads-input&quot; value=&quot;3&quot; min=&quot;0&quot; max=&quot;20&quot; style=&quot;width: 60px;&quot; /&gt;
        
        &lt;label for=&quot;tails-input&quot; style=&quot;margin-left: 20px;&quot;&gt;Số lần ngửa: &lt;/label&gt;
        &lt;input type=&quot;number&quot; id=&quot;tails-input&quot; value=&quot;2&quot; min=&quot;0&quot; max=&quot;20&quot; style=&quot;width: 60px;&quot; /&gt;
    &lt;/div&gt;
    
    &lt;div style=&quot;margin: 15px 0;&quot;&gt;
        &lt;canvas id=&quot;likelihood-plot&quot; width=&quot;600&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc;&quot;&gt;&lt;/canvas&gt;
    &lt;/div&gt;
    
    &lt;div id=&quot;likelihood-result&quot; style=&quot;background: #f8f9fa; padding: 10px; border-radius: 4px; margin: 10px 0;&quot;&gt;
        &lt;strong&gt;Likelihood hiện tại:&lt;/strong&gt; &lt;span id=&quot;current-likelihood&quot;&gt;0.3125&lt;/span&gt;&lt;br /&gt;
        &lt;strong&gt;Log-likelihood:&lt;/strong&gt; &lt;span id=&quot;current-log-likelihood&quot;&gt;-1.16&lt;/span&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    const pSlider = document.getElementById(&apos;p-slider&apos;);
    const pValue = document.getElementById(&apos;p-value&apos;);
    const headsInput = document.getElementById(&apos;heads-input&apos;);
    const tailsInput = document.getElementById(&apos;tails-input&apos;);
    const canvas = document.getElementById(&apos;likelihood-plot&apos;);
    const ctx = canvas.getContext(&apos;2d&apos;);
    const likelihoodResult = document.getElementById(&apos;current-likelihood&apos;);
    const logLikelihoodResult = document.getElementById(&apos;current-log-likelihood&apos;);
    
    function binomialCoeff(n, k) {
        if (k &gt; n) return 0;
        if (k === 0 || k === n) return 1;
        
        let result = 1;
        for (let i = 0; i &lt; k; i++) {
            result = result * (n - i) / (i + 1);
        }
        return result;
    }
    
    function likelihood(p, heads, tails) {
        const n = heads + tails;
        const coeff = binomialCoeff(n, heads);
        return coeff * Math.pow(p, heads) * Math.pow(1 - p, tails);
    }
    
    function logLikelihood(p, heads, tails) {
        const n = heads + tails;
        const logCoeff = Math.log(binomialCoeff(n, heads));
        return logCoeff + heads * Math.log(p) + tails * Math.log(1 - p);
    }
    
    function plotLikelihood() {
        const heads = parseInt(headsInput.value);
        const tails = parseInt(tailsInput.value);
        const currentP = parseFloat(pSlider.value);
        
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // Vẽ trục
        ctx.strokeStyle = &apos;#333&apos;;
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(50, 250);
        ctx.lineTo(550, 250);
        ctx.moveTo(50, 250);
        ctx.lineTo(50, 50);
        ctx.stroke();
        
        // Nhãn trục
        ctx.fillStyle = &apos;#333&apos;;
        ctx.font = &apos;12px Arial&apos;;
        ctx.fillText(&apos;p (xác suất mặt sấp)&apos;, 250, 280);
        ctx.save();
        ctx.translate(20, 150);
        ctx.rotate(-Math.PI/2);
        ctx.fillText(&apos;Likelihood&apos;, 0, 0);
        ctx.restore();
        
        // Vẽ đường likelihood
        ctx.strokeStyle = &apos;#2196F3&apos;;
        ctx.lineWidth = 2;
        ctx.beginPath();
        
        let maxLikelihood = 0;
        const points = [];
        
        for (let i = 0; i &lt;= 500; i++) {
            const p = 0.01 + (i / 500) * 0.98;
            const l = likelihood(p, heads, tails);
            points.push({p: p, l: l});
            maxLikelihood = Math.max(maxLikelihood, l);
        }
        
        for (let i = 0; i &lt; points.length; i++) {
            const x = 50 + (points[i].p - 0.01) / 0.98 * 500;
            const y = 250 - (points[i].l / maxLikelihood) * 200;
            
            if (i === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        }
        ctx.stroke();
        
        // Vẽ điểm hiện tại
        const currentLikelihood = likelihood(currentP, heads, tails);
        const currentX = 50 + (currentP - 0.01) / 0.98 * 500;
        const currentY = 250 - (currentLikelihood / maxLikelihood) * 200;
        
        ctx.fillStyle = &apos;#f44336&apos;;
        ctx.beginPath();
        ctx.arc(currentX, currentY, 5, 0, 2 * Math.PI);
        ctx.fill();
        
        // Cập nhật kết quả
        likelihoodResult.textContent = currentLikelihood.toFixed(6);
        logLikelihoodResult.textContent = logLikelihood(currentP, heads, tails).toFixed(4);
        
        // Vẽ các tick marks
        ctx.fillStyle = &apos;#666&apos;;
        ctx.font = &apos;10px Arial&apos;;
        for (let i = 0; i &lt;= 10; i++) {
            const p = i / 10;
            const x = 50 + (p - 0.01) / 0.98 * 500;
            ctx.fillText(p.toFixed(1), x - 10, 265);
        }
    }
    
    function updateDisplay() {
        pValue.textContent = pSlider.value;
        plotLikelihood();
    }
    
    pSlider.addEventListener(&apos;input&apos;, updateDisplay);
    headsInput.addEventListener(&apos;input&apos;, plotLikelihood);
    tailsInput.addEventListener(&apos;input&apos;, plotLikelihood);
    
    // Khởi tạo
    updateDisplay();
});
&lt;/script&gt;

&lt;h3 id=&quot;ước-lượng-hợp-lý-cực-đại-mle&quot;&gt;Ước lượng hợp lý cực đại (MLE)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ước lượng hợp lý cực đại&lt;/strong&gt; (&lt;em&gt;Maximum Likelihood Estimation — MLE&lt;/em&gt;) là phương pháp chọn giá trị tham số \(\theta\) sao cho hàm hợp lý \(L(\theta \mid x)\) đạt cực đại:&lt;/p&gt;

\[\hat{\theta}_{MLE} = \arg\max_{\theta} L(\theta \mid x)\]

&lt;p&gt;Trong thực tế, vì hàm logarit đơn điệu tăng, ta thường cực đại hóa &lt;strong&gt;log-likelihood&lt;/strong&gt; để chuyển tích thành tổng và giúp việc tính đạo hàm thuận tiện hơn:&lt;/p&gt;

\[\hat{\theta}_{MLE} = \arg\max_{\theta} \log L(\theta \mid x)\]

&lt;h3 id=&quot;ví-dụ-mle-phân-phối-chuẩn&quot;&gt;Ví dụ MLE: Phân phối chuẩn&lt;/h3&gt;

&lt;p&gt;Giả sử ta có \(n\) quan sát độc lập \(x_1, x_2, \ldots, x_n\) lấy từ phân phối chuẩn \(N(\mu, \sigma^2)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hàm hợp lý:&lt;/strong&gt;
\(L(\mu, \sigma^2 \mid x_1, \ldots, x_n) = \prod_{i=1}^{n} \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x_i - \mu)^2}{2\sigma^2}\right)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Log-likelihood:&lt;/strong&gt;
\(\ell(\mu, \sigma^2) = -\frac{n}{2}\log(2\pi) - \frac{n}{2}\log(\sigma^2) - \frac{1}{2\sigma^2}\sum_{i=1}^{n}(x_i - \mu)^2\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tìm ước lượng MLE:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Lấy đạo hàm riêng theo \(\mu\) và cho bằng 0:
\(\frac{\partial \ell}{\partial \mu} = \frac{1}{\sigma^2}\sum_{i=1}^{n}(x_i - \mu) = 0\)&lt;/p&gt;

&lt;p&gt;Giải phương trình trên thu được: \(\hat{\mu}_{MLE} = \frac{1}{n}\sum_{i=1}^{n} x_i = \bar{x}\).&lt;/p&gt;

&lt;p&gt;Làm tương tự với \(\sigma^2\):
\(\hat{\sigma^2}_{MLE} = \frac{1}{n}\sum_{i=1}^{n}(x_i - \bar{x})^2\)&lt;/p&gt;

&lt;h3 id=&quot;minh-họa-tương-tác-mle-cho-phân-phối-chuẩn&quot;&gt;Minh họa tương tác: MLE cho phân phối chuẩn&lt;/h3&gt;

&lt;div id=&quot;normal-mle-example&quot; style=&quot;border: 1px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 8px;&quot;&gt;
    &lt;h4&gt;MLE cho phân phối chuẩn&lt;/h4&gt;
    
    &lt;div style=&quot;margin: 15px 0;&quot;&gt;
        &lt;button id=&quot;generate-data&quot; style=&quot;background: #4CAF50; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer;&quot;&gt;Tạo dữ liệu mới&lt;/button&gt;
        &lt;span style=&quot;margin-left: 20px;&quot;&gt;Số mẫu: &lt;/span&gt;
        &lt;input type=&quot;number&quot; id=&quot;sample-size&quot; value=&quot;50&quot; min=&quot;10&quot; max=&quot;200&quot; style=&quot;width: 60px;&quot; /&gt;
    &lt;/div&gt;
    
    &lt;div style=&quot;margin: 15px 0;&quot;&gt;
        &lt;label for=&quot;mu-guess&quot;&gt;Ước lượng μ: &lt;span id=&quot;mu-guess-value&quot;&gt;0&lt;/span&gt;&lt;/label&gt;&lt;br /&gt;
        &lt;input type=&quot;range&quot; id=&quot;mu-guess&quot; min=&quot;-3&quot; max=&quot;3&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 300px;&quot; /&gt;
    &lt;/div&gt;
    
    &lt;div style=&quot;margin: 15px 0;&quot;&gt;
        &lt;label for=&quot;sigma-guess&quot;&gt;Ước lượng σ: &lt;span id=&quot;sigma-guess-value&quot;&gt;1&lt;/span&gt;&lt;/label&gt;&lt;br /&gt;
        &lt;input type=&quot;range&quot; id=&quot;sigma-guess&quot; min=&quot;0.1&quot; max=&quot;3&quot; step=&quot;0.1&quot; value=&quot;1&quot; style=&quot;width: 300px;&quot; /&gt;
    &lt;/div&gt;
    
    &lt;div style=&quot;margin: 15px 0;&quot;&gt;
        &lt;canvas id=&quot;normal-plot&quot; width=&quot;600&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc;&quot;&gt;&lt;/canvas&gt;
    &lt;/div&gt;
    
    &lt;div id=&quot;mle-results&quot; style=&quot;background: #f8f9fa; padding: 10px; border-radius: 4px; margin: 10px 0;&quot;&gt;
        &lt;div&gt;&lt;strong&gt;Dữ liệu thực:&lt;/strong&gt; μ = &lt;span id=&quot;true-mu&quot;&gt;1.0&lt;/span&gt;, σ = &lt;span id=&quot;true-sigma&quot;&gt;1.5&lt;/span&gt;&lt;/div&gt;
        &lt;div&gt;&lt;strong&gt;MLE ước lượng:&lt;/strong&gt; μ̂ = &lt;span id=&quot;mle-mu&quot;&gt;0.95&lt;/span&gt;, σ̂ = &lt;span id=&quot;mle-sigma&quot;&gt;1.48&lt;/span&gt;&lt;/div&gt;
        &lt;div&gt;&lt;strong&gt;Ước lượng hiện tại:&lt;/strong&gt; μ = &lt;span id=&quot;current-mu&quot;&gt;0&lt;/span&gt;, σ = &lt;span id=&quot;current-sigma&quot;&gt;1&lt;/span&gt;&lt;/div&gt;
        &lt;div&gt;&lt;strong&gt;Log-likelihood hiện tại:&lt;/strong&gt; &lt;span id=&quot;current-ll&quot;&gt;-75.2&lt;/span&gt;&lt;/div&gt;
        &lt;div&gt;&lt;strong&gt;Log-likelihood cực đại:&lt;/strong&gt; &lt;span id=&quot;max-ll&quot;&gt;-72.1&lt;/span&gt;&lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    const generateBtn = document.getElementById(&apos;generate-data&apos;);
    const sampleSizeInput = document.getElementById(&apos;sample-size&apos;);
    const muGuess = document.getElementById(&apos;mu-guess&apos;);
    const sigmaGuess = document.getElementById(&apos;sigma-guess&apos;);
    const muGuessValue = document.getElementById(&apos;mu-guess-value&apos;);
    const sigmaGuessValue = document.getElementById(&apos;sigma-guess-value&apos;);
    const canvas = document.getElementById(&apos;normal-plot&apos;);
    const ctx = canvas.getContext(&apos;2d&apos;);
    
    let data = [];
    let trueMu = 1.0;
    let trueSigma = 1.5;
    
    function normalRandom(mu, sigma) {
        let u = 0, v = 0;
        while(u === 0) u = Math.random();
        while(v === 0) v = Math.random();
        return Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v) * sigma + mu;
    }
    
    function generateData() {
        const n = parseInt(sampleSizeInput.value);
        trueMu = (Math.random() - 0.5) * 4; // -2 to 2
        trueSigma = 0.5 + Math.random() * 2; // 0.5 to 2.5
        
        data = [];
        for (let i = 0; i &lt; n; i++) {
            data.push(normalRandom(trueMu, trueSigma));
        }
        
        // Tính MLE
        const mleMu = data.reduce((sum, x) =&gt; sum + x, 0) / data.length;
        const mleSigma = Math.sqrt(data.reduce((sum, x) =&gt; sum + (x - mleMu) ** 2, 0) / data.length);
        
        document.getElementById(&apos;true-mu&apos;).textContent = trueMu.toFixed(2);
        document.getElementById(&apos;true-sigma&apos;).textContent = trueSigma.toFixed(2);
        document.getElementById(&apos;mle-mu&apos;).textContent = mleMu.toFixed(2);
        document.getElementById(&apos;mle-sigma&apos;).textContent = mleSigma.toFixed(2);
        
        plotData();
    }
    
    function logLikelihood(mu, sigma, data) {
        const n = data.length;
        const sumSquares = data.reduce((sum, x) =&gt; sum + (x - mu) ** 2, 0);
        return -n/2 * Math.log(2 * Math.PI) - n * Math.log(sigma) - sumSquares / (2 * sigma ** 2);
    }
    
    function normalPDF(x, mu, sigma) {
        return (1 / (sigma * Math.sqrt(2 * Math.PI))) * Math.exp(-0.5 * ((x - mu) / sigma) ** 2);
    }
    
    function plotData() {
        if (data.length === 0) return;
        
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        const currentMu = parseFloat(muGuess.value);
        const currentSigma = parseFloat(sigmaGuess.value);
        
        // Tìm phạm vi dữ liệu
        const minX = Math.min(...data) - 1;
        const maxX = Math.max(...data) + 1;
        const range = maxX - minX;
        
        // Vẽ histogram
        const bins = 20;
        const binWidth = range / bins;
        const binCounts = new Array(bins).fill(0);
        
        data.forEach(x =&gt; {
            const binIndex = Math.floor((x - minX) / binWidth);
            if (binIndex &gt;= 0 &amp;&amp; binIndex &lt; bins) {
                binCounts[binIndex]++;
            }
        });
        
        const maxCount = Math.max(...binCounts);
        
        ctx.fillStyle = &apos;rgba(33, 150, 243, 0.3)&apos;;
        for (let i = 0; i &lt; bins; i++) {
            const x = 50 + (i * binWidth / range) * 500;
            const height = (binCounts[i] / maxCount) * 200;
            const width = (binWidth / range) * 500;
            ctx.fillRect(x, 250 - height, width, height);
        }
        
        // Vẽ đường phân phối thực
        ctx.strokeStyle = &apos;#4CAF50&apos;;
        ctx.lineWidth = 2;
        ctx.beginPath();
        for (let i = 0; i &lt;= 500; i++) {
            const x = minX + (i / 500) * range;
            const y = normalPDF(x, trueMu, trueSigma);
            const plotX = 50 + (i / 500) * 500;
            const plotY = 250 - (y / (1 / (trueSigma * Math.sqrt(2 * Math.PI)))) * 200;
            
            if (i === 0) ctx.moveTo(plotX, plotY);
            else ctx.lineTo(plotX, plotY);
        }
        ctx.stroke();
        
        // Vẽ đường ước lượng hiện tại
        ctx.strokeStyle = &apos;#f44336&apos;;
        ctx.lineWidth = 2;
        ctx.setLineDash([5, 5]);
        ctx.beginPath();
        for (let i = 0; i &lt;= 500; i++) {
            const x = minX + (i / 500) * range;
            const y = normalPDF(x, currentMu, currentSigma);
            const plotX = 50 + (i / 500) * 500;
            const plotY = 250 - (y / (1 / (currentSigma * Math.sqrt(2 * Math.PI)))) * 200;
            
            if (i === 0) ctx.moveTo(plotX, plotY);
            else ctx.lineTo(plotX, plotY);
        }
        ctx.stroke();
        ctx.setLineDash([]);
        
        // Vẽ trục
        ctx.strokeStyle = &apos;#333&apos;;
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(50, 250);
        ctx.lineTo(550, 250);
        ctx.stroke();
        
        // Cập nhật kết quả
        const currentLL = logLikelihood(currentMu, currentSigma, data);
        const mleMu = data.reduce((sum, x) =&gt; sum + x, 0) / data.length;
        const mleSigma = Math.sqrt(data.reduce((sum, x) =&gt; sum + (x - mleMu) ** 2, 0) / data.length);
        const maxLL = logLikelihood(mleMu, mleSigma, data);
        
        document.getElementById(&apos;current-mu&apos;).textContent = currentMu.toFixed(2);
        document.getElementById(&apos;current-sigma&apos;).textContent = currentSigma.toFixed(2);
        document.getElementById(&apos;current-ll&apos;).textContent = currentLL.toFixed(2);
        document.getElementById(&apos;max-ll&apos;).textContent = maxLL.toFixed(2);
        
        // Thêm chú thích
        ctx.fillStyle = &apos;#4CAF50&apos;;
        ctx.fillRect(450, 60, 15, 3);
        ctx.fillStyle = &apos;#333&apos;;
        ctx.font = &apos;12px Arial&apos;;
        ctx.fillText(&apos;Phân phối thực&apos;, 470, 65);
        
        ctx.strokeStyle = &apos;#f44336&apos;;
        ctx.setLineDash([5, 5]);
        ctx.beginPath();
        ctx.moveTo(450, 80);
        ctx.lineTo(465, 80);
        ctx.stroke();
        ctx.setLineDash([]);
        ctx.fillText(&apos;Ước lượng hiện tại&apos;, 470, 85);
    }
    
    function updateDisplay() {
        muGuessValue.textContent = muGuess.value;
        sigmaGuessValue.textContent = sigmaGuess.value;
        plotData();
    }
    
    generateBtn.addEventListener(&apos;click&apos;, generateData);
    muGuess.addEventListener(&apos;input&apos;, updateDisplay);
    sigmaGuess.addEventListener(&apos;input&apos;, updateDisplay);
    sampleSizeInput.addEventListener(&apos;change&apos;, generateData);
    
    // Khởi tạo
    generateData();
});
&lt;/script&gt;

&lt;h3 id=&quot;các-tính-chất-của-mle&quot;&gt;Các tính chất của MLE&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính nhất quán (&lt;em&gt;Consistency&lt;/em&gt;):&lt;/strong&gt; khi kích thước mẫu tăng lên vô hạn, ước lượng MLE hội tụ về giá trị đúng của tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính chuẩn tiệm cận (&lt;em&gt;Asymptotic Normality&lt;/em&gt;):&lt;/strong&gt; với kích thước mẫu đủ lớn, phân phối của ước lượng MLE xấp xỉ phân phối chuẩn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính hiệu quả tiệm cận (&lt;em&gt;Asymptotic Efficiency&lt;/em&gt;):&lt;/strong&gt; MLE tiệm cận cận dưới Cramér–Rao, tức đạt phương sai nhỏ nhất trong lớp các ước lượng không chệch.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính bất biến (&lt;em&gt;Invariance&lt;/em&gt;):&lt;/strong&gt; nếu \(\hat{\theta}\) là MLE của \(\theta\), thì \(g(\hat{\theta})\) là MLE của \(g(\theta)\) với mọi hàm \(g\) khả nghịch.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ứng-dụng-của-mle&quot;&gt;Ứng dụng của MLE&lt;/h3&gt;

&lt;h4 id=&quot;1-ước-lượng-tham-số&quot;&gt;1. Ước lượng tham số&lt;/h4&gt;

&lt;p&gt;MLE được dùng phổ biến để ước lượng tham số cho các mô hình thống kê:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Phân phối chuẩn: ước lượng kỳ vọng và phương sai.&lt;/li&gt;
  &lt;li&gt;Phân phối Poisson: ước lượng tham số tốc độ \(\lambda\).&lt;/li&gt;
  &lt;li&gt;Hồi quy tuyến tính: ước lượng hệ số hồi quy.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;2-so-sánh-mô-hình&quot;&gt;2. So sánh mô hình&lt;/h4&gt;

&lt;p&gt;Hàm hợp lý là cơ sở của nhiều tiêu chí đánh giá và so sánh mô hình:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm định tỉ số hợp lý (&lt;em&gt;Likelihood Ratio Test&lt;/em&gt;):&lt;/strong&gt; so sánh hai mô hình lồng nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;AIC / BIC:&lt;/strong&gt; các tiêu chí lựa chọn mô hình dựa trên log-likelihood và số lượng tham số.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;3-thống-kê-bayes&quot;&gt;3. Thống kê Bayes&lt;/h4&gt;

&lt;p&gt;Trong suy luận Bayes, hàm hợp lý kết hợp với phân phối tiên nghiệm (&lt;em&gt;prior&lt;/em&gt;) để tạo thành phân phối hậu nghiệm (&lt;em&gt;posterior&lt;/em&gt;):&lt;/p&gt;

\[P(\theta \mid x) \propto L(\theta \mid x) \cdot P(\theta)\]

&lt;h3 id=&quot;liên-hệ-với-tối-ưu-hóa&quot;&gt;Liên hệ với tối ưu hóa&lt;/h3&gt;

&lt;p&gt;MLE phát biểu trực tiếp dưới dạng một bài toán tối ưu hóa:&lt;/p&gt;

\[\max_{\theta} L(\theta \mid x) \quad \text{hoặc} \quad \max_{\theta} \log L(\theta \mid x)\]

&lt;p&gt;Bài toán này thường rơi vào các lớp sau:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tối ưu hóa không ràng buộc:&lt;/strong&gt; khi tham số không chịu điều kiện phụ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tối ưu hóa có ràng buộc:&lt;/strong&gt; khi tham số phải thỏa mãn các miền điều kiện nhất định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài toán lồi:&lt;/strong&gt; nhiều hàm log-likelihood là hàm lõm (tương đương âm log-likelihood là hàm lồi), bảo đảm nghiệm tối ưu tìm được là tối ưu toàn cục.&lt;/li&gt;
&lt;/ul&gt;

&lt;div style=&quot;background: #e8f4fd; padding: 15px; border-left: 4px solid #2196F3; margin: 20px 0;&quot;&gt;
&lt;strong&gt;💡 Liên hệ với tối ưu hóa lồi:&lt;/strong&gt; Nhiều bài toán MLE dẫn đến bài toán tối ưu hóa lồi, đặc biệt trong họ phân phối mũ. Nhờ đó, cực trị tìm được là tối ưu toàn cục và các thuật toán tối ưu hội tụ đáng tin cậy hơn.
&lt;/div&gt;

&lt;h3 id=&quot;ví-dụ-thực-tế-hồi-quy-logistic&quot;&gt;Ví dụ thực tế: Hồi quy logistic&lt;/h3&gt;

&lt;p&gt;Trong hồi quy logistic, xác suất của biến nhị phân được mô hình hóa như sau:&lt;/p&gt;

\[P(y = 1 \mid x) = \frac{1}{1 + e^{-(\beta_0 + \beta_1 x)}}\]

&lt;p&gt;&lt;strong&gt;Log-likelihood:&lt;/strong&gt;
\(\ell(\beta_0, \beta_1) = \sum_{i=1}^{n} \left[ y_i \log(p_i) + (1-y_i) \log(1-p_i) \right]\)&lt;/p&gt;

&lt;p&gt;Đây là bài toán tối ưu hóa lồi (cực đại hóa hàm lõm theo \(\beta_0, \beta_1\)), có thể giải bằng gradient descent hoặc phương pháp Newton.&lt;/p&gt;

&lt;h3 id=&quot;tóm-tắt&quot;&gt;Tóm tắt&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hàm hợp lý (&lt;em&gt;likelihood&lt;/em&gt;)&lt;/strong&gt; đo mức độ phù hợp của tham số với dữ liệu quan sát.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;MLE&lt;/strong&gt; tìm tham số cực đại hóa hàm hợp lý (hoặc log-likelihood).&lt;/li&gt;
  &lt;li&gt;MLE có các tính chất thống kê tốt: nhất quán, hiệu quả tiệm cận và chuẩn tiệm cận.&lt;/li&gt;
  &lt;li&gt;MLE dẫn trực tiếp đến các bài toán tối ưu hóa, trong đó nhiều bài toán thuộc lớp tối ưu lồi.&lt;/li&gt;
  &lt;li&gt;Phương pháp này được ứng dụng rộng rãi trong thống kê, học máy và khoa học dữ liệu.&lt;/li&gt;
&lt;/ul&gt;

&lt;div style=&quot;background: #d4edda; padding: 15px; border-left: 4px solid #28a745; margin: 20px 0;&quot;&gt;
&lt;strong&gt;🎯 Điểm quan trọng:&lt;/strong&gt; MLE là cầu nối trực tiếp giữa thống kê và tối ưu hóa, giúp ta hiểu cách ước lượng tham số mô hình thông qua các phương pháp tối ưu — đặc biệt là tối ưu hóa lồi.
&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pYxNSUDSFH4&quot;&gt;In Statistics, Probability is not Likelihood.&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Làm rõ vì sao hàm hợp lý không phải là phân phối xác suất của tham số, đúng với cảnh báo ở đầu bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=XepXtl9YKwc&quot;&gt;Maximum Likelihood, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích trực quan ước lượng hợp lý cực đại (argmax của hàm hợp lý), đồng bộ với ví dụ tung đồng xu trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=4KKV9yZCoM4&quot;&gt;Maximum Likelihood for the Binomial Distribution, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Trình bày từng bước tính hàm hợp lý nhị thức, tương ứng trực tiếp với ví dụ tung đồng xu 5 lần.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-02 Các Phân Phối Xác Suất Thông Dụng</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_02_Common_Probability_Distributions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_02_Common_Probability_Distributions</id>
   <content type="html">&lt;p&gt;Trong tự nhiên và dữ liệu số, sự ngẫu nhiên không hề hỗn loạn vô định—chúng thường lặp lại theo một số ít “khuôn mẫu toán học” kinh điển gọi là các &lt;strong&gt;phân phối xác suất&lt;/strong&gt;. Việc nhận diện đúng bài toán của bạn thuộc khuôn mẫu nào (nhị phân Bernoulli, đếm sự kiện Poisson, đo lường liên tục Gaussian hay vector tương quan Multivariate Normal) quyết định trực tiếp việc chọn hàm kích hoạt đầu ra, hàm mất mát và kiến trúc mô hình sinh. Bài tổng quan này phác thảo bản đồ ba nhóm phân phối bạn sẽ gặp đi gặp lại xuyên suốt khóa học.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-họ-phân-phối-xác-suất-thiết-yếu-trong-học-sâu&quot;&gt;Kiến thức cần nhớ: Ba họ Phân phối Xác suất thiết yếu trong Học sâu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Họ phân phối Rời rạc (Bernoulli, Binomial, Categorical, Poisson)&lt;/strong&gt;:
Mô hình hóa nhãn lớp, token ngôn ngữ, mặt nạ Dropout (Bernoulli) và số lần xuất hiện sự kiện; trực tiếp sinh ra Binary Cross-Entropy và Categorical Cross-Entropy.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Họ phân phối Liên tục một biến (Uniform, Normal/Gaussian, Exponential)&lt;/strong&gt;:
Cơ sở cho khởi tạo trọng số (Uniform/Normal), mô hình hóa nhiễu đo lường trong bài toán hồi quy (Gaussian \(\to\) MSE), và lấy mẫu bước thời gian/nhiễu trong Diffusion Models.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân phối Đa biến (Multivariate Normal &amp;amp; Covariance Matrix)&lt;/strong&gt;:
Nắm bắt mối tương quan đồng thời giữa nhiều đặc trưng, làm nền cho không gian ẩn (&lt;em&gt;latent space&lt;/em&gt;) của Variational Autoencoder (VAE), Gaussian Mixture Models và phép làm trắng dữ liệu (&lt;em&gt;whitening&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-ánh-xạ-nhanh-4-bài-toán-deep-learning-sang-đúng-phân-phối-và-hàm-mất-mát&quot;&gt;Giải thích: Ánh xạ nhanh 4 bài toán Deep Learning sang đúng phân phối và hàm mất mát&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Bài toán Deep Learning&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Đầu ra cần dự đoán&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Phân phối xác suất phù hợp&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Hàm kích hoạt cuối &amp;amp; Loss tương ứng&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Lọc email rác&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Nhãn \(y \in \{0, 1\}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Bernoulli\((p)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Sigmoid + Binary Cross-Entropy&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Nhận diện 10 chữ số MNIST&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Nhãn \(y \in \{0,\dots,9\}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Categorical\((\mathbf{p})\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Softmax + Categorical Cross-Entropy&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Dự báo giá nhà&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Số thực \(y \in \mathbb{R}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Gaussian\((\mu, \sigma^2)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Linear + MSE (Mean Squared Error)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Sinh ảnh bằng VAE&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Vector ẩn \(\mathbf{z} \in \mathbb{R}^d\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;Multivariate Normal\((\boldsymbol{\mu}, \text{diag}(\boldsymbol{\sigma}^2))\)&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;KL-Divergence + Reconstruction Loss&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Mỗi khi thiết kế một mạng nơ-ron mới, hãy tự hỏi: &lt;em&gt;“Dữ liệu đầu ra của mình sinh ra từ phân phối nào?”&lt;/em&gt;—câu trả lời sẽ tự động chỉ ra kiến trúc tầng cuối và hàm mất mát chuẩn xác nhất.&lt;/p&gt;

&lt;p&gt;Bài học này khảo sát các phân phối xác suất thường dùng trong học sâu, chia thành ba phần:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối rời rạc&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối liên tục&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối đa biến và ứng dụng&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=oI3hZJqXJuc&quot;&gt;The Main Ideas behind Probability Distributions&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giới thiệu khái niệm phân phối xác suất trước khi đi vào các nhóm phân phối rời rạc, liên tục và đa biến.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NbzVwvE_syQ&quot;&gt;MaDL - Common Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Điểm qua các họ phân phối thông dụng sẽ được trình bày chi tiết trong từng bài sau.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=rzFX5NWojp0&quot;&gt;The Normal Distribution, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích phân phối chuẩn (Gauss) — phân phối liên tục xuất hiện xuyên suốt các bài tiếp theo.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-02-03 Phân Phối Đa Biến và Ứng Dụng</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_02_03_Multivariate_and_DL_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_02_03_Multivariate_and_DL_Applications</id>
   <content type="html">&lt;p&gt;Trong dữ liệu thực tế, các đặc trưng hiếm khi “mạnh ai nấy chạy”: chiều cao thường đi đôi với cân nặng, độ sáng của hai điểm ảnh cạnh nhau gần như giống hệt nhau, và các chiều của vector embedding ngôn ngữ tương tác chặt chẽ với nhau. Để mô tả trọn vẹn thế giới đa chiều ấy, ta cần &lt;strong&gt;phân phối chuẩn đa biến&lt;/strong&gt; (&lt;em&gt;Multivariate Normal&lt;/em&gt;) với &lt;strong&gt;ma trận hiệp phương sai&lt;/strong&gt; \(\boldsymbol{\Sigma}\)—chìa khóa toán học đứng sau cả phép làm trắng dữ liệu (&lt;em&gt;PCA Whitening&lt;/em&gt;), khoảng cách Mahalanobis, lẫn thủ thuật tái tham số hóa (&lt;em&gt;reparameterization trick&lt;/em&gt;) của Variational Autoencoder (VAE).&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-phân-phối-đa-biến-trong-học-sâu&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Phân phối Đa biến trong Học sâu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vector kỳ vọng (\(\boldsymbol{\mu}\)) và Ma trận Hiệp phương sai (\(\boldsymbol{\Sigma}\))&lt;/strong&gt;:
Đường chéo chính của \(\boldsymbol{\Sigma}\) chứa phương sai từng chiều; các phần tử ngoài đường chéo \(\Sigma_{ij} = \text{Cov}(X_i, X_j)\) đo mức độ hai đặc trưng biến thiên cùng chiều hay ngược chiều.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hình học đường đồng mức Elip và Khoảng cách Mahalanobis&lt;/strong&gt;:
Số mũ \(-\frac{1}{2}(\mathbf{x}-\boldsymbol{\mu})^\top \boldsymbol{\Sigma}^{-1} (\mathbf{x}-\boldsymbol{\mu})\) đo khoảng cách có tính đến độ co giãn và độ nghiêng của đám mây dữ liệu, giúp phát hiện điểm bất thường (&lt;em&gt;anomaly detection&lt;/em&gt;) chuẩn xác hơn nhiều so với khoảng cách Euclid.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Thủ thuật Tái tham số hóa (Reparameterization Trick trong VAE)&lt;/strong&gt;:
Chuyển việc lấy mẫu ngẫu nhiên \(\mathbf{z} \sim \mathcal{N}(\boldsymbol{\mu}, \text{diag}(\boldsymbol{\sigma}^2))\) thành \(\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\varepsilon}\) với \(\boldsymbol{\varepsilon} \sim \mathcal{N}(\mathbf{0}, \mathbf{I})\), giúp đạo hàm lan truyền ngược mượt mà qua \(\boldsymbol{\mu}\) và \(\boldsymbol{\sigma}\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân phối Biên và Phân phối Có điều kiện&lt;/strong&gt;:
Một tính chất đẹp hiếm có của Gaussian đa biến là mọi phép chiếu biên và mọi phân phối có điều kiện của nó đều vẫn là Gaussian—nền tảng của Gaussian Processes và bộ lọc Kalman.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-khoảng-cách-mahalanobis-và-kiểm-tra-bước-tái-tham-số-hóa-vae&quot;&gt;Giải thích: Tính tay khoảng cách Mahalanobis và kiểm tra bước tái tham số hóa VAE&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Khoảng cách Mahalanobis vs. Euclid:&lt;/strong&gt;
Xét phân phối chuẩn 2D có \(\boldsymbol{\mu} = \begin{bmatrix} 0 \\ 0 \end{bmatrix}\) và ma trận hiệp phương sai chéo \(\boldsymbol{\Sigma} = \begin{bmatrix} 4 &amp;amp; 0 \\ 0 &amp;amp; 0.25 \end{bmatrix}\) (chiều \(x_1\) trải rộng với \(\sigma_1 = 2\), chiều \(x_2\) hẹp với \(\sigma_2 = 0.5\)), suy ra \(\boldsymbol{\Sigma}^{-1} = \begin{bmatrix} 0.25 &amp;amp; 0 \\ 0 &amp;amp; 4 \end{bmatrix}\).
So sánh hai điểm có &lt;strong&gt;cùng khoảng cách Euclid bằng 1&lt;/strong&gt; tới gốc tọa độ: \(\mathbf{a} = (1, 0)\) và \(\mathbf{b} = (0, 1)\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Với \(\mathbf{a} = (1, 0)\): \(d_M^2(\mathbf{a}) = 1^2(0.25) + 0^2(4) = 0.25 \implies d_M(\mathbf{a}) = 0.5\) (chỉ lệch \(0.5\sigma_1\), rất bình thường).&lt;/li&gt;
  &lt;li&gt;Với \(\mathbf{b} = (0, 1)\): \(d_M^2(\mathbf{b}) = 0^2(0.25) + 1^2(4) = 4.00 \implies d_M(\mathbf{b}) = 2.0\) (lệch tới \(2\sigma_2\), hiếm hơn hẳn!).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Phần B — Tính tay 1 mẫu ẩn VAE:&lt;/strong&gt;
Encoder xuất ra \(\boldsymbol{\mu} = (1.5, -0.5)\) và \(\boldsymbol{\sigma} = (0.4, 0.2)\). Rút nhiễu chuẩn \(\boldsymbol{\varepsilon} = (0.5, -1.0)\):
\(\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\varepsilon} = (1.5 + 0.4 \times 0.5,\; -0.5 + 0.2 \times (-1.0)) = (1.7,\; -0.7).\)
Ta thấy ngay \(\frac{\partial z_1}{\partial \mu_1} = 1\) và \(\frac{\partial z_1}{\partial \sigma_1} = \varepsilon_1 = 0.5\)—hoàn toàn khả vi để chạy backpropagation!&lt;/p&gt;

&lt;h3 id=&quot;3-phân-phối-đa-biến&quot;&gt;3. Phân phối đa biến&lt;/h3&gt;

&lt;h4 id=&quot;phân-phối-chuẩn-đa-biến-multivariate-normal&quot;&gt;Phân phối chuẩn đa biến (&lt;em&gt;Multivariate Normal&lt;/em&gt;)&lt;/h4&gt;

&lt;p&gt;Phân phối chuẩn đa biến là sự mở rộng của phân phối chuẩn sang không gian nhiều chiều.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tham số:&lt;/strong&gt; vector kỳ vọng \(\boldsymbol{\mu} \in \mathbb{R}^d\) và ma trận hiệp phương sai xác định dương \(\boldsymbol{\Sigma} \in \mathbb{R}^{d \times d}\).&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;PDF:&lt;/strong&gt; $$f(\mathbf{x}) = \frac{1}{(2\pi)^{d/2}&lt;/td&gt;
      &lt;td&gt;\boldsymbol{\Sigma}&lt;/td&gt;
      &lt;td&gt;^{1/2}} \exp\left(-\frac{1}{2}(\mathbf{x}-\boldsymbol{\mu})^T\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu})\right)$$&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mọi phân phối biên đều là phân phối chuẩn.&lt;/li&gt;
  &lt;li&gt;Mọi tổ hợp tuyến tính của các thành phần đều tuân theo phân phối chuẩn.&lt;/li&gt;
  &lt;li&gt;Mọi phân phối có điều kiện đều là phân phối chuẩn.&lt;/li&gt;
&lt;/ul&gt;

&lt;div id=&quot;multivariate-demo&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f0f8ff;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Phân phối chuẩn đa biến&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;multivariateCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;Trực quan hóa 2D:&lt;/strong&gt; Đồ thị đường đồng mức của phân phối chuẩn hai biến; các mẫu sinh ra hiển thị dưới dạng chấm.
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Tham số&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;mu1-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;μ₁: &lt;span id=&quot;mu1-value&quot;&gt;0.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;mu1-slider&quot; min=&quot;-2&quot; max=&quot;2&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;mu2-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;μ₂: &lt;span id=&quot;mu2-value&quot;&gt;0.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;mu2-slider&quot; min=&quot;-2&quot; max=&quot;2&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;sigma1-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;σ₁: &lt;span id=&quot;sigma1-value&quot;&gt;1.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;sigma1-slider&quot; min=&quot;0.5&quot; max=&quot;2&quot; step=&quot;0.1&quot; value=&quot;1.0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;sigma2-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;σ₂: &lt;span id=&quot;sigma2-value&quot;&gt;1.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;sigma2-slider&quot; min=&quot;0.5&quot; max=&quot;2&quot; step=&quot;0.1&quot; value=&quot;1.0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;rho-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;ρ (tương quan): &lt;span id=&quot;rho-value&quot;&gt;0.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;rho-slider&quot; min=&quot;-0.9&quot; max=&quot;0.9&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;button id=&quot;generate-samples&quot; style=&quot;width: 100%; padding: 10px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer; margin-bottom: 15px;&quot;&gt;Tạo mẫu&lt;/button&gt;
                
                &lt;div id=&quot;multivariate-stats&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Ma trận hiệp phương sai:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;Σ₁₁: &lt;span id=&quot;cov11&quot;&gt;1.000&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Σ₁₂: &lt;span id=&quot;cov12&quot;&gt;0.000&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Σ₂₂: &lt;span id=&quot;cov22&quot;&gt;1.000&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Det(Σ): &lt;span id=&quot;det-cov&quot;&gt;1.000&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;4-ứng-dụng-trong-tối-ưu-hóa&quot;&gt;4. Ứng dụng trong tối ưu hóa&lt;/h3&gt;

&lt;h4 id=&quot;ước-lượng-hợp-lý-cực-đại-mle&quot;&gt;Ước lượng hợp lý cực đại (MLE)&lt;/h4&gt;
&lt;p&gt;Nhiều bài toán tối ưu hóa tìm tham số cực đại hóa hàm hợp lý của dữ liệu quan sát theo một phân phối giả định:&lt;/p&gt;

\[\hat{\theta} = \arg\max_\theta \prod_{i=1}^n f(x_i; \theta)\]

&lt;h4 id=&quot;tối-ưu-hóa-bayes&quot;&gt;Tối ưu hóa Bayes&lt;/h4&gt;
&lt;p&gt;Phân phối tiên nghiệm (&lt;em&gt;prior&lt;/em&gt;) biểu diễn niềm tin ban đầu về tham số trước khi quan sát dữ liệu:&lt;/p&gt;

\[p(\theta|dữ\ liệu) \propto p(dữ\ liệu|\theta) \cdot p(\theta)\]

&lt;h4 id=&quot;điều-chuẩn-regularization&quot;&gt;Điều chuẩn (&lt;em&gt;Regularization&lt;/em&gt;)&lt;/h4&gt;
&lt;p&gt;Các phân phối xác suất có thể đóng vai trò phân phối tiên nghiệm để điều chuẩn bài toán tối ưu:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Điều chuẩn \(L_2\) ↔ phân phối tiên nghiệm Gauss (&lt;em&gt;Gaussian prior&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Điều chuẩn \(L_1\) ↔ phân phối tiên nghiệm Laplace (&lt;em&gt;Laplace prior&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;tối-ưu-hóa-ngẫu-nhiên&quot;&gt;Tối ưu hóa ngẫu nhiên&lt;/h4&gt;
&lt;p&gt;Phân phối xác suất dùng để mô hình hóa nhiễu và yếu tố bất định trong hàm mục tiêu cũng như ràng buộc.&lt;/p&gt;

&lt;h3 id=&quot;điểm-cần-ghi-nhớ-cho-tối-ưu-hóa&quot;&gt;Điểm cần ghi nhớ cho tối ưu hóa&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lựa chọn mô hình:&lt;/strong&gt; chọn phân phối phù hợp với đặc tính thực tế của dữ liệu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ước lượng tham số:&lt;/strong&gt; dùng MLE hoặc suy luận Bayes để ước lượng tham số phân phối.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Định lượng bất định:&lt;/strong&gt; phân phối xác suất cung cấp ngôn ngữ chuẩn để đo lường sự bất định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điều chuẩn:&lt;/strong&gt; phân phối tiên nghiệm giúp hạn chế quá khớp (&lt;em&gt;overfitting&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hiệu quả tính toán:&lt;/strong&gt; nhiều phân phối quen thuộc có biểu thức nghiệm dạng đóng (&lt;em&gt;closed-form&lt;/em&gt;) cho các phép tính thông dụng.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Hiểu rõ các phân phối đa biến và tính chất của chúng giúp ta mô hình hóa và giải hiệu quả nhiều bài toán tối ưu trong học máy, thống kê và kỹ thuật.&lt;/p&gt;

&lt;script&gt;
class MultivariateDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;multivariateCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.params = { mu1: 0, mu2: 0, sigma1: 1, sigma2: 1, rho: 0 };
        this.samples = [];
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const sliders = [&apos;mu1&apos;, &apos;mu2&apos;, &apos;sigma1&apos;, &apos;sigma2&apos;, &apos;rho&apos;];
        
        sliders.forEach(slider =&gt; {
            const element = document.getElementById(slider + &apos;-slider&apos;);
            element.addEventListener(&apos;input&apos;, (e) =&gt; {
                this.params[slider] = parseFloat(e.target.value);
                document.getElementById(slider + &apos;-value&apos;).textContent = this.params[slider].toFixed(1);
                this.updateStats();
                this.draw();
            });
        });
        
        document.getElementById(&apos;generate-samples&apos;).addEventListener(&apos;click&apos;, () =&gt; {
            this.generateSamples();
            this.draw();
        });
        
        this.updateStats();
    }
    
    updateStats() {
        const cov11 = this.params.sigma1 * this.params.sigma1;
        const cov12 = this.params.rho * this.params.sigma1 * this.params.sigma2;
        const cov22 = this.params.sigma2 * this.params.sigma2;
        const det = cov11 * cov22 - cov12 * cov12;
        
        document.getElementById(&apos;cov11&apos;).textContent = cov11.toFixed(3);
        document.getElementById(&apos;cov12&apos;).textContent = cov12.toFixed(3);
        document.getElementById(&apos;cov22&apos;).textContent = cov22.toFixed(3);
        document.getElementById(&apos;det-cov&apos;).textContent = det.toFixed(3);
    }
    
    generateSamples() {
        this.samples = [];
        const n = 100;
        
        for (let i = 0; i &lt; n; i++) {
            // Box-Muller transform
            const u1 = Math.random();
            const u2 = Math.random();
            const z1 = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
            const z2 = Math.sqrt(-2 * Math.log(u1)) * Math.sin(2 * Math.PI * u2);
            
            // Transform to correlated normal
            const x1 = this.params.mu1 + this.params.sigma1 * z1;
            const x2 = this.params.mu2 + this.params.sigma2 * (this.params.rho * z1 + Math.sqrt(1 - this.params.rho * this.params.rho) * z2);
            
            this.samples.push([x1, x2]);
        }
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        const marginX = 50;
        const marginY = 50;
        const plotWidth = this.width - 2 * marginX;
        const plotHeight = this.height - 2 * marginY;
        
        // Draw axes
        this.ctx.strokeStyle = &apos;#ddd&apos;;
        this.ctx.lineWidth = 1;
        this.ctx.beginPath();
        this.ctx.moveTo(marginX, this.height - marginY);
        this.ctx.lineTo(this.width - marginX, this.height - marginY);
        this.ctx.moveTo(marginX, marginY);
        this.ctx.lineTo(marginX, this.height - marginY);
        this.ctx.stroke();
        
        // Draw contour ellipses
        const levels = [0.5, 1, 1.5, 2];
        const colors = [&apos;#ff9999&apos;, &apos;#ff6666&apos;, &apos;#ff3333&apos;, &apos;#ff0000&apos;];
        
        levels.forEach((level, idx) =&gt; {
            this.ctx.strokeStyle = colors[idx];
            this.ctx.lineWidth = 1;
            this.ctx.beginPath();
            
            const a = level * this.params.sigma1;
            const b = level * this.params.sigma2;
            const angle = 0.5 * Math.atan2(2 * this.params.rho * this.params.sigma1 * this.params.sigma2,
                                          this.params.sigma1 * this.params.sigma1 - this.params.sigma2 * this.params.sigma2);
            
            for (let i = 0; i &lt;= 100; i++) {
                const t = 2 * Math.PI * i / 100;
                const x = a * Math.cos(t) * Math.cos(angle) - b * Math.sin(t) * Math.sin(angle) + this.params.mu1;
                const y = a * Math.cos(t) * Math.sin(angle) + b * Math.sin(t) * Math.cos(angle) + this.params.mu2;
                
                const plotX = marginX + (x + 4) / 8 * plotWidth;
                const plotY = this.height - marginY - (y + 4) / 8 * plotHeight;
                
                if (i === 0) {
                    this.ctx.moveTo(plotX, plotY);
                } else {
                    this.ctx.lineTo(plotX, plotY);
                }
            }
            this.ctx.stroke();
        });
        
        // Draw samples
        if (this.samples.length &gt; 0) {
            this.ctx.fillStyle = &apos;#2196f3&apos;;
            this.samples.forEach(([x1, x2]) =&gt; {
                const plotX = marginX + (x1 + 4) / 8 * plotWidth;
                const plotY = this.height - marginY - (x2 + 4) / 8 * plotHeight;
                
                if (plotX &gt;= marginX &amp;&amp; plotX &lt;= this.width - marginX &amp;&amp;
                    plotY &gt;= marginY &amp;&amp; plotY &lt;= this.height - marginY) {
                    this.ctx.beginPath();
                    this.ctx.arc(plotX, plotY, 2, 0, 2 * Math.PI);
                    this.ctx.fill();
                }
            });
        }
        
        // Draw mean point
        const meanX = marginX + (this.params.mu1 + 4) / 8 * plotWidth;
        const meanY = this.height - marginY - (this.params.mu2 + 4) / 8 * plotHeight;
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.beginPath();
        this.ctx.arc(meanX, meanY, 4, 0, 2 * Math.PI);
        this.ctx.fill();
        
        // Labels
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;12px Arial&apos;;
        this.ctx.textAlign = &apos;center&apos;;
        this.ctx.fillText(&apos;X₁&apos;, this.width / 2, this.height - 10);
        
        this.ctx.save();
        this.ctx.translate(15, this.height / 2);
        this.ctx.rotate(-Math.PI / 2);
        this.ctx.fillText(&apos;X₂&apos;, 0, 0);
        this.ctx.restore();
    }
}

// Initialize when DOM is loaded

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new MultivariateDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=UVvuwv-ne1I&quot;&gt;Multivariate Normal (Gaussian) Distribution Explained&lt;/a&gt; — DataMListic, tiếng Anh. Giải thích trực quan về phân phối chuẩn đa biến — đối tượng chính của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kmRm3XIND8M&quot;&gt;MaDL - Expectation, Variance and Covariance&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Làm rõ vai trò của ma trận hiệp phương sai trong phân phối chuẩn đa biến khi các đặc trưng tương quan nhau.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NbzVwvE_syQ&quot;&gt;MaDL - Common Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Đặt các họ phân phối đa biến trong bức tranh chung cùng các phân phối một chiều ở bài trước.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-02-02 Phân Phối Liên Tục</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_02_02_Continuous_Distributions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_02_02_Continuous_Distributions</id>
   <content type="html">&lt;p&gt;Tại sao trọng số khởi tạo của hầu hết mạng nơ-ron lại lấy từ phân phối Chuẩn (Gaussian) hoặc Đều (Uniform), và vì sao chỉ một lỗi nhỏ khi chuẩn hóa dữ liệu đầu vào cũng có thể đẩy toàn bộ hàm Sigmoid vào vùng bão hòa? Câu trả lời nằm ở hình học của các &lt;strong&gt;phân phối liên tục&lt;/strong&gt;—nơi xác suất không tập trung tại từng điểm rời rạc mà trải đều thành diện tích dưới đường cong mật độ \(p(x)\). Bài học này giúp bạn nắm vững ba phân phối liên tục quan trọng nhất (Đều, Chuẩn, Mũ) cùng quy tắc chuẩn hóa Z-score áp dụng trực tiếp vào tiền xử lý dữ liệu và Batch Normalization.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-phân-phối-liên-tục&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Phân phối Liên tục&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hàm mật độ (PDF \(p(x)\)) và Hàm phân phối tích lũy (CDF \(F(x)\))&lt;/strong&gt;:
Với biến liên tục, xác suất tại đúng một điểm luôn bằng \(0\) (\(P(X = c) = 0\)); xác suất chỉ có nghĩa trên một khoảng: \(P(a \le X \le b) = \int_a^b p(x)\,dx = F(b) - F(a)\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân phối Đều (Uniform \(\mathcal{U}(a, b)\))&lt;/strong&gt;:
Mọi giá trị trong \([a, b]\) có mật độ ngang nhau \(p(x) = \frac{1}{b-a}\), kỳ vọng \(\frac{a+b}{2}\), phương sai \(\frac{(b-a)^2}{12}\). Đây là cơ sở của khởi tạo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Kaiming Uniform&lt;/code&gt; mặc định trong &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Linear&lt;/code&gt; của PyTorch!&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân phối Chuẩn (Gaussian \(\mathcal{N}(\mu, \sigma^2)\))&lt;/strong&gt;:
Hình chuông đối xứng đặc trưng bởi quy tắc 68–95–99.7%, định lý giới hạn trung tâm (tổng nhiều nguồn nhiễu nhỏ hội tụ về Gaussian), và phép chuẩn hóa \(Z = \frac{X - \mu}{\sigma} \sim \mathcal{N}(0, 1)\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân phối Mũ (Exponential \(\text{Exp}(\lambda)\))&lt;/strong&gt;:
Mô hình hóa thời gian chờ giữa các sự kiện với tính chất “không nhớ” (&lt;em&gt;memoryless&lt;/em&gt;), đồng thời xuất hiện trong phân phối Laplace (\(L_1\) regularization) và phân tích sinh tồn.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-biên-khởi-tạo-uniform-tương-đương-phương-sai-của-normal&quot;&gt;Giải thích: Tính tay biên khởi tạo &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Uniform&lt;/code&gt; tương đương phương sai của &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Normal&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;Trong PyTorch, khi khởi tạo một lớp tuyến tính có \(n_{\text{in}} = 100\) đầu vào theo chuẩn Xavier, ta muốn trọng số có \(\mathbb{E}[w] = 0\) và phương sai \(\text{Var}(w) = \frac{1}{100} = 0.01\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nếu dùng phân phối Chuẩn \(\mathcal{N}(0, \sigma^2)\)&lt;/strong&gt;:
Chỉ cần đặt độ lệch chuẩn \(\sigma = \sqrt{0.01} = 0.1\). Theo quy tắc 68–95–99.7%, khoảng 95% trọng số sẽ nằm trong \([-0.2, 0.2]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nếu dùng phân phối Đều đối xứng \(\mathcal{U}(-a, a)\)&lt;/strong&gt;:
Ta biết phương sai của \(\mathcal{U}(-a, a)\) là \(\text{Var}(w) = \frac{(a - (-a))^2}{12} = \frac{4a^2}{12} = \frac{a^2}{3}\).
Để \(\frac{a^2}{3} = 0.01\), ta giải được:
\(a^2 = 0.03 \implies a = \sqrt{0.03} \approx 0.1732.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra ngược&lt;/strong&gt;: Với \(w \sim \mathcal{U}(-0.1732, 0.1732)\), mật độ \(p(w) = \frac{1}{0.3464} \approx 2.887 &amp;gt; 1\) (hoàn toàn hợp lệ cho PDF!) và diện tích \(2.887 \times 0.3464 = 1\). Bạn vừa tự chứng minh xong con số \(\sqrt{3}\) nổi tiếng trong mã nguồn khởi tạo trọng số của PyTorch!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;2-phân-phối-liên-tục&quot;&gt;2. Phân phối liên tục&lt;/h3&gt;

&lt;h4 id=&quot;phân-phối-đều-uniform&quot;&gt;Phân phối đều (&lt;em&gt;Uniform&lt;/em&gt;)&lt;/h4&gt;

&lt;p&gt;Mọi giá trị trong một đoạn cho trước đều có mật độ xác suất như nhau.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tham số:&lt;/strong&gt; \(a, b \in \mathbb{R}\) với \(a &amp;lt; b\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PDF:&lt;/strong&gt; \(f(x) = \frac{1}{b-a}\) với \(x \in [a,b]\), và bằng \(0\) ngoài đoạn đó.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kỳ vọng:&lt;/strong&gt; \(\mathbb{E}[X] = \frac{a+b}{2}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương sai:&lt;/strong&gt; \(\text{Var}(X) = \frac{(b-a)^2}{12}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ứng dụng:&lt;/strong&gt; lấy mẫu ngẫu nhiên, khởi tạo tham số trong thuật toán.&lt;/p&gt;

&lt;h4 id=&quot;phân-phối-chuẩn-normal--gaussian&quot;&gt;Phân phối chuẩn (&lt;em&gt;Normal / Gaussian&lt;/em&gt;)&lt;/h4&gt;

&lt;p&gt;Đây là phân phối quan trọng và phổ biến nhất trong thống kê cũng như tối ưu hóa.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tham số:&lt;/strong&gt; \(\mu \in \mathbb{R}\) (kỳ vọng), \(\sigma^2 &amp;gt; 0\) (phương sai)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PDF:&lt;/strong&gt; \(f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kỳ vọng:&lt;/strong&gt; \(\mathbb{E}[X] = \mu\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương sai:&lt;/strong&gt; \(\text{Var}(X) = \sigma^2\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đối xứng quanh kỳ vọng \(\mu\).&lt;/li&gt;
  &lt;li&gt;Tuân theo quy tắc 68–95–99,7.&lt;/li&gt;
  &lt;li&gt;Gắn trực tiếp với Định lý giới hạn trung tâm (&lt;em&gt;Central Limit Theorem&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Có entropy cực đại trong số mọi phân phối có cùng kỳ vọng và phương sai cho trước.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;phân-phối-mũ-exponential&quot;&gt;Phân phối mũ (&lt;em&gt;Exponential&lt;/em&gt;)&lt;/h4&gt;

&lt;p&gt;Mô hình hóa thời gian chờ giữa hai sự kiện liên tiếp trong một quá trình Poisson.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tham số:&lt;/strong&gt; \(\lambda &amp;gt; 0\) (tốc độ xuất hiện)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PDF:&lt;/strong&gt; \(f(x) = \lambda e^{-\lambda x}\) với \(x \geq 0\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kỳ vọng:&lt;/strong&gt; \(\mathbb{E}[X] = \frac{1}{\lambda}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương sai:&lt;/strong&gt; \(\text{Var}(X) = \frac{1}{\lambda^2}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt; có tính không nhớ (&lt;em&gt;memoryless&lt;/em&gt;).&lt;/p&gt;

&lt;h4 id=&quot;phân-phối-beta&quot;&gt;Phân phối Beta&lt;/h4&gt;

&lt;p&gt;Phân phối liên tục linh hoạt trên đoạn \([0,1]\), thường dùng để mô hình hóa các đại lượng mang ý nghĩa xác suất hoặc tỉ lệ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tham số:&lt;/strong&gt; \(\alpha, \beta &amp;gt; 0\) (các tham số hình dạng)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PDF:&lt;/strong&gt; \(f(x) = \frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)} x^{\alpha-1}(1-x)^{\beta-1}\) với \(x \in [0,1]\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kỳ vọng:&lt;/strong&gt; \(\mathbb{E}[X] = \frac{\alpha}{\alpha+\beta}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương sai:&lt;/strong&gt; \(\text{Var}(X) = \frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}\)&lt;/p&gt;

&lt;div id=&quot;continuous-distributions-demo&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f9f9f9;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Phân phối liên tục tương tác&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;continuousCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;Trực quan hóa:&lt;/strong&gt; Hàm mật độ xác suất (PDF) của các phân phối liên tục.
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Loại phân phối&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;continuous-dist&quot; value=&quot;uniform&quot; checked=&quot;&quot; /&gt; Đều
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;continuous-dist&quot; value=&quot;normal&quot; /&gt; Chuẩn
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;continuous-dist&quot; value=&quot;exponential&quot; /&gt; Mũ
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;continuous-dist&quot; value=&quot;beta&quot; /&gt; Beta
                    &lt;/label&gt;
                &lt;/div&gt;
                
                &lt;div id=&quot;continuous-params&quot;&gt;
                    &lt;div id=&quot;uniform-params&quot;&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;a-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;a: &lt;span id=&quot;a-value&quot;&gt;0&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;a-slider&quot; min=&quot;-2&quot; max=&quot;2&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;b-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;b: &lt;span id=&quot;b-value&quot;&gt;1&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;b-slider&quot; min=&quot;0.5&quot; max=&quot;4&quot; step=&quot;0.1&quot; value=&quot;1&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                    
                    &lt;div id=&quot;normal-params&quot; style=&quot;display: none;&quot;&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;mu-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;μ: &lt;span id=&quot;mu-value&quot;&gt;0&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;mu-slider&quot; min=&quot;-3&quot; max=&quot;3&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;sigma-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;σ: &lt;span id=&quot;sigma-value&quot;&gt;1.0&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;sigma-slider&quot; min=&quot;0.5&quot; max=&quot;3&quot; step=&quot;0.1&quot; value=&quot;1.0&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                    
                    &lt;div id=&quot;exponential-params&quot; style=&quot;display: none;&quot;&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;exp-lambda-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;λ: &lt;span id=&quot;exp-lambda-value&quot;&gt;1.0&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;exp-lambda-slider&quot; min=&quot;0.2&quot; max=&quot;3&quot; step=&quot;0.1&quot; value=&quot;1.0&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                    
                    &lt;div id=&quot;beta-params&quot; style=&quot;display: none;&quot;&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;alpha-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;α: &lt;span id=&quot;alpha-value&quot;&gt;2&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;alpha-slider&quot; min=&quot;0.5&quot; max=&quot;5&quot; step=&quot;0.1&quot; value=&quot;2&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;beta-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;β: &lt;span id=&quot;beta-value&quot;&gt;2&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;beta-slider&quot; min=&quot;0.5&quot; max=&quot;5&quot; step=&quot;0.1&quot; value=&quot;2&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                
                &lt;div id=&quot;continuous-stats&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Thống kê:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;Kỳ vọng: &lt;span id=&quot;continuous-mean&quot;&gt;0.500&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Phương sai: &lt;span id=&quot;continuous-variance&quot;&gt;0.083&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Miền xác định: &lt;span id=&quot;continuous-support&quot;&gt;[0, 1]&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
class ContinuousDistributionsDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;continuousCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.distType = &apos;uniform&apos;;
        this.params = { a: 0, b: 1, mu: 0, sigma: 1, lambda: 1, alpha: 2, beta: 2 };
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const radios = document.querySelectorAll(&apos;input[name=&quot;continuous-dist&quot;]&apos;);
        
        radios.forEach(radio =&gt; {
            radio.addEventListener(&apos;change&apos;, (e) =&gt; {
                this.distType = e.target.value;
                this.updateParameterVisibility();
                this.updateStats();
                this.draw();
            });
        });
        
        // Setup all sliders
        const sliders = [&apos;a&apos;, &apos;b&apos;, &apos;mu&apos;, &apos;sigma&apos;, &apos;exp-lambda&apos;, &apos;alpha&apos;, &apos;beta&apos;];
        sliders.forEach(slider =&gt; {
            const element = document.getElementById(slider + &apos;-slider&apos;);
            if (element) {
                element.addEventListener(&apos;input&apos;, (e) =&gt; {
                    const value = parseFloat(e.target.value);
                    const param = slider === &apos;exp-lambda&apos; ? &apos;lambda&apos; : slider;
                    this.params[param] = value;
                    
                    const valueSpan = document.getElementById(slider + &apos;-value&apos;);
                    if (valueSpan) {
                        valueSpan.textContent = value.toFixed(1);
                    }
                    
                    this.updateStats();
                    this.draw();
                });
            }
        });
        
        this.updateParameterVisibility();
        this.updateStats();
    }
    
    updateParameterVisibility() {
        document.getElementById(&apos;uniform-params&apos;).style.display = 
            this.distType === &apos;uniform&apos; ? &apos;block&apos; : &apos;none&apos;;
        document.getElementById(&apos;normal-params&apos;).style.display = 
            this.distType === &apos;normal&apos; ? &apos;block&apos; : &apos;none&apos;;
        document.getElementById(&apos;exponential-params&apos;).style.display = 
            this.distType === &apos;exponential&apos; ? &apos;block&apos; : &apos;none&apos;;
        document.getElementById(&apos;beta-params&apos;).style.display = 
            this.distType === &apos;beta&apos; ? &apos;block&apos; : &apos;none&apos;;
    }
    
    updateStats() {
        let mean, variance, support;
        
        switch(this.distType) {
            case &apos;uniform&apos;:
                mean = (this.params.a + this.params.b) / 2;
                variance = Math.pow(this.params.b - this.params.a, 2) / 12;
                support = `[${this.params.a}, ${this.params.b}]`;
                break;
            case &apos;normal&apos;:
                mean = this.params.mu;
                variance = this.params.sigma * this.params.sigma;
                support = &apos;(-∞, ∞)&apos;;
                break;
            case &apos;exponential&apos;:
                mean = 1 / this.params.lambda;
                variance = 1 / (this.params.lambda * this.params.lambda);
                support = &apos;[0, ∞)&apos;;
                break;
            case &apos;beta&apos;:
                mean = this.params.alpha / (this.params.alpha + this.params.beta);
                variance = (this.params.alpha * this.params.beta) / 
                          (Math.pow(this.params.alpha + this.params.beta, 2) * 
                           (this.params.alpha + this.params.beta + 1));
                support = &apos;[0, 1]&apos;;
                break;
        }
        
        document.getElementById(&apos;continuous-mean&apos;).textContent = mean.toFixed(3);
        document.getElementById(&apos;continuous-variance&apos;).textContent = variance.toFixed(3);
        document.getElementById(&apos;continuous-support&apos;).textContent = support;
    }
    
    gamma(z) {
        // Stirling&apos;s approximation for gamma function
        if (z &lt; 0.5) return Math.PI / (Math.sin(Math.PI * z) * this.gamma(1 - z));
        z -= 1;
        let x = 0.99999999999980993;
        const p = [676.5203681218851, -1259.1392167224028, 771.32342877765313,
                  -176.61502916214059, 12.507343278686905, -0.13857109526572012,
                  9.9843695780195716e-6, 1.5056327351493116e-7];
        for (let i = 0; i &lt; p.length; i++) {
            x += p[i] / (z + i + 1);
        }
        const t = z + p.length - 0.5;
        return Math.sqrt(2 * Math.PI) * Math.pow(t, z + 0.5) * Math.exp(-t) * x;
    }
    
    getPDF(x) {
        switch(this.distType) {
            case &apos;uniform&apos;:
                return (x &gt;= this.params.a &amp;&amp; x &lt;= this.params.b) ? 
                       1 / (this.params.b - this.params.a) : 0;
            case &apos;normal&apos;:
                return Math.exp(-0.5 * Math.pow((x - this.params.mu) / this.params.sigma, 2)) / 
                       (this.params.sigma * Math.sqrt(2 * Math.PI));
            case &apos;exponential&apos;:
                return x &gt;= 0 ? this.params.lambda * Math.exp(-this.params.lambda * x) : 0;
            case &apos;beta&apos;:
                if (x &lt; 0 || x &gt; 1) return 0;
                const B = this.gamma(this.params.alpha) * this.gamma(this.params.beta) / 
                         this.gamma(this.params.alpha + this.params.beta);
                return Math.pow(x, this.params.alpha - 1) * Math.pow(1 - x, this.params.beta - 1) / B;
        }
    }
    
    getRange() {
        switch(this.distType) {
            case &apos;uniform&apos;: return [this.params.a - 0.5, this.params.b + 0.5];
            case &apos;normal&apos;: return [this.params.mu - 4 * this.params.sigma, this.params.mu + 4 * this.params.sigma];
            case &apos;exponential&apos;: return [0, 5 / this.params.lambda];
            case &apos;beta&apos;: return [0, 1];
        }
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        const marginX = 50;
        const marginY = 50;
        const plotWidth = this.width - 2 * marginX;
        const plotHeight = this.height - 2 * marginY;
        
        // Draw axes
        this.ctx.strokeStyle = &apos;#ddd&apos;;
        this.ctx.lineWidth = 1;
        this.ctx.beginPath();
        this.ctx.moveTo(marginX, this.height - marginY);
        this.ctx.lineTo(this.width - marginX, this.height - marginY);
        this.ctx.moveTo(marginX, marginY);
        this.ctx.lineTo(marginX, this.height - marginY);
        this.ctx.stroke();
        
        const [minX, maxX] = this.getRange();
        
        // Find max PDF for scaling
        let maxPDF = 0;
        for (let i = 0; i &lt;= 200; i++) {
            const x = minX + (maxX - minX) * i / 200;
            maxPDF = Math.max(maxPDF, this.getPDF(x));
        }
        
        // Draw PDF curve
        this.ctx.strokeStyle = &apos;#2196f3&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        
        for (let i = 0; i &lt;= 200; i++) {
            const x = minX + (maxX - minX) * i / 200;
            const pdf = this.getPDF(x);
            const plotX = marginX + (x - minX) / (maxX - minX) * plotWidth;
            const plotY = this.height - marginY - (pdf / maxPDF) * plotHeight * 0.8;
            
            if (i === 0) {
                this.ctx.moveTo(plotX, plotY);
            } else {
                this.ctx.lineTo(plotX, plotY);
            }
        }
        this.ctx.stroke();
        
        // Labels
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;12px Arial&apos;;
        this.ctx.textAlign = &apos;center&apos;;
        this.ctx.fillText(&apos;x&apos;, this.width / 2, this.height - 10);
        
        this.ctx.save();
        this.ctx.translate(15, this.height / 2);
        this.ctx.rotate(-Math.PI / 2);
        this.ctx.fillText(&apos;f(x)&apos;, 0, 0);
        this.ctx.restore();
    }
}

// Multivariate Normal Demo

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new ContinuousDistributionsDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=rzFX5NWojp0&quot;&gt;The Normal Distribution, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Trình bày phân phối chuẩn — phân phối liên tục trọng tâm của bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=oI3hZJqXJuc&quot;&gt;The Main Ideas behind Probability Distributions&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Làm rõ sự khác biệt giữa hàm mật độ xác suất (PDF) và hàm khối xác suất (PMF) trước khi làm việc với các công thức liên tục.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NbzVwvE_syQ&quot;&gt;MaDL - Common Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Đặt phân phối Gauss cạnh các phân phối liên tục khác như phân phối mũ và Beta.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-02-01 Phân Phối Rời Rạc</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_02_01_Discrete_Distributions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_02_01_Discrete_Distributions</id>
   <content type="html">&lt;p&gt;Từ một lần tung đồng xu xác định bật hay tắt một nơ-ron trong Dropout, cho tới việc một mô hình ngôn ngữ chọn ra 1 từ trong kho 50{,}000 từ vựng, mọi quyết định rời rạc trong Học sâu đều được điều khiển bởi các &lt;strong&gt;phân phối rời rạc&lt;/strong&gt;. Nếu không phân biệt rõ Bernoulli, Nhị thức (Binomial), Categorical và Poisson, ta rất dễ dùng nhầm hàm mất mát hoặc hiểu sai bản chất thống kê của độ chính xác phân loại. Bài học này đi sâu vào công thức, kỳ vọng, phương sai và dấu ấn thực tế của từng phân phối rời rạc trong Deep Learning.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-phân-phối-rời-rạc-trụ-cột&quot;&gt;Kiến thức cần nhớ: Bốn phân phối Rời rạc trụ cột&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân phối Bernoulli (\(p\))&lt;/strong&gt;:
Mô hình hóa một phép thử Đúng/Sai duy nhất với \(P(X=1)=p\), \(\mathbb{E}[X]=p\), \(\text{Var}(X)=p(1-p)\). Đây là nền tảng của phân loại nhị phân và từng phần tử trong mặt nạ Dropout.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân phối Nhị thức — Binomial (\(n, p\))&lt;/strong&gt;:
Đếm số lần thành công trong \(n\) phép thử Bernoulli độc lập, với \(\mathbb{E}[X]=np\) và \(\text{Var}(X)=np(1-p)\). Dùng để đánh giá độ tin cậy thống kê khi kiểm thử mô hình trên \(n\) mẫu test.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân phối Categorical / Multinomial&lt;/strong&gt;:
Mở rộng Bernoulli từ 2 lớp lên \(K\) lớp với vector xác suất \(\sum_{k=1}^K p_k = 1\)—đầu ra chuẩn của mọi bài toán phân loại đa lớp và dự đoán token kế tiếp trong Transformer.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân phối Poisson (\(\lambda\))&lt;/strong&gt;:
Mô hình hóa số lần sự kiện xảy ra trong một khoảng thời gian/không gian cố định (ví dụ số lượt nhấp chuột, số lượng phương tiện qua ngã tư mỗi phút), với đặc trưng \(\mathbb{E}[X] = \text{Var}(X) = \lambda\).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-xác-suất-và-phương-sai-cho-dropout-bernoulli-và-test-set-binomial&quot;&gt;Giải thích: Tính tay xác suất và phương sai cho Dropout (Bernoulli) và Test Set (Binomial)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Phân tích một lớp Dropout với xác suất giữ lại \(p = 0.8\) (tỷ lệ tắt 20%):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mỗi nơ-ron nhân với biến \(M \sim \text{Bernoulli}(0.8)\): \(P(M=1)=0.8, P(M=0)=0.2\).&lt;/li&gt;
  &lt;li&gt;Kỳ vọng: \(\mathbb{E}[M] = 0.8\); phương sai: \(\text{Var}(M) = 0.8 \times 0.2 = 0.16\).&lt;/li&gt;
  &lt;li&gt;Để kỳ vọng đầu ra khi huấn luyện khớp với lúc suy luận (không tắt nơ-ron), ta chia cho \(0.8\) (nhân \(1.25\)): \(\mathbb{E}[M / 0.8] = 0.8 / 0.8 = 1.0\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Tính tay xác suất Binomial khi chấm điểm 5 mẫu kiểm thử:&lt;/strong&gt;
Giả sử mô hình có độ chính xác thật \(p = 0.8\) trên mỗi mẫu độc lập. Xác suất mô hình đoán đúng &lt;strong&gt;ít nhất 4 trên 5 mẫu&lt;/strong&gt; là:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Đúng đúng 4 mẫu: \(P(X=4) = \binom{5}{4}(0.8)^4(0.2)^1 = 5 \times 0.4096 \times 0.2 = 0.4096\).&lt;/li&gt;
  &lt;li&gt;Đúng cả 5 mẫu: \(P(X=5) = \binom{5}{5}(0.8)^5(0.2)^0 = 1 \times 0.32768 = 0.32768\).&lt;/li&gt;
  &lt;li&gt;Cộng lại: \(P(X \ge 4) = 0.4096 + 0.32768 = 0.73728 \approx 73.73\%\).
Dù độ chính xác thật là 80%, vẫn có hơn 26% khả năng trên 5 mẫu ngẫu nhiên mô hình chỉ đạt \(\le 60\%\)—nhắc ta luôn cần tập kiểm thử đủ lớn để giảm phương sai đánh giá!&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;các-phân-phối-xác-suất-thông-dụng&quot;&gt;Các phân phối xác suất thông dụng&lt;/h2&gt;

&lt;p&gt;Nắm vững các phân phối xác suất cơ bản là yêu cầu thiết yếu cho các bài toán tối ưu hóa trong học máy và thống kê. Các phân phối này thường xuất hiện dưới dạng giả định mô hình dữ liệu, phân phối tiên nghiệm (&lt;em&gt;prior&lt;/em&gt;) trong phương pháp Bayes và mô hình nhiễu trong hồi quy.&lt;/p&gt;

&lt;h3 id=&quot;1-phân-phối-rời-rạc&quot;&gt;1. Phân phối rời rạc&lt;/h3&gt;

&lt;h4 id=&quot;phân-phối-bernoulli&quot;&gt;Phân phối Bernoulli&lt;/h4&gt;

&lt;p&gt;Mô hình hóa một phép thử đơn lẻ chỉ có hai kết quả (thành công hoặc thất bại).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tham số:&lt;/strong&gt; \(p \in [0,1]\) (xác suất thành công)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PMF:&lt;/strong&gt; \(P(X = k) = p^k (1-p)^{1-k}\) với \(k \in \{0,1\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kỳ vọng:&lt;/strong&gt; \(\mathbb{E}[X] = p\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương sai:&lt;/strong&gt; \(\text{Var}(X) = p(1-p)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ứng dụng:&lt;/strong&gt; phân loại nhị phân, tung đồng xu, kiểm định A/B.&lt;/p&gt;

&lt;h4 id=&quot;phân-phối-nhị-thức-binomial&quot;&gt;Phân phối nhị thức (&lt;em&gt;Binomial&lt;/em&gt;)&lt;/h4&gt;

&lt;p&gt;Mô hình hóa số lần thành công trong \(n\) phép thử Bernoulli độc lập.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tham số:&lt;/strong&gt; \(n \in \mathbb{N}\) (số phép thử), \(p \in [0,1]\) (xác suất thành công ở mỗi phép thử)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PMF:&lt;/strong&gt; \(P(X = k) = \binom{n}{k} p^k (1-p)^{n-k}\) với \(k = 0,1,\ldots,n\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kỳ vọng:&lt;/strong&gt; \(\mathbb{E}[X] = np\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương sai:&lt;/strong&gt; \(\text{Var}(X) = np(1-p)\)&lt;/p&gt;

&lt;h4 id=&quot;phân-phối-poisson&quot;&gt;Phân phối Poisson&lt;/h4&gt;

&lt;p&gt;Mô hình hóa số sự kiện xảy ra trong một khoảng thời gian (hoặc không gian) cố định khi các sự kiện xuất hiện độc lập với tốc độ trung bình không đổi.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tham số:&lt;/strong&gt; \(\lambda &amp;gt; 0\) (tốc độ xuất hiện trung bình)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PMF:&lt;/strong&gt; \(P(X = k) = \frac{\lambda^k e^{-\lambda}}{k!}\) với \(k = 0,1,2,\ldots\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kỳ vọng:&lt;/strong&gt; \(\mathbb{E}[X] = \lambda\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương sai:&lt;/strong&gt; \(\text{Var}(X) = \lambda\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ứng dụng:&lt;/strong&gt; dữ liệu đếm, sự kiện hiếm, lý thuyết hàng đợi.&lt;/p&gt;

&lt;div id=&quot;discrete-distributions-demo&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f9f9f9;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Phân phối rời rạc tương tác&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;discreteCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;Trực quan hóa:&lt;/strong&gt; Hàm khối xác suất (PMF) của các phân phối rời rạc.
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Loại phân phối&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;discrete-dist&quot; value=&quot;bernoulli&quot; checked=&quot;&quot; /&gt; Bernoulli
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;discrete-dist&quot; value=&quot;binomial&quot; /&gt; Nhị thức
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;discrete-dist&quot; value=&quot;poisson&quot; /&gt; Poisson
                    &lt;/label&gt;
                &lt;/div&gt;
                
                &lt;div id=&quot;discrete-params&quot;&gt;
                    &lt;div id=&quot;p-param&quot; style=&quot;margin-bottom: 15px;&quot;&gt;
                        &lt;label for=&quot;p-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;p: &lt;span id=&quot;p-value&quot;&gt;0.5&lt;/span&gt;&lt;/label&gt;
                        &lt;input type=&quot;range&quot; id=&quot;p-slider&quot; min=&quot;0.1&quot; max=&quot;0.9&quot; step=&quot;0.05&quot; value=&quot;0.5&quot; style=&quot;width: 100%;&quot; /&gt;
                    &lt;/div&gt;
                    
                    &lt;div id=&quot;n-param&quot; style=&quot;margin-bottom: 15px; display: none;&quot;&gt;
                        &lt;label for=&quot;n-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;n: &lt;span id=&quot;n-value&quot;&gt;10&lt;/span&gt;&lt;/label&gt;
                        &lt;input type=&quot;range&quot; id=&quot;n-slider&quot; min=&quot;5&quot; max=&quot;50&quot; step=&quot;1&quot; value=&quot;10&quot; style=&quot;width: 100%;&quot; /&gt;
                    &lt;/div&gt;
                    
                    &lt;div id=&quot;lambda-param&quot; style=&quot;margin-bottom: 15px; display: none;&quot;&gt;
                        &lt;label for=&quot;lambda-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;λ: &lt;span id=&quot;lambda-value&quot;&gt;3.0&lt;/span&gt;&lt;/label&gt;
                        &lt;input type=&quot;range&quot; id=&quot;lambda-slider&quot; min=&quot;0.5&quot; max=&quot;10&quot; step=&quot;0.5&quot; value=&quot;3.0&quot; style=&quot;width: 100%;&quot; /&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                
                &lt;div id=&quot;discrete-stats&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Thống kê:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;Kỳ vọng: &lt;span id=&quot;discrete-mean&quot;&gt;0.500&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Phương sai: &lt;span id=&quot;discrete-variance&quot;&gt;0.250&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Mode: &lt;span id=&quot;discrete-mode&quot;&gt;0 hoặc 1&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
class DiscreteDistributionsDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;discreteCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.distType = &apos;bernoulli&apos;;
        this.params = { p: 0.5, n: 10, lambda: 3.0 };
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const radios = document.querySelectorAll(&apos;input[name=&quot;discrete-dist&quot;]&apos;);
        const pSlider = document.getElementById(&apos;p-slider&apos;);
        const nSlider = document.getElementById(&apos;n-slider&apos;);
        const lambdaSlider = document.getElementById(&apos;lambda-slider&apos;);
        
        radios.forEach(radio =&gt; {
            radio.addEventListener(&apos;change&apos;, (e) =&gt; {
                this.distType = e.target.value;
                this.updateParameterVisibility();
                this.updateStats();
                this.draw();
            });
        });
        
        pSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.params.p = parseFloat(e.target.value);
            document.getElementById(&apos;p-value&apos;).textContent = this.params.p.toFixed(1);
            this.updateStats();
            this.draw();
        });
        
        nSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.params.n = parseInt(e.target.value);
            document.getElementById(&apos;n-value&apos;).textContent = this.params.n;
            this.updateStats();
            this.draw();
        });
        
        lambdaSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.params.lambda = parseFloat(e.target.value);
            document.getElementById(&apos;lambda-value&apos;).textContent = this.params.lambda.toFixed(1);
            this.updateStats();
            this.draw();
        });
        
        this.updateParameterVisibility();
        this.updateStats();
    }
    
    updateParameterVisibility() {
        document.getElementById(&apos;p-param&apos;).style.display = 
            (this.distType === &apos;bernoulli&apos; || this.distType === &apos;binomial&apos;) ? &apos;block&apos; : &apos;none&apos;;
        document.getElementById(&apos;n-param&apos;).style.display = 
            this.distType === &apos;binomial&apos; ? &apos;block&apos; : &apos;none&apos;;
        document.getElementById(&apos;lambda-param&apos;).style.display = 
            this.distType === &apos;poisson&apos; ? &apos;block&apos; : &apos;none&apos;;
    }
    
    updateStats() {
        let mean, variance, mode;
        
        switch(this.distType) {
            case &apos;bernoulli&apos;:
                mean = this.params.p;
                variance = this.params.p * (1 - this.params.p);
                mode = this.params.p &gt; 0.5 ? &apos;1&apos; : (this.params.p &lt; 0.5 ? &apos;0&apos; : &apos;0 hoặc 1&apos;);
                break;
            case &apos;binomial&apos;:
                mean = this.params.n * this.params.p;
                variance = this.params.n * this.params.p * (1 - this.params.p);
                mode = Math.floor((this.params.n + 1) * this.params.p).toString();
                break;
            case &apos;poisson&apos;:
                mean = this.params.lambda;
                variance = this.params.lambda;
                mode = Math.floor(this.params.lambda).toString();
                break;
        }
        
        document.getElementById(&apos;discrete-mean&apos;).textContent = mean.toFixed(3);
        document.getElementById(&apos;discrete-variance&apos;).textContent = variance.toFixed(3);
        document.getElementById(&apos;discrete-mode&apos;).textContent = mode;
    }
    
    factorial(n) {
        if (n &lt;= 1) return 1;
        return n * this.factorial(n - 1);
    }
    
    binomialCoeff(n, k) {
        if (k &gt; n) return 0;
        return this.factorial(n) / (this.factorial(k) * this.factorial(n - k));
    }
    
    getProbability(k) {
        switch(this.distType) {
            case &apos;bernoulli&apos;:
                return k === 0 ? (1 - this.params.p) : (k === 1 ? this.params.p : 0);
            case &apos;binomial&apos;:
                if (k &lt; 0 || k &gt; this.params.n) return 0;
                return this.binomialCoeff(this.params.n, k) * 
                       Math.pow(this.params.p, k) * 
                       Math.pow(1 - this.params.p, this.params.n - k);
            case &apos;poisson&apos;:
                if (k &lt; 0) return 0;
                return Math.pow(this.params.lambda, k) * Math.exp(-this.params.lambda) / this.factorial(k);
        }
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        const marginX = 50;
        const marginY = 50;
        const plotWidth = this.width - 2 * marginX;
        const plotHeight = this.height - 2 * marginY;
        
        // Draw axes
        this.ctx.strokeStyle = &apos;#ddd&apos;;
        this.ctx.lineWidth = 1;
        this.ctx.beginPath();
        this.ctx.moveTo(marginX, this.height - marginY);
        this.ctx.lineTo(this.width - marginX, this.height - marginY);
        this.ctx.moveTo(marginX, marginY);
        this.ctx.lineTo(marginX, this.height - marginY);
        this.ctx.stroke();
        
        // Determine range
        let maxK;
        switch(this.distType) {
            case &apos;bernoulli&apos;: maxK = 1; break;
            case &apos;binomial&apos;: maxK = this.params.n; break;
            case &apos;poisson&apos;: maxK = Math.min(20, this.params.lambda + 3 * Math.sqrt(this.params.lambda)); break;
        }
        
        // Find max probability for scaling
        let maxProb = 0;
        for (let k = 0; k &lt;= maxK; k++) {
            maxProb = Math.max(maxProb, this.getProbability(k));
        }
        
        // Draw bars
        this.ctx.fillStyle = &apos;#2196f3&apos;;
        const barWidth = plotWidth / (maxK + 2);
        
        for (let k = 0; k &lt;= maxK; k++) {
            const prob = this.getProbability(k);
            const x = marginX + (k + 0.5) * barWidth;
            const height = (prob / maxProb) * plotHeight * 0.8;
            const y = this.height - marginY - height;
            
            this.ctx.fillRect(x - barWidth * 0.3, y, barWidth * 0.6, height);
            
            // Label
            this.ctx.fillStyle = &apos;#000&apos;;
            this.ctx.font = &apos;10px Arial&apos;;
            this.ctx.textAlign = &apos;center&apos;;
            this.ctx.fillText(k.toString(), x, this.height - marginY + 15);
            this.ctx.fillText(prob.toFixed(3), x, y - 5);
            this.ctx.fillStyle = &apos;#2196f3&apos;;
        }
        
        // Labels
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;12px Arial&apos;;
        this.ctx.textAlign = &apos;center&apos;;
        this.ctx.fillText(&apos;k&apos;, this.width / 2, this.height - 10);
        
        this.ctx.save();
        this.ctx.translate(15, this.height / 2);
        this.ctx.rotate(-Math.PI / 2);
        this.ctx.fillText(&apos;P(X = k)&apos;, 0, 0);
        this.ctx.restore();
    }
}

// Continuous Distributions Demo

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new DiscreteDistributionsDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=J8jNoF-K8E8&quot;&gt;The Binomial Distribution and Test, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích rõ phép thử Bernoulli và phân phối nhị thức — hai mô hình rời rạc trọng tâm của bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Binomial distributions&lt;/td&gt;
          &lt;td&gt;Probabilities of probabilities, part 1](https://www.youtube.com/watch?v=8idr1WZ1A7Q) — 3Blue1Brown, tiếng Anh. Trình bày góc nhìn trực quan về phân phối nhị thức khi số lần thành công là biến ngẫu nhiên.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jmqZG6roVqU&quot;&gt;An Introduction to the Poisson Distribution&lt;/a&gt; — jbstatistics, tiếng Anh. Giới thiệu phân phối Poisson, họ phân phối rời rạc còn lại được khảo sát trong bài.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-01 Lý Thuyết Xác Suất Cơ Bản</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_01_Basic_Probability_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_01_Basic_Probability_Theory</id>
   <content type="html">&lt;p&gt;Trước khi làm quen với những mô hình xác suất phức tạp như Variational Autoencoder hay Diffusion Models, mọi thứ đều bắt đầu từ ba câu hỏi rất đời thường: &lt;em&gt;những kết cục nào có thể xảy ra?&lt;/em&gt; (không gian mẫu), &lt;em&gt;biết thêm manh mối mới thì xác suất thay đổi ra sao?&lt;/em&gt; (xác suất có điều kiện), và &lt;em&gt;làm sao gán con số cho các kết cục ngẫu nhiên để tính toán?&lt;/em&gt; (biến ngẫu nhiên). Mục tổng quan này dẫn lối qua ba bài học nền tảng giúp bạn chuyển hóa trực giác xác suất thành công cụ toán học sắc bén cho Deep Learning.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-tầng-kiến-thức-của-lý-thuyết-xác-suất-cơ-bản&quot;&gt;Kiến thức cần nhớ: Ba tầng kiến thức của Lý thuyết Xác suất Cơ bản&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Không gian mẫu và Tiên đề Kolmogorov&lt;/strong&gt;:
Thiết lập luật chơi tối thiểu (không âm, tổng bằng 1, cộng tính trên biến cố xung khắc) để mọi công thức xác suất sau này không bao giờ mâu thuẫn—chính xác là điều kiện mà hàm Softmax ở tầng cuối mạng phân loại luôn phải thỏa mãn.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Xác suất có điều kiện, Độc lập và Định lý Bayes&lt;/strong&gt;:
Nền tảng của mô hình ngôn ngữ tự hồi quy \(P(w_1, \dots, w_T) = \prod_t P(w_t \mid w_{&amp;lt;t})\) và giả định dữ liệu i.i.d. (độc lập, cùng phân phối) khi tính tổng hàm mất mát trên tập huấn luyện.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Biến ngẫu nhiên, Kỳ vọng và Phương sai&lt;/strong&gt;:
Cho phép định lượng rủi ro kỳ vọng (&lt;em&gt;expected risk&lt;/em&gt;), kiểm soát phương sai của tín hiệu qua các tầng mạng (BatchNorm, LayerNorm) và phân tích độ nhiễu của gradient ngẫu nhiên.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tách-một-xác-suất-đồng-thời-bằng-quy-tắc-chuỗi-xác-suất&quot;&gt;Giải thích: Tách một xác suất đồng thời bằng Quy tắc Chuỗi Xác suất&lt;/h3&gt;

&lt;p&gt;Xét một mô hình ngôn ngữ mini sinh câu 3 từ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;Tôi học AI&quot;&lt;/code&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Xác suất từ đầu tiên: \(P(\text{&quot;Tôi&quot;}) = 0.20\).&lt;/li&gt;
  &lt;li&gt;Biết từ đầu là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;Tôi&quot;&lt;/code&gt;, xác suất từ kế tiếp là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;học&quot;&lt;/code&gt;: \(P(\text{&quot;học&quot;} \mid \text{&quot;Tôi&quot;}) = 0.30\).&lt;/li&gt;
  &lt;li&gt;Biết hai từ đầu là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;Tôi học&quot;&lt;/code&gt;, xác suất từ cuối là &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;AI&quot;&lt;/code&gt;: \(P(\text{&quot;AI&quot;} \mid \text{&quot;Tôi học&quot;}) = 0.50\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng quy tắc chuỗi xác suất&lt;/strong&gt;:
\(P(\text{&quot;Tôi học AI&quot;}) = 0.20 \times 0.30 \times 0.50 = 0.03.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chuyển sang log-xác suất (để tránh tràn số dưới &lt;em&gt;underflow&lt;/em&gt; trên máy tính)&lt;/strong&gt;:
\(\ln P = \ln(0.20) + \ln(0.30) + \ln(0.50) \approx -1.609 - 1.204 - 0.693 = -3.506.\)
Chỉ từ một quy tắc xác suất cơ bản, bạn đã nhìn thấy trọn vẹn cơ chế tính điểm của mọi mô hình ngôn ngữ lớn (LLM) hiện nay!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bài học này trình bày lý thuyết xác suất cơ bản phục vụ cho học sâu (&lt;em&gt;deep learning&lt;/em&gt;), gồm ba phần chính:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Không gian mẫu và tiên đề xác suất&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất có điều kiện và tính độc lập&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biến ngẫu nhiên và học sâu&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Mỗi phần có kèm minh họa tương tác (nếu có).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pA83XtLeVig&quot;&gt;L01.4 Probability Axioms&lt;/a&gt; — MIT OpenCourseWare, tiếng Anh. Trình bày các tiên đề xác suất mở đầu cho cụm bài này.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=_IgyaD7vOOA&quot;&gt;Conditional Probabilities, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích rõ ràng về xác suất có điều kiện, nội dung trọng tâm của bài thứ hai.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=bvBukLjHZh8&quot;&gt;MaDL - Random Variables and Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Giới thiệu biến ngẫu nhiên và phân phối, gắn với cách mô hình học sâu biểu diễn dữ liệu.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-01-03 Biến Ngẫu Nhiên và Deep Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_01_03_Random_Variables_and_Deep_Learning/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_01_03_Random_Variables_and_Deep_Learning</id>
   <content type="html">&lt;p&gt;Máy tính không thể cộng trừ chữ “Mèo” hay “Mưa”, nhưng ngay khi ta gán cho mỗi kết cục ngẫu nhiên một con số thực—gọi là &lt;strong&gt;biến ngẫu nhiên&lt;/strong&gt; (&lt;em&gt;random variable&lt;/em&gt;)—toàn bộ kho vũ khí của giải tích và đại số lập tức phát huy tác dụng. Trong một mạng nơ-ron đang huấn luyện, gần như mọi thứ đều là biến ngẫu nhiên: từ mẫu dữ liệu rút ngẫu nhiên trong mini-batch, mặt nạ Dropout bật/tắt 0–1, cho tới chính trọng số khởi tạo ban đầu. Hiểu rõ kỳ vọng, phương sai và hiệp phương sai của biến ngẫu nhiên giúp bạn kiểm soát dòng chảy tín hiệu xuyên qua hàng trăm tầng mạng.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-công-cụ-của-biến-ngẫu-nhiên-trong-học-sâu&quot;&gt;Kiến thức cần nhớ: Bốn công cụ của Biến Ngẫu nhiên trong Học sâu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Biến ngẫu nhiên Rời rạc (PMF) vs. Liên tục (PDF &amp;amp; CDF)&lt;/strong&gt;:
Biến rời rạc dùng hàm khối xác suất \(P(X = x)\) và tổng \(\sum\); biến liên tục dùng hàm mật độ \(p(x)\) (có thể lớn hơn \(1\)!) và tích phân \(\int p(x)\,dx = 1\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Kỳ vọng (\(\mathbb{E}[X]\)) và Tính tuyến tính của Kỳ vọng&lt;/strong&gt;:
\(\mathbb{E}[aX + bY] = a\mathbb{E}[X] + b\mathbb{E}[Y]\) luôn đúng &lt;em&gt;kể cả khi \(X, Y\) phụ thuộc nhau&lt;/em&gt;—đây là cơ sở chứng minh công thức bù tỷ lệ \(\frac{1}{1-p}\) của Inverted Dropout!&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phương sai (\(\text{Var}(X)\)) và Luật nhân hệ số&lt;/strong&gt;:
\(\text{Var}(aX) = a^2 \text{Var}(X)\), và với các biến độc lập, \(\text{Var}\!\left(\sum_{i=1}^n X_i\right) = \sum_{i=1}^n \text{Var}(X_i)\). Công thức này dẫn thẳng tới công thức khởi tạo trọng số &lt;strong&gt;Xavier&lt;/strong&gt; (\(\text{Var}(w) = 1/n_{\text{in}}\)) để tín hiệu không phình to khi đi qua lớp rộng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hàm mất mát dưới góc nhìn Kỳ vọng (Expected Risk)&lt;/strong&gt;:
Mục tiêu lý tưởng của Deep Learning là cực tiểu hóa rủi ro kỳ vọng \(\mathbb{E}_{(x,y)\sim P_{\text{data}}}[\ell(f_\theta(x), y)]\), và tập huấn luyện chỉ là trung bình thực nghiệm xấp xỉ kỳ vọng đó.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-phương-sai-qua-một-nơ-ron-tuyến-tính-để-hiểu-khởi-tạo-xavier&quot;&gt;Giải thích: Tính tay phương sai qua một nơ-ron tuyến tính để hiểu khởi tạo Xavier&lt;/h3&gt;

&lt;p&gt;Giả sử một nơ-ron nhận \(n = 100\) đầu vào độc lập \(x_1, \dots, x_{100}\) đều có \(\mathbb{E}[x_i] = 0, \text{Var}(x_i) = 1\), và ta khởi tạo trọng số độc lập \(w_1, \dots, w_{100}\) với \(\mathbb{E}[w_i] = 0, \text{Var}(w_i) = \sigma_w^2\). Xét đầu ra \(z = \sum_{i=1}^{100} w_i x_i\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kỳ vọng của \(z\)&lt;/strong&gt;: Do \(w_i\) và \(x_i\) độc lập, \(\mathbb{E}[w_i x_i] = \mathbb{E}[w_i]\mathbb{E}[x_i] = 0 \implies \mathbb{E}[z] = 0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương sai của từng tích \(w_i x_i\)&lt;/strong&gt;:
\(\text{Var}(w_i x_i) = \mathbb{E}[w_i^2 x_i^2] - (\mathbb{E}[w_i x_i])^2 = \mathbb{E}[w_i^2]\mathbb{E}[x_i^2] = \sigma_w^2 \times 1 = \sigma_w^2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương sai tổng \(z\)&lt;/strong&gt;: Vì 100 số hạng độc lập nhau,
\(\text{Var}(z) = \sum_{i=1}^{100} \text{Var}(w_i x_i) = 100\,\sigma_w^2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thử thay số&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Nếu chọn ngây thơ \(\sigma_w = 1\): \(\text{Var}(z) = 100\) (độ lệch chuẩn tăng gấp 10 chỉ sau 1 tầng—đi qua 5 tầng sẽ bùng nổ thành \(10^{10}\)!).&lt;/li&gt;
      &lt;li&gt;Nếu chọn \(\sigma_w^2 = \frac{1}{100} \implies \sigma_w = 0.1\): \(\text{Var}(z) = 100 \times 0.01 = 1\) (giữ nguyên thang đo tín hiệu!). Đó chính là linh hồn toán học của khởi tạo Xavier/He.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;6-biến-ngẫu-nhiên&quot;&gt;6. Biến ngẫu nhiên&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Biến ngẫu nhiên&lt;/strong&gt; \(X\) là một hàm ánh xạ mỗi kết quả trong không gian mẫu sang một số thực:
\(X: \Omega \rightarrow \mathbb{R}\)&lt;/p&gt;

&lt;h4 id=&quot;phân-loại-biến-ngẫu-nhiên&quot;&gt;Phân loại biến ngẫu nhiên&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Biến ngẫu nhiên rời rạc:&lt;/strong&gt; nhận tập giá trị hữu hạn hoặc đếm được (ví dụ: số lần xuất hiện mặt sấp).&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Hàm khối xác suất (&lt;em&gt;PMF&lt;/em&gt;): \(P(X = x)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Biến ngẫu nhiên liên tục:&lt;/strong&gt; nhận giá trị trên một khoảng liên tục của trục số thực (ví dụ: chiều cao, cân nặng).&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Hàm mật độ xác suất (&lt;em&gt;PDF&lt;/em&gt;): \(f_X(x)\)&lt;/li&gt;
  &lt;li&gt;
\[P(a \leq X \leq b) = \int_a^b f_X(x) dx\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;7-liên-hệ-với-tối-ưu-hóa&quot;&gt;7. Liên hệ với tối ưu hóa&lt;/h3&gt;

&lt;p&gt;Lý thuyết xác suất gắn liền với tối ưu hóa qua nhiều bài toán quen thuộc:&lt;/p&gt;

&lt;h4 id=&quot;ước-lượng-hợp-lý-cực-đại-mle&quot;&gt;Ước lượng hợp lý cực đại (MLE)&lt;/h4&gt;
&lt;p&gt;Tìm tham số \(\theta\) cực đại hóa hàm hợp lý (&lt;em&gt;likelihood&lt;/em&gt;):
\(\hat{\theta} = \arg\max_\theta P(\text{dữ liệu}|\theta)\)&lt;/p&gt;

&lt;h4 id=&quot;tối-ưu-hóa-giá-trị-kỳ-vọng&quot;&gt;Tối ưu hóa giá trị kỳ vọng&lt;/h4&gt;
&lt;p&gt;Cực tiểu hóa hàm mất mát kỳ vọng:
\(\min_\theta \mathbb{E}[L(Y, f(X; \theta))]\)&lt;/p&gt;

&lt;h4 id=&quot;tối-ưu-hóa-bayes&quot;&gt;Tối ưu hóa Bayes&lt;/h4&gt;
&lt;p&gt;Sử dụng phân phối xác suất để mô hình hóa sự bất định của hàm mục tiêu và định hướng quá trình tìm kiếm nghiệm tối ưu.&lt;/p&gt;

&lt;div id=&quot;deep-learning-connection&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f0f8ff;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Ví dụ ứng dụng xác suất trong tối ưu hóa&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;deep-learningCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;Ví dụ MLE:&lt;/strong&gt; Tìm tham số μ cực đại hóa hàm hợp lý của dữ liệu quan sát từ phân phối chuẩn Normal(μ, 1).
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Minh họa MLE&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;true-mu-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;μ thực: &lt;span id=&quot;true-mu-value&quot;&gt;2.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;true-mu-slider&quot; min=&quot;-2&quot; max=&quot;4&quot; step=&quot;0.1&quot; value=&quot;2.0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;sample-size-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;Kích thước mẫu: &lt;span id=&quot;sample-size-value&quot;&gt;20&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;sample-size-slider&quot; min=&quot;5&quot; max=&quot;100&quot; step=&quot;5&quot; value=&quot;20&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;button id=&quot;generate-mle-data&quot; style=&quot;width: 100%; padding: 10px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer; margin-bottom: 15px;&quot;&gt;Tạo dữ liệu &amp;amp; Tìm MLE&lt;/button&gt;
                
                &lt;div id=&quot;mle-results&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Kết quả:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;μ thực: &lt;span id=&quot;display-true-mu&quot;&gt;2.000&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Trung bình mẫu: &lt;span id=&quot;sample-mean&quot;&gt;--&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Ước lượng MLE: &lt;span id=&quot;mle-estimate&quot;&gt;--&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Sai số: &lt;span id=&quot;mle-error&quot;&gt;--&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;điểm-chính-cần-nhớ&quot;&gt;Điểm chính cần nhớ&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nền tảng:&lt;/strong&gt; các tiên đề xác suất tạo khung toán học chặt chẽ để xử lý sự bất định.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác suất có điều kiện:&lt;/strong&gt; công cụ cốt lõi để cập nhật niềm tin khi có thông tin mới.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính độc lập:&lt;/strong&gt; giúp đơn giản hóa phép tính và các giả định mô hình.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biến ngẫu nhiên:&lt;/strong&gt; cầu nối giữa không gian mẫu trừu tượng và các đại lượng số cụ thể.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Liên hệ với tối ưu hóa:&lt;/strong&gt; nhiều bài toán tối ưu hóa phát sinh trực tiếp từ mô hình xác suất.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Nắm vững các khái niệm nền tảng này giúp bạn tiếp cận thuận lợi những chủ đề nâng cao hơn như suy luận Bayes, ước lượng hợp lý cực đại và tối ưu hóa ngẫu nhiên — các thành phần cốt lõi của học máy và khoa học dữ liệu hiện đại.&lt;/p&gt;

&lt;script&gt;
class MLEDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;deep-learningCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.trueMu = 2.0;
        this.sampleSize = 20;
        this.data = [];
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const trueMuSlider = document.getElementById(&apos;true-mu-slider&apos;);
        const sampleSizeSlider = document.getElementById(&apos;sample-size-slider&apos;);
        const generateBtn = document.getElementById(&apos;generate-mle-data&apos;);
        
        trueMuSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.trueMu = parseFloat(e.target.value);
            document.getElementById(&apos;true-mu-value&apos;).textContent = this.trueMu.toFixed(1);
            document.getElementById(&apos;display-true-mu&apos;).textContent = this.trueMu.toFixed(3);
        });
        
        sampleSizeSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.sampleSize = parseInt(e.target.value);
            document.getElementById(&apos;sample-size-value&apos;).textContent = this.sampleSize;
        });
        
        generateBtn.addEventListener(&apos;click&apos;, () =&gt; this.generateDataAndFindMLE());
    }
    
    generateDataAndFindMLE() {
        // Generate data from Normal(trueMu, 1)
        this.data = [];
        for (let i = 0; i &lt; this.sampleSize; i++) {
            // Box-Muller transform for normal distribution
            const u1 = Math.random();
            const u2 = Math.random();
            const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
            this.data.push(this.trueMu + z); // Normal(trueMu, 1)
        }
        
        // Calculate MLE (sample mean for normal distribution)
        const sampleMean = this.data.reduce((sum, x) =&gt; sum + x, 0) / this.data.length;
        const error = Math.abs(sampleMean - this.trueMu);
        
        // Update display
        document.getElementById(&apos;sample-mean&apos;).textContent = sampleMean.toFixed(3);
        document.getElementById(&apos;mle-estimate&apos;).textContent = sampleMean.toFixed(3);
        document.getElementById(&apos;mle-error&apos;).textContent = error.toFixed(3);
        
        this.draw();
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        if (this.data.length === 0) {
            this.ctx.fillStyle = &apos;#666&apos;;
            this.ctx.font = &apos;16px Arial&apos;;
            this.ctx.textAlign = &apos;center&apos;;
            this.ctx.fillText(&apos;Nhấp &quot;Tạo Dữ Liệu &amp; Tìm MLE&quot; để bắt đầu&apos;, this.width / 2, this.height / 2);
            return;
        }
        
        // Draw axes
        this.ctx.strokeStyle = &apos;#ddd&apos;;
        this.ctx.lineWidth = 1;
        const marginX = 50;
        const marginY = 50;
        const plotWidth = this.width - 2 * marginX;
        const plotHeight = this.height - 2 * marginY;
        
        // X-axis
        this.ctx.beginPath();
        this.ctx.moveTo(marginX, this.height - marginY);
        this.ctx.lineTo(this.width - marginX, this.height - marginY);
        this.ctx.stroke();
        
        // Y-axis
        this.ctx.beginPath();
        this.ctx.moveTo(marginX, marginY);
        this.ctx.lineTo(marginX, this.height - marginY);
        this.ctx.stroke();
        
        // Find data range
        const minX = Math.min(...this.data) - 1;
        const maxX = Math.max(...this.data) + 1;
        
        // Draw likelihood function
        this.ctx.strokeStyle = &apos;#2196f3&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        
        for (let i = 0; i &lt;= 100; i++) {
            const mu = minX + (maxX - minX) * i / 100;
            let logLikelihood = 0;
            
            // Calculate log-likelihood
            for (const x of this.data) {
                logLikelihood -= 0.5 * Math.log(2 * Math.PI);
                logLikelihood -= 0.5 * (x - mu) * (x - mu);
            }
            
            const x = marginX + (mu - minX) / (maxX - minX) * plotWidth;
            const y = this.height - marginY - (logLikelihood - (-this.data.length * 2)) / (this.data.length) * plotHeight * 0.8;
            
            if (i === 0) {
                this.ctx.moveTo(x, y);
            } else {
                this.ctx.lineTo(x, y);
            }
        }
        this.ctx.stroke();
        
        // Mark MLE
        const sampleMean = this.data.reduce((sum, x) =&gt; sum + x, 0) / this.data.length;
        const mleX = marginX + (sampleMean - minX) / (maxX - minX) * plotWidth;
        
        this.ctx.strokeStyle = &apos;#f44336&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        this.ctx.moveTo(mleX, marginY);
        this.ctx.lineTo(mleX, this.height - marginY);
        this.ctx.stroke();
        
        // Mark true value
        const trueX = marginX + (this.trueMu - minX) / (maxX - minX) * plotWidth;
        this.ctx.strokeStyle = &apos;#4caf50&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.setLineDash([5, 5]);
        this.ctx.beginPath();
        this.ctx.moveTo(trueX, marginY);
        this.ctx.lineTo(trueX, this.height - marginY);
        this.ctx.stroke();
        this.ctx.setLineDash([]);
        
        // Draw data points
        this.ctx.fillStyle = &apos;#666&apos;;
        for (const x of this.data) {
            const pointX = marginX + (x - minX) / (maxX - minX) * plotWidth;
            this.ctx.beginPath();
            this.ctx.arc(pointX, this.height - marginY + 10, 2, 0, 2 * Math.PI);
            this.ctx.fill();
        }
        
        // Labels
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;12px Arial&apos;;
        this.ctx.textAlign = &apos;center&apos;;
        this.ctx.fillText(&apos;μ&apos;, this.width / 2, this.height - 10);
        
        this.ctx.save();
        this.ctx.translate(15, this.height / 2);
        this.ctx.rotate(-Math.PI / 2);
        this.ctx.fillText(&apos;Log-Likelihood&apos;, 0, 0);
        this.ctx.restore();
        
        // Legend
        this.ctx.textAlign = &apos;left&apos;;
        this.ctx.fillText(&apos;— Likelihood&apos;, 10, 20);
        this.ctx.fillStyle = &apos;#f44336&apos;;
        this.ctx.fillText(&apos;— MLE&apos;, 10, 35);
        this.ctx.fillStyle = &apos;#4caf50&apos;;
        this.ctx.fillText(&apos;--- μ Thực&apos;, 10, 50);
    }
}

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new MLEDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=bvBukLjHZh8&quot;&gt;MaDL - Random Variables and Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Trình bày biến ngẫu nhiên dưới dạng hàm trên không gian mẫu, khớp với cách mô hình hóa dữ liệu và dự đoán trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=lHCpYeFvTs0&quot;&gt;Random Variables and Probability Distributions&lt;/a&gt; — Dr Nic’s Maths and Stats, tiếng Anh. Giới thiệu ngắn gọn về biến ngẫu nhiên rời rạc và liên tục trước khi đi vào các phân phối cụ thể.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kmRm3XIND8M&quot;&gt;MaDL - Expectation, Variance and Covariance&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Giải thích kỳ vọng, phương sai và hiệp phương sai — các đại lượng đặc trưng dùng khi đầu ra mạng nơ-ron mang tính xác suất.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-01-02 Xác Suất Có Điều Kiện và Tính Độc Lập</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_01_02_Conditional_Probability_and_Independence/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_01_02_Conditional_Probability_and_Independence</id>
   <content type="html">&lt;p&gt;Nếu một xét nghiệm y khoa AI có độ chính xác 99% báo bạn dương tính với một căn bệnh hiếm gặp (chỉ 1 trên 1{,}000 người mắc), khả năng thực sự bạn bị bệnh có phải là 99% không? Câu trả lời gây sốc cho hầu hết mọi người là &lt;strong&gt;chỉ khoảng 9%!&lt;/strong&gt; Nghịch lý nổi tiếng ấy cho thấy trực giác con người rất dễ sụp đổ khi đối mặt với &lt;strong&gt;xác suất có điều kiện&lt;/strong&gt; và &lt;strong&gt;định lý Bayes&lt;/strong&gt;. Trong Deep Learning, việc hiểu chính xác \(P(y \mid \mathbf{x})\), giả định độc lập có điều kiện và suy luận Bayes giúp bạn thiết kế bài toán phân loại dữ liệu mất cân bằng đúng đắn ngay từ đầu.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-trụ-cột-của-xác-suất-có-điều-kiện-và-tính-độc-lập&quot;&gt;Kiến thức cần nhớ: Bốn trụ cột của Xác suất Có điều kiện và Tính Độc lập&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Xác suất có điều kiện (\(P(A \mid B) = \frac{P(A \cap B)}{P(B)}\))&lt;/strong&gt;:
Thu hẹp không gian mẫu từ \(\Omega\) xuống còn đúng vùng biến cố \(B\) đã xảy ra—mọi mô hình phân biệt (&lt;em&gt;discriminative model&lt;/em&gt;) đều trực tiếp học \(P(y \mid \mathbf{x})\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Định lý Bayes (Bayes’ Theorem)&lt;/strong&gt;:
Đảo chiều điều kiện từ \(P(\mathbf{x} \mid y)\) sang \(P(y \mid \mathbf{x}) = \frac{P(\mathbf{x} \mid y)P(y)}{P(\mathbf{x})}\), kết nối xác suất tiên nghiệm (&lt;em&gt;prior&lt;/em&gt;) với bằng chứng dữ liệu (&lt;em&gt;likelihood&lt;/em&gt;) để tạo thành hậu nghiệm (&lt;em&gt;posterior&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tính độc lập và Độc lập có điều kiện&lt;/strong&gt;:
Hai biến cố độc lập thỏa \(P(A \cap B) = P(A)P(B)\). Trong huấn luyện mạng nơ-ron, giả định các mẫu dữ liệu độc lập cho phép tách tích xác suất toàn tập thành tổng các log-loss riêng lẻ.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Định lý Xác suất Toàn phần (Law of Total Probability)&lt;/strong&gt;:
Tính xác suất biên \(P(A) = \sum_i P(A \mid B_i)P(B_i)\) bằng cách cộng theo từng kịch bản—cốt lõi của cơ chế biên hóa biến ẩn (&lt;em&gt;latent variables&lt;/em&gt;) trong mô hình sinh.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-giải-tay-nghịch-lý-chẩn-đoán-bệnh-hiếm-bằng-định-lý-bayes&quot;&gt;Giải thích: Giải tay nghịch lý chẩn đoán bệnh hiếm bằng Định lý Bayes&lt;/h3&gt;

&lt;p&gt;Xét một bộ sàng lọc AI cho căn bệnh hiếm có tỷ lệ mắc trong dân số \(P(D) = 0.001\) (tức \(P(\neg D) = 0.999\)). Mô hình có độ nhạy \(P(+ \mid D) = 0.99\) và tỷ lệ dương tính giả \(P(+ \mid \neg D) = 0.01\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính xác suất ra kết quả dương tính (Xác suất toàn phần)&lt;/strong&gt;:
\(P(+) = P(+ \mid D)P(D) + P(+ \mid \neg D)P(\neg D) = 0.99 \times 0.001 + 0.01 \times 0.999 = 0.00099 + 0.00999 = 0.01098.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Áp dụng Định lý Bayes tìm xác suất thực sự mắc bệnh khi có kết quả dương tính&lt;/strong&gt;:
\(P(D \mid +) = \frac{P(+ \mid D)P(D)}{P(+)} = \frac{0.00099}{0.01098} \approx 0.0902 \quad (9.02\%).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bài học thực chiến cho Deep Learning&lt;/strong&gt;: Dù độ nhạy và độ đặc hiệu đều đạt 99%, vì lớp âm áp đảo gấp 999 lần, số ca báo động giả (\(0.00999\)) vẫn gấp 10 lần số ca bệnh thật (\(0.00099\))! Đó là lý do trên tập dữ liệu mất cân bằng, ta không bao giờ chỉ nhìn vào Accuracy mà phải theo dõi Precision, Recall và PR-AUC.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;4-xác-suất-có-điều-kiện&quot;&gt;4. Xác suất có điều kiện&lt;/h3&gt;

&lt;p&gt;Xác suất để biến cố \(A\) xảy ra khi biết biến cố \(B\) đã xảy ra được định nghĩa là:&lt;/p&gt;

\[P(A|B) = \frac{P(A \cap B)}{P(B)}, \quad P(B) &amp;gt; 0\]

&lt;p&gt;&lt;strong&gt;Ý nghĩa:&lt;/strong&gt; Xác suất có điều kiện cập nhật mức độ tin cậy của ta về biến cố \(A\) sau khi có thêm thông tin rằng \(B\) đã xảy ra.&lt;/p&gt;

&lt;div id=&quot;conditional-prob-demo&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f9f9f9;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Trực quan hóa xác suất có điều kiện&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;conditionalCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;Biểu đồ Venn:&lt;/strong&gt; Hình tròn xanh biểu diễn biến cố A, hình tròn đỏ biểu diễn biến cố B, phần giao màu tím biểu diễn A ∩ B.
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Điều chỉnh xác suất&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;prob-a-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;P(A): &lt;span id=&quot;prob-a-value&quot;&gt;0.4&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;prob-a-slider&quot; min=&quot;0.1&quot; max=&quot;0.9&quot; step=&quot;0.05&quot; value=&quot;0.4&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;prob-b-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;P(B): &lt;span id=&quot;prob-b-value&quot;&gt;0.5&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;prob-b-slider&quot; min=&quot;0.1&quot; max=&quot;0.9&quot; step=&quot;0.05&quot; value=&quot;0.5&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;overlap-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;Phần giao: &lt;span id=&quot;overlap-value&quot;&gt;0.2&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;overlap-slider&quot; min=&quot;0&quot; max=&quot;0.4&quot; step=&quot;0.05&quot; value=&quot;0.2&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div id=&quot;conditional-results&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Xác suất:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;P(A) = &lt;span id=&quot;display-prob-a&quot;&gt;0.400&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(B) = &lt;span id=&quot;display-prob-b&quot;&gt;0.500&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(A ∩ B) = &lt;span id=&quot;display-prob-ab&quot;&gt;0.200&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(A ∪ B) = &lt;span id=&quot;display-prob-union&quot;&gt;0.700&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;&lt;strong&gt;Có điều kiện:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;P(A|B) = &lt;span id=&quot;display-prob-a-given-b&quot;&gt;0.400&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(B|A) = &lt;span id=&quot;display-prob-b-given-a&quot;&gt;0.500&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;5-tính-độc-lập&quot;&gt;5. Tính độc lập&lt;/h3&gt;

&lt;p&gt;Hai biến cố \(A\) và \(B\) được gọi là &lt;strong&gt;độc lập&lt;/strong&gt; nếu:
\(P(A \cap B) = P(A) \cdot P(B)\)&lt;/p&gt;

&lt;p&gt;Tương đương (khi \(P(A) &amp;gt; 0, P(B) &amp;gt; 0\)):
\(P(A|B) = P(A) \quad \text{và} \quad P(B|A) = P(B)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ý nghĩa:&lt;/strong&gt; Việc biết một biến cố đã xảy ra không làm thay đổi xác suất của biến cố còn lại.&lt;/p&gt;

&lt;script&gt;
class ConditionalProbDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;conditionalCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.probA = 0.4;
        this.probB = 0.5;
        this.overlap = 0.2;
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const probASlider = document.getElementById(&apos;prob-a-slider&apos;);
        const probBSlider = document.getElementById(&apos;prob-b-slider&apos;);
        const overlapSlider = document.getElementById(&apos;overlap-slider&apos;);
        
        probASlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.probA = parseFloat(e.target.value);
            document.getElementById(&apos;prob-a-value&apos;).textContent = this.probA.toFixed(1);
            this.updateCalculations();
            this.draw();
        });
        
        probBSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.probB = parseFloat(e.target.value);
            document.getElementById(&apos;prob-b-value&apos;).textContent = this.probB.toFixed(1);
            this.updateCalculations();
            this.draw();
        });
        
        overlapSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.overlap = parseFloat(e.target.value);
            document.getElementById(&apos;overlap-value&apos;).textContent = this.overlap.toFixed(1);
            // Ensure overlap doesn&apos;t exceed min(probA, probB)
            const maxOverlap = Math.min(this.probA, this.probB);
            if (this.overlap &gt; maxOverlap) {
                this.overlap = maxOverlap;
                overlapSlider.value = this.overlap;
                document.getElementById(&apos;overlap-value&apos;).textContent = this.overlap.toFixed(1);
            }
            this.updateCalculations();
            this.draw();
        });
        
        this.updateCalculations();
    }
    
    updateCalculations() {
        const probUnion = this.probA + this.probB - this.overlap;
        const probAGivenB = this.probB &gt; 0 ? this.overlap / this.probB : 0;
        const probBGivenA = this.probA &gt; 0 ? this.overlap / this.probA : 0;
        
        document.getElementById(&apos;display-prob-a&apos;).textContent = this.probA.toFixed(3);
        document.getElementById(&apos;display-prob-b&apos;).textContent = this.probB.toFixed(3);
        document.getElementById(&apos;display-prob-ab&apos;).textContent = this.overlap.toFixed(3);
        document.getElementById(&apos;display-prob-union&apos;).textContent = probUnion.toFixed(3);
        document.getElementById(&apos;display-prob-a-given-b&apos;).textContent = probAGivenB.toFixed(3);
        document.getElementById(&apos;display-prob-b-given-a&apos;).textContent = probBGivenA.toFixed(3);
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        // Draw universe rectangle
        this.ctx.strokeStyle = &apos;#000&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(50, 50, 300, 200);
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;14px Arial&apos;;
        this.ctx.fillText(&apos;Ω (Không gian mẫu)&apos;, 55, 45);
        
        // Calculate circle parameters
        const centerAX = 150;
        const centerAY = 150;
        const centerBX = 250;
        const centerBY = 150;
        
        // Calculate radii based on probabilities (area proportional to probability)
        const radiusA = Math.sqrt(this.probA * 10000 / Math.PI);
        const radiusB = Math.sqrt(this.probB * 10000 / Math.PI);
        
        // Draw circle A
        this.ctx.globalAlpha = 0.3;
        this.ctx.fillStyle = &apos;#2196f3&apos;;
        this.ctx.beginPath();
        this.ctx.arc(centerAX, centerAY, radiusA, 0, 2 * Math.PI);
        this.ctx.fill();
        
        // Draw circle B
        this.ctx.fillStyle = &apos;#f44336&apos;;
        this.ctx.beginPath();
        this.ctx.arc(centerBX, centerBY, radiusB, 0, 2 * Math.PI);
        this.ctx.fill();
        
        // Draw intersection (approximate)
        if (this.overlap &gt; 0) {
            this.ctx.fillStyle = &apos;#9c27b0&apos;;
            const overlapRadius = Math.sqrt(this.overlap * 5000 / Math.PI);
            this.ctx.beginPath();
            this.ctx.arc((centerAX + centerBX) / 2, (centerAY + centerBY) / 2, overlapRadius, 0, 2 * Math.PI);
            this.ctx.fill();
        }
        
        this.ctx.globalAlpha = 1.0;
        
        // Draw circle outlines
        this.ctx.strokeStyle = &apos;#2196f3&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        this.ctx.arc(centerAX, centerAY, radiusA, 0, 2 * Math.PI);
        this.ctx.stroke();
        
        this.ctx.strokeStyle = &apos;#f44336&apos;;
        this.ctx.beginPath();
        this.ctx.arc(centerBX, centerBY, radiusB, 0, 2 * Math.PI);
        this.ctx.stroke();
        
        // Labels
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;16px Arial&apos;;
        this.ctx.fillText(&apos;A&apos;, centerAX - 40, centerAY);
        this.ctx.fillText(&apos;B&apos;, centerBX + 30, centerBY);
        
        if (this.overlap &gt; 0) {
            this.ctx.fillText(&apos;A∩B&apos;, (centerAX + centerBX) / 2 - 15, (centerAY + centerBY) / 2 + 5);
        }
    }
}

// MLE Deep Learning Demo

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new ConditionalProbDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=_IgyaD7vOOA&quot;&gt;Conditional Probabilities, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Trình bày rõ định nghĩa $$P(A&lt;/td&gt;
          &lt;td&gt;B)$$ — khái niệm mở đầu của bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2nDYX8IKrwo&quot;&gt;Independence in Probability&lt;/a&gt; — Steve Brunton, tiếng Anh. Giải thích tính độc lập giữa hai biến cố khi xác suất có điều kiện trùng với xác suất biên.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Xác suất có điều kiện (Conditional probability)&lt;/td&gt;
          &lt;td&gt;Công thức nhân xác suất](https://www.youtube.com/watch?v=EsIW9oLsqiI) — TOÁN HỌC MUÔN NƠI, tiếng Việt. Bài giảng tiếng Việt trình bày xác suất có điều kiện cùng công thức nhân xác suất.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-01-01 Không Gian Mẫu và Tiên Đề Xác Suất</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_01_01_Sample_Spaces_and_Axioms/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_04_01_01_Sample_Spaces_and_Axioms</id>
   <content type="html">&lt;p&gt;Năm 1933, nhà toán học Andrey Kolmogorov đã làm một điều phi thường: chỉ bằng &lt;strong&gt;ba tiên đề ngắn gọn&lt;/strong&gt;, ông biến toàn bộ lĩnh vực xác suất—vốn trước đó chỉ xoay quanh các bài toán cờ bạc tung xúc xắc—thành một hệ thống giải tích chặt chẽ như hình học Euclid. Ngày nay, mỗi khi tầng Softmax ở cuối mạng phân loại ảnh ép đầu ra thành các con số nằm trong \([0, 1]\) và có tổng đúng bằng \(1\), nó đang tôn trọng chính xác ba tiên đề Kolmogorov ấy. Bài học này xây dựng nền móng không gian mẫu, biến cố và hệ tiên đề xác suất để bạn hiểu rõ ngôn ngữ gốc của mọi mô hình phân loại.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-của-không-gian-mẫu-và-tiên-đề-kolmogorov&quot;&gt;Kiến thức cần nhớ: Ba trụ cột của Không gian Mẫu và Tiên đề Kolmogorov&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Không gian mẫu (\(\Omega\)) và Biến cố (\(A \subseteq \Omega\))&lt;/strong&gt;:
Liệt kê toàn bộ kết cục có thể xảy ra (từ 10 lớp chữ số MNIST đến 50{,}000 token từ vựng của LLM); mỗi biến cố là một tập con chứa các kết cục ta quan tâm.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ba tiên đề Kolmogorov (Không âm, Chuẩn hóa, Cộng tính)&lt;/strong&gt;:
Mọi xác suất đều thỏa \(P(A) \ge 0\), \(P(\Omega) = 1\), và với các biến cố đôi một xung khắc (\(A_i \cap A_j = \emptyset\)), \(P(\bigcup_i A_i) = \sum_i P(A_i)\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Các hệ quả trực tiếp (Phần bù và Luật cộng tổng quát)&lt;/strong&gt;:
Tính xác suất “không xảy ra” bằng \(P(A^c) = 1 - P(A)\) và xử lý các biến cố chồng lấn bằng \(P(A \cup B) = P(A) + P(B) - P(A \cap B)\), tránh lỗi đếm trùng cực kỳ phổ biến khi phân tích sai số mô hình.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-kiểm-tra-tiên-đề-kolmogorov-trên-đầu-ra-softmax-và-lỗi-đếm-trùng&quot;&gt;Giải thích: Kiểm tra tiên đề Kolmogorov trên đầu ra Softmax và lỗi đếm trùng&lt;/h3&gt;

&lt;p&gt;Giả sử một bộ phân loại ảnh 3 lớp \(\Omega = \{\text{Mèo}, \text{Chó}, \text{Chim}\}\) xuất ra vector xác suất \(P(\text{Mèo}) = 0.65\), \(P(\text{Chó}) = 0.25\), \(P(\text{Chim}) = 0.10\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra ba tiên đề Kolmogorov&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Không âm: cả ba số đều \(\ge 0\).&lt;/li&gt;
      &lt;li&gt;Chuẩn hóa: \(0.65 + 0.25 + 0.10 = 1.00 = P(\Omega)\).&lt;/li&gt;
      &lt;li&gt;Cộng tính xung khắc: biến cố \(A = \{\text{Động vật bốn chân}\} = \{\text{Mèo}, \text{Chó}\}\) có \(P(A) = 0.65 + 0.25 = 0.90\), và phần bù \(P(A^c) = 1 - 0.90 = 0.10 = P(\text{Chim})\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xử lý hai biến cố &lt;em&gt;không&lt;/em&gt; xung khắc trên bộ kiểm thử&lt;/strong&gt;:
Trong 100 ảnh test, có 20 ảnh bị mờ (\(P(M) = 0.20\)), 15 ảnh thiếu sáng (\(P(T) = 0.15\)), và 6 ảnh vừa mờ vừa thiếu sáng (\(P(M \cap T) = 0.06\)).
    &lt;ul&gt;
      &lt;li&gt;Xác suất ảnh bị mờ &lt;strong&gt;hoặc&lt;/strong&gt; thiếu sáng là:
\(P(M \cup T) = 0.20 + 0.15 - 0.06 = 0.29 \quad (\text{không phải } 0.35!).\)&lt;/li&gt;
      &lt;li&gt;Xác suất ảnh sạch (không mờ, không thiếu sáng): \(1 - 0.29 = 0.71\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;lý-thuyết-xác-suất-cơ-bản&quot;&gt;Lý thuyết xác suất cơ bản&lt;/h2&gt;

&lt;p&gt;Lý thuyết xác suất cung cấp khung toán học để suy luận về sự bất định — nền tảng của nhiều bài toán tối ưu hóa trong học máy và khoa học dữ liệu.&lt;/p&gt;

&lt;h3 id=&quot;1-không-gian-mẫu-và-biến-cố&quot;&gt;1. Không gian mẫu và biến cố&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Không gian mẫu (\(\Omega\)):&lt;/strong&gt; tập hợp tất cả các kết quả có thể xảy ra của một phép thử ngẫu nhiên.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Biến cố (\(A\)):&lt;/strong&gt; một tập con của không gian mẫu, đại diện cho một nhóm kết quả cụ thể.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Tung đồng xu: \(\Omega = \{S, N\}\)&lt;/li&gt;
  &lt;li&gt;Tung xúc xắc: \(\Omega = \{1, 2, 3, 4, 5, 6\}\)&lt;/li&gt;
  &lt;li&gt;Phép thử liên tục: \(\Omega = [0, 1]\) đối với biến ngẫu nhiên phân phối đều&lt;/li&gt;
&lt;/ul&gt;

&lt;div id=&quot;sample-space-demo&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f9f9f9;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Trực quan hóa không gian mẫu tương tác&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;sampleSpaceCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;Trực quan hóa:&lt;/strong&gt; Nhấp để sinh mẫu ngẫu nhiên. Mỗi màu biểu thị một biến cố khác nhau.
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Loại phép thử&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;experiment&quot; value=&quot;coin&quot; checked=&quot;&quot; /&gt; Tung đồng xu
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;experiment&quot; value=&quot;dice&quot; /&gt; Tung xúc xắc
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;experiment&quot; value=&quot;uniform&quot; /&gt; Phân phối đều [0,1]
                    &lt;/label&gt;
                &lt;/div&gt;
                
                &lt;button id=&quot;generate-sample&quot; style=&quot;width: 100%; padding: 10px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; margin-bottom: 10px;&quot;&gt;Tạo mẫu&lt;/button&gt;
                &lt;button id=&quot;clear-samples&quot; style=&quot;width: 100%; padding: 8px; background: #6c757d; color: white; border: none; border-radius: 5px; cursor: pointer; margin-bottom: 15px;&quot;&gt;Xóa&lt;/button&gt;
                
                &lt;div id=&quot;sample-stats&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Thống kê:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;Tổng mẫu: &lt;span id=&quot;total-samples&quot;&gt;0&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Biến cố A: &lt;span id=&quot;event-a-count&quot;&gt;0&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Biến cố B: &lt;span id=&quot;event-b-count&quot;&gt;0&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(A) ≈ &lt;span id=&quot;prob-a&quot;&gt;0.000&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(B) ≈ &lt;span id=&quot;prob-b&quot;&gt;0.000&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;2-tiên-đề-xác-suất-tiên-đề-kolmogorov&quot;&gt;2. Tiên đề xác suất (Tiên đề Kolmogorov)&lt;/h3&gt;

&lt;p&gt;Mọi độ đo xác suất \(P\) đều phải thỏa mãn ba tiên đề sau:&lt;/p&gt;

&lt;h4 id=&quot;tiên-đề-1-tính-không-âm&quot;&gt;Tiên đề 1: Tính không âm&lt;/h4&gt;
&lt;p&gt;\(P(A) \geq 0 \text{ với mọi biến cố } A\)&lt;/p&gt;

&lt;h4 id=&quot;tiên-đề-2-chuẩn-hóa&quot;&gt;Tiên đề 2: Chuẩn hóa&lt;/h4&gt;
&lt;p&gt;\(P(\Omega) = 1\)&lt;/p&gt;

&lt;h4 id=&quot;tiên-đề-3-tính-cộng-đếm-được&quot;&gt;Tiên đề 3: Tính cộng đếm được&lt;/h4&gt;
&lt;p&gt;Với dãy các biến cố đôi một xung khắc \(A_1, A_2, \ldots\):
\(P\left(\bigcup_{i=1}^{\infty} A_i\right) = \sum_{i=1}^{\infty} P(A_i)\)&lt;/p&gt;

&lt;h3 id=&quot;3-tính-chất-và-quy-tắc-cơ-bản&quot;&gt;3. Tính chất và quy tắc cơ bản&lt;/h3&gt;

&lt;h4 id=&quot;quy-tắc-phần-bù&quot;&gt;Quy tắc phần bù&lt;/h4&gt;
&lt;p&gt;\(P(A^c) = 1 - P(A)\)&lt;/p&gt;

&lt;h4 id=&quot;quy-tắc-cộng&quot;&gt;Quy tắc cộng&lt;/h4&gt;
&lt;p&gt;Với hai biến cố \(A\) và \(B\) bất kỳ:
\(P(A \cup B) = P(A) + P(B) - P(A \cap B)\)&lt;/p&gt;

&lt;h4 id=&quot;quy-tắc-nhân&quot;&gt;Quy tắc nhân&lt;/h4&gt;
&lt;p&gt;\(P(A \cap B) = P(A|B) \cdot P(B) = P(B|A) \cdot P(A)\)&lt;/p&gt;

&lt;script&gt;
class SampleSpaceDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;sampleSpaceCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.samples = [];
        this.experimentType = &apos;coin&apos;;
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const radios = document.querySelectorAll(&apos;input[name=&quot;experiment&quot;]&apos;);
        const generateBtn = document.getElementById(&apos;generate-sample&apos;);
        const clearBtn = document.getElementById(&apos;clear-samples&apos;);
        
        radios.forEach(radio =&gt; {
            radio.addEventListener(&apos;change&apos;, (e) =&gt; {
                this.experimentType = e.target.value;
                this.samples = [];
                this.updateStats();
                this.draw();
            });
        });
        
        generateBtn.addEventListener(&apos;click&apos;, () =&gt; this.generateSample());
        clearBtn.addEventListener(&apos;click&apos;, () =&gt; {
            this.samples = [];
            this.updateStats();
            this.draw();
        });
        
        this.canvas.addEventListener(&apos;click&apos;, () =&gt; this.generateSample());
    }
    
    generateSample() {
        let sample;
        
        switch(this.experimentType) {
            case &apos;coin&apos;:
                sample = {
                    value: Math.random() &lt; 0.5 ? &apos;S&apos; : &apos;N&apos;,
                    x: Math.random() * (this.width - 40) + 20,
                    y: Math.random() * (this.height - 40) + 20,
                    eventA: Math.random() &lt; 0.5, // Biến cố A: Sấp
                    eventB: Math.random() &lt; 0.3  // Biến cố B: May mắn
                };
                break;
            case &apos;dice&apos;:
                const diceValue = Math.floor(Math.random() * 6) + 1;
                sample = {
                    value: diceValue,
                    x: Math.random() * (this.width - 40) + 20,
                    y: Math.random() * (this.height - 40) + 20,
                    eventA: diceValue &gt;= 4, // Biến cố A: 4, 5, hoặc 6
                    eventB: diceValue % 2 === 0 // Biến cố B: Chẵn
                };
                break;
            case &apos;uniform&apos;:
                const uniformValue = Math.random();
                sample = {
                    value: uniformValue.toFixed(3),
                    x: uniformValue * (this.width - 40) + 20,
                    y: Math.random() * (this.height - 40) + 20,
                    eventA: uniformValue &gt; 0.5, // Biến cố A: &gt; 0.5
                    eventB: uniformValue &lt; 0.7  // Biến cố B: &lt; 0.7
                };
                break;
        }
        
        this.samples.push(sample);
        this.updateStats();
        this.draw();
    }
    
    updateStats() {
        const total = this.samples.length;
        const eventACount = this.samples.filter(s =&gt; s.eventA).length;
        const eventBCount = this.samples.filter(s =&gt; s.eventB).length;
        
        document.getElementById(&apos;total-samples&apos;).textContent = total;
        document.getElementById(&apos;event-a-count&apos;).textContent = eventACount;
        document.getElementById(&apos;event-b-count&apos;).textContent = eventBCount;
        document.getElementById(&apos;prob-a&apos;).textContent = total &gt; 0 ? (eventACount / total).toFixed(3) : &apos;0.000&apos;;
        document.getElementById(&apos;prob-b&apos;).textContent = total &gt; 0 ? (eventBCount / total).toFixed(3) : &apos;0.000&apos;;
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        // Draw background
        this.ctx.fillStyle = &apos;#f8f9fa&apos;;
        this.ctx.fillRect(0, 0, this.width, this.height);
        
        // Draw samples
        this.samples.forEach(sample =&gt; {
            // Determine color based on events
            let color = &apos;#666&apos;;
            if (sample.eventA &amp;&amp; sample.eventB) color = &apos;#9c27b0&apos;; // Cả hai biến cố
            else if (sample.eventA) color = &apos;#2196f3&apos;; // Chỉ biến cố A
            else if (sample.eventB) color = &apos;#f44336&apos;; // Chỉ biến cố B
            
            this.ctx.fillStyle = color;
            this.ctx.beginPath();
            this.ctx.arc(sample.x, sample.y, 5, 0, 2 * Math.PI);
            this.ctx.fill();
            
            // Draw value
            this.ctx.fillStyle = &apos;#000&apos;;
            this.ctx.font = &apos;10px Arial&apos;;
            this.ctx.textAlign = &apos;center&apos;;
            this.ctx.fillText(sample.value, sample.x, sample.y - 8);
        });
        
        // Draw legend
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;12px Arial&apos;;
        this.ctx.textAlign = &apos;left&apos;;
        this.ctx.fillText(&apos;Chú thích:&apos;, 10, 20);
        
        this.ctx.fillStyle = &apos;#2196f3&apos;;
        this.ctx.beginPath();
        this.ctx.arc(20, 35, 4, 0, 2 * Math.PI);
        this.ctx.fill();
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.fillText(&apos;Chỉ biến cố A&apos;, 30, 38);
        
        this.ctx.fillStyle = &apos;#f44336&apos;;
        this.ctx.beginPath();
        this.ctx.arc(20, 50, 4, 0, 2 * Math.PI);
        this.ctx.fill();
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.fillText(&apos;Chỉ biến cố B&apos;, 30, 53);
        
        this.ctx.fillStyle = &apos;#9c27b0&apos;;
        this.ctx.beginPath();
        this.ctx.arc(20, 65, 4, 0, 2 * Math.PI);
        this.ctx.fill();
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.fillText(&apos;Cả A và B&apos;, 30, 68);
    }
}

// Conditional Probability Visualization

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new SampleSpaceDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pA83XtLeVig&quot;&gt;L01.4 Probability Axioms&lt;/a&gt; — MIT OpenCourseWare, tiếng Anh. Trình bày không gian mẫu, biến cố và ba tiên đề xác suất tương ứng trực tiếp với nội dung bài này.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=oI3hZJqXJuc&quot;&gt;The Main Ideas behind Probability Distributions&lt;/a&gt; — StatQuest with Josh Starmer, tiếng Anh. Giải thích cách độ đo xác suất trên không gian mẫu hình thành nên một phân phối xác suất.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Minh họa trực quan định lý Bayes — hệ quả trực tiếp của các tiên đề xác suất khi các biến cố phụ thuộc nhau.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-03 Giải tích thực và Lý thuyết tập hợp</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_03_Real_Analysis_and_Set_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_03_Real_Analysis_and_Set_Theory</id>
   <content type="html">&lt;p&gt;Khi viết một bài toán tối ưu như \(\min_{\theta \in \Theta} L(\theta)\), chúng ta thường mặc nhiên giả định rằng nghiệm nhỏ nhất &lt;em&gt;chắc chắn tồn tại&lt;/em&gt; và chuỗi cập nhật \(\theta_1, \theta_2, \dots\) sẽ tiến về đâu đó có nghĩa. Nhưng trên thực tế, một hàm số trên tập mở hoàn toàn có thể không bao giờ đạt cực tiểu (ví dụ \(f(x) = x\) trên \((0, 1)\) không có giá trị nhỏ nhất!). Giải tích thực và lý thuyết tập hợp cung cấp khung ngôn ngữ chính xác về tập đóng, tập mở, tính compact và sự hội tụ—những bảo chứng thầm lặng đằng sau mọi định lý tối ưu hóa và học máy lý thuyết.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-của-lý-thuyết-tập-hợp-và-giải-tích-thực&quot;&gt;Kiến thức cần nhớ: Ba trụ cột của Lý thuyết Tập hợp và Giải tích Thực&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lý thuyết tập hợp và Ánh xạ (Sets &amp;amp; Functions)&lt;/strong&gt;:
Xây dựng ngôn ngữ chuẩn hóa để biểu diễn không gian mẫu, tập dữ liệu huấn luyện/kiểm thử, miền tham số khả thi và các ánh xạ tầng mạng nơ-ron \(f: \mathbb{R}^d \to \mathbb{R}^k\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Không gian Metric và Tôpô trong \(\mathbb{R}^n\) (Open, Closed, Boundary)&lt;/strong&gt;:
Định nghĩa khái niệm “gần nhau” thông qua khoảng cách, hình cầu mở và lân cận—cần thiết để phát biểu cực trị địa phương, miền hội tụ và lân cận nhiễu đối kháng (&lt;em&gt;adversarial ball&lt;/em&gt; \(\|\delta\|_p \le \varepsilon\)).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tính Compact và Định lý Weierstrass&lt;/strong&gt;:
Trong \(\mathbb{R}^n\), tập vừa đóng vừa bị chặn là tập compact; mọi hàm liên tục trên tập compact đều đạt giá trị lớn nhất và nhỏ nhất—bảo chứng cốt lõi cho sự tồn tại nghiệm của bài toán tối ưu có ràng buộc.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-sự-tồn-tại-cực-tiểu-trên-tập-mở-và-tập-đóng&quot;&gt;Giải thích: So sánh sự tồn tại cực tiểu trên tập mở và tập đóng&lt;/h3&gt;

&lt;p&gt;Xét hàm đơn giản \(f(x) = \frac{1}{x} + x\) trên hai miền khác nhau:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Trên tập mở \((0, 2)\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Đạo hàm \(f&apos;(x) = 1 - \frac{1}{x^2} = 0 \iff x = 1 \in (0, 2)\), cho cực tiểu \(f(1) = 2\).&lt;/li&gt;
      &lt;li&gt;Tuy nhiên, nếu hỏi &lt;strong&gt;cực đại&lt;/strong&gt; trên \((0, 2)\): khi \(x \to 0^+\) thì \(f(x) \to +\infty\) nên không có cực đại!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xét hàm \(g(x) = x^2\) trên tập mở \((1, 3)\) so với tập đóng \([1, 3]\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Trên \((1, 3)\): giá trị \(g(x)\) có thể tiến sát \(1\) tùy ý (như \(g(1.001) = 1.002001\)), nhưng không tồn tại điểm \(x^* \in (1, 3)\) nào đạt đúng \(1\) vì điểm biên \(1\) không thuộc tập.&lt;/li&gt;
      &lt;li&gt;Trên tập compact \([1, 3]\): điểm biên nằm trong tập, nên \(g\) chắc chắn đạt cực tiểu tại \(x^* = 1\) (\(g(1) = 1\)) và cực đại tại \(x^* = 3\) (\(g(3) = 9\)).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Khi bạn thêm ràng buộc chuẩn trọng số \(\|\theta\|_2 \le R\) trong huấn luyện mạng nơ-ron, bạn đang biến miền tìm kiếm thành một &lt;strong&gt;hình cầu đóng và bị chặn (compact)&lt;/strong&gt; để bài toán tối ưu luôn có nghiệm xác định!&lt;/p&gt;

&lt;p&gt;Phần này trình bày các khái niệm nền tảng từ giải tích thực và lý thuyết tập hợp phục vụ cho tối ưu hóa, được chia thành hai bài học chính.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Intro to Sets&lt;/td&gt;
          &lt;td&gt;Examples, Notation &amp;amp; Properties](https://www.youtube.com/watch?v=B1v2-nGXNzs) — Dr. Trefor Bazett, tiếng Anh. Giới thiệu tập hợp, phần tử và hàm số — ngôn ngữ cơ bản dùng trong bài lý thuyết tập hợp.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Intro to Open Sets (with Examples)&lt;/td&gt;
          &lt;td&gt;Real Analysis](https://www.youtube.com/watch?v=pnWgj8jjs3w) — Wrath of Math, tiếng Anh. Giải thích khái niệm tập mở, đối tượng tôpô đầu tiên của bài thứ hai.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Limits, L’Hôpital’s rule, and epsilon delta definitions&lt;/td&gt;
          &lt;td&gt;Chapter 7, Essence of calculus](https://www.youtube.com/watch?v=kfF40MiS7zA) — 3Blue1Brown, tiếng Anh. Trình bày định nghĩa giới hạn và liên tục kiểu \(\varepsilon\text{-}\delta\) trong phần giải tích thực.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-03-02 Tôpô trong Giải tích thực</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_03_02_Topology_in_Real_Analysis/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_03_02_Topology_in_Real_Analysis</id>
   <content type="html">&lt;p&gt;Trong bảo mật AI hiện đại, một bức ảnh gấu trúc chỉ cần cộng thêm một nhiễu vô hình có chuẩn nhỏ hơn \(\varepsilon = 8/255\) đã có thể đánh lừa mạng nơ-ron nhận nhầm thành vượn cáo. Câu hỏi &lt;em&gt;“tất cả những bức ảnh nằm trong bán kính \(\varepsilon\) quanh ảnh gốc có hình thù thế nào?”&lt;/em&gt; chính là một câu hỏi của &lt;strong&gt;tôpô trong không gian metric&lt;/strong&gt;. Bằng cách hiểu rõ hình cầu mở, tập đóng, điểm biên, tính lồi và tính compact, bạn sẽ nhìn thấy khung hình học đứng sau cả tối ưu hóa lẫn độ bền vững của mạng nơ-ron.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-khái-niệm-tôpô-thiết-yếu-trong-giải-tích-thực&quot;&gt;Kiến thức cần nhớ: Bốn khái niệm Tôpô thiết yếu trong Giải tích Thực&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Không gian Metric và Hình cầu mở (Metric Spaces &amp;amp; Open Balls)&lt;/strong&gt;:
Tổng quát hóa khái niệm khoảng cách (Euclid \(L_2\), Manhattan \(L_1\), Chebyshev \(L_\infty\)). Mỗi chuẩn tạo ra một “hình cầu” khác nhau: hình tròn (\(L_2\)), hình thoi (\(L_1\)), và hình vuông/siêu lập phương (\(L_\infty\)—chuẩn phổ biến nhất trong tấn công đối kháng).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tập mở, Tập đóng và Điểm biên (Open, Closed, Boundary)&lt;/strong&gt;:
Tập mở cho phép di chuyển tự do một chút theo mọi hướng mà không rời khỏi tập (điều kiện để tính đạo hàm nội điểm); tập đóng chứa trọn đường biên của nó nên mọi dãy hội tụ trong tập không bị “rơi ra ngoài”.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tính Compact (Định lý Heine–Borel trong \(\mathbb{R}^n\))&lt;/strong&gt;:
Tập đóng và bị chặn đảm bảo mọi dãy đều có dãy con hội tụ và mọi hàm liên tục đều đạt cực tiểu/cực đại toàn cục trên tập đó.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Liên hệ với Tối ưu hóa Lồi và Regularization&lt;/strong&gt;:
Ràng buộc trọng số \(\|\mathbf{w}\|_2 \le C\) hay \(\|\mathbf{w}\|_1 \le C\) chính là các tập compact lồi; nghiệm tối ưu thường rơi đúng lên &lt;strong&gt;biên&lt;/strong&gt; của tập này (và ở các góc nhọn của hình thoi \(L_1\), tạo nên trọng số bằng \(0\)).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-tay-3-hình-cầu-bán-kính-r--1-quanh-gốc-tọa-độ&quot;&gt;Giải thích: So sánh tay 3 hình cầu bán kính \(r = 1\) quanh gốc tọa độ&lt;/h3&gt;

&lt;p&gt;Xét điểm thử \(\mathbf{p} = (0.7, 0.7)\) trong \(\mathbb{R}^2\). Hãy kiểm tra xem \(\mathbf{p}\) có nằm trong hình cầu mở đơn vị \(B(\mathbf{0}, 1) = \{\mathbf{x} : \|\mathbf{x}\| &amp;lt; 1\}\) ứng với ba chuẩn khác nhau hay không:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Chuẩn (Metric)&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Công thức khoảng cách từ \(\mathbf{0}\) tới \(\mathbf{p} = (0.7, 0.7)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Kết quả số&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Thuộc hình cầu mở \(B(\mathbf{0}, 1)\)?&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Chuẩn \(L_1\) (Manhattan)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\lvert 0.7 \rvert + \lvert 0.7 \rvert\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1.40\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Không&lt;/strong&gt; (\(1.40 &amp;gt; 1\), nằm ngoài hình thoi)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Chuẩn \(L_2\) (Euclid)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\sqrt{0.7^2 + 0.7^2} = \sqrt{0.98}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(\approx 0.990\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Có&lt;/strong&gt; (\(0.990 &amp;lt; 1\), nằm sát biên trong hình tròn)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Chuẩn \(L_\infty\) (Chebyshev)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(\max(\lvert 0.7 \rvert, \lvert 0.7 \rvert)\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.70\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;&lt;strong&gt;Có&lt;/strong&gt; (\(0.70 &amp;lt; 1\), nằm sâu trong hình vuông)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Từ phép tính nhỏ này ta thấy ngay quan hệ bao hàm tôpô tổng quát trên \(\mathbb{R}^n\): \(B_{L_1}(\mathbf{0}, 1) \subset B_{L_2}(\mathbf{0}, 1) \subset B_{L_\infty}(\mathbf{0}, 1)\). Đó cũng là lý do cùng một ngân sách nhiễu \(\varepsilon\), không gian tấn công theo chuẩn \(L_\infty\) rộng lớn hơn rất nhiều so với \(L_2\) và \(L_1\).&lt;/p&gt;

&lt;p&gt;Bài học này trình bày các khái niệm tôpô (&lt;em&gt;topology&lt;/em&gt;) cốt lõi trong giải tích thực — nền tảng để phân tích cấu trúc miền khả thi, tính liên tục và sự tồn tại nghiệm tối ưu.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-về-tôpô&quot;&gt;Giới thiệu về tôpô&lt;/h2&gt;

&lt;p&gt;Tôpô nghiên cứu các tính chất của không gian được bảo toàn qua những phép biến dạng liên tục. Trong tối ưu hóa, ngôn ngữ tôpô giúp ta mô tả chính xác cấu trúc của miền khả thi và hành vi của hàm mục tiêu, đặc biệt khi xét sự tồn tại và đặc trưng của nghiệm tối ưu.&lt;/p&gt;

&lt;h3 id=&quot;không-gian-metric-và-khoảng-cách&quot;&gt;Không gian metric và khoảng cách&lt;/h3&gt;

&lt;p&gt;Trước khi xét các khái niệm tôpô, ta cần định nghĩa khoảng cách. Trong \(\mathbb{R}^n\), &lt;strong&gt;khoảng cách Euclid&lt;/strong&gt; chuẩn giữa hai điểm \(\mathbf{x}\) và \(\mathbf{y}\) là:&lt;/p&gt;

\[d(\mathbf{x}, \mathbf{y}) = \|\mathbf{x} - \mathbf{y}\|_2 = \sqrt{\sum_{i=1}^n (x_i - y_i)^2}\]

&lt;h3 id=&quot;hình-cầu-mở-và-lân-cận&quot;&gt;Hình cầu mở và lân cận&lt;/h3&gt;

&lt;p&gt;Một &lt;strong&gt;hình cầu mở&lt;/strong&gt; (&lt;em&gt;open ball&lt;/em&gt;) tâm \(\mathbf{x}_0\) bán kính \(\epsilon &amp;gt; 0\) được định nghĩa là:&lt;/p&gt;

\[B(\mathbf{x}_0, \epsilon) = \{\mathbf{y} \in \mathbb{R}^n : d(\mathbf{x}_0, \mathbf{y}) &amp;lt; \epsilon\}\]

&lt;p&gt;Tập này chứa mọi điểm có khoảng cách tới \(\mathbf{x}_0\) nhỏ hơn ngặt \(\epsilon\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Trong \(\mathbb{R}\): \(B(0, 1) = (-1, 1)\) (khoảng mở).&lt;/li&gt;
  &lt;li&gt;Trong \(\mathbb{R}^2\): \(B(\mathbf{0}, 1) = \{(x, y) : x^2 + y^2 &amp;lt; 1\}\) (hình tròn đơn vị mở).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;tập-mở&quot;&gt;Tập mở&lt;/h2&gt;

&lt;p&gt;Một &lt;strong&gt;tập mở&lt;/strong&gt; (&lt;em&gt;open set&lt;/em&gt;) được đặc trưng bởi tính chất không chứa bất kỳ điểm biên nào của chính nó.&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa-hình-thức&quot;&gt;Định nghĩa hình thức&lt;/h3&gt;

&lt;p&gt;Tập \(S \subseteq \mathbb{R}^n\) được gọi là &lt;strong&gt;tập mở&lt;/strong&gt; nếu với mọi điểm \(\mathbf{x} \in S\), tồn tại \(\epsilon &amp;gt; 0\) sao cho hình cầu mở \(B(\mathbf{x}, \epsilon)\) nằm trọn trong \(S\):&lt;/p&gt;

\[\forall \mathbf{x} \in S, \exists \epsilon &amp;gt; 0 : B(\mathbf{x}, \epsilon) \subseteq S\]

&lt;h3 id=&quot;trực-giác&quot;&gt;Trực giác&lt;/h3&gt;

&lt;p&gt;Nếu đứng tại bất kỳ điểm nào thuộc tập mở, ta luôn có thể dịch chuyển một đoạn đủ nhỏ theo mọi hướng mà vẫn nằm bên trong tập đó. Xung quanh mỗi điểm luôn có một “vùng đệm” thuộc tập.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-về-tập-mở&quot;&gt;Ví dụ về tập mở&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Trong \(\mathbb{R}\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[(0, 1) = \{x : 0 &amp;lt; x &amp;lt; 1\}\]
  &lt;/li&gt;
  &lt;li&gt;
\[(-\infty, 5) = \{x : x &amp;lt; 5\}\]
  &lt;/li&gt;
  &lt;li&gt;Chính \(\mathbb{R}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trong \(\mathbb{R}^2\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\{(x, y) : x^2 + y^2 &amp;lt; 1\}\) (hình tròn đơn vị mở)&lt;/li&gt;
  &lt;li&gt;\(\{(x, y) : x &amp;gt; 0, y &amp;gt; 0\}\) (góc phần tư thứ nhất, không tính hai trục tọa độ)&lt;/li&gt;
  &lt;li&gt;Chính \(\mathbb{R}^2\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trong \(\mathbb{R}^n\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mọi hình cầu mở \(B(\mathbf{x}_0, r)\)&lt;/li&gt;
  &lt;li&gt;Chính \(\mathbb{R}^n\)&lt;/li&gt;
  &lt;li&gt;Tập rỗng \(\emptyset\) (hiển nhiên thỏa mãn định nghĩa)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tính-chất-của-tập-mở&quot;&gt;Tính chất của tập mở&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Hợp tùy ý các tập mở là tập mở.&lt;/li&gt;
  &lt;li&gt;Giao hữu hạn các tập mở là tập mở.&lt;/li&gt;
  &lt;li&gt;\(\mathbb{R}^n\) và \(\emptyset\) đều là tập mở.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;tập-đóng&quot;&gt;Tập đóng&lt;/h2&gt;

&lt;p&gt;Một &lt;strong&gt;tập đóng&lt;/strong&gt; (&lt;em&gt;closed set&lt;/em&gt;) là tập chứa toàn bộ các điểm biên của nó. Nói cách khác, \(S\) là tập đóng khi và chỉ khi phần bù \(\mathbb{R}^n \setminus S\) là một &lt;strong&gt;tập mở&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa-hình-thức-1&quot;&gt;Định nghĩa hình thức&lt;/h3&gt;

&lt;p&gt;Tập \(S\) là &lt;strong&gt;tập đóng&lt;/strong&gt; nếu nó chứa mọi điểm giới hạn của nó: bất cứ khi nào một dãy \((\mathbf{x}_n)\) trong \(S\) hội tụ về \(\mathbf{x}\), ta đều có \(\mathbf{x} \in S\):&lt;/p&gt;

\[\text{Nếu } \mathbf{x}_n \in S \text{ với mọi } n \text{ và } \lim_{n \to \infty} \mathbf{x}_n = \mathbf{x}, \text{ thì } \mathbf{x} \in S\]

&lt;h3 id=&quot;ví-dụ-về-tập-đóng&quot;&gt;Ví dụ về tập đóng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Trong \(\mathbb{R}\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[[0, 1] = \{x : 0 \leq x \leq 1\}\]
  &lt;/li&gt;
  &lt;li&gt;
\[[a, \infty) = \{x : x \geq a\}\]
  &lt;/li&gt;
  &lt;li&gt;\(\{0\}\) (tập một điểm)&lt;/li&gt;
  &lt;li&gt;\(\mathbb{Z}\) (tập số nguyên)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trong \(\mathbb{R}^2\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\{(x, y) : x^2 + y^2 \leq 1\}\) (hình tròn đơn vị đóng)&lt;/li&gt;
  &lt;li&gt;\(\{(x, y) : x \geq 0, y \geq 0\}\) (góc phần tư thứ nhất, bao gồm cả hai trục tọa độ)&lt;/li&gt;
  &lt;li&gt;\(\{(0, 0)\}\) (tập một điểm)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trong \(\mathbb{R}^n\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mọi hình cầu đóng \(\overline{B}(\mathbf{x}_0, r) = \{\mathbf{x} : d(\mathbf{x}, \mathbf{x}_0) \leq r\}\)&lt;/li&gt;
  &lt;li&gt;Chính \(\mathbb{R}^n\)&lt;/li&gt;
  &lt;li&gt;Tập rỗng \(\emptyset\)&lt;/li&gt;
  &lt;li&gt;Mọi tập hữu hạn&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tính-chất-của-tập-đóng&quot;&gt;Tính chất của tập đóng&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Giao tùy ý các tập đóng là tập đóng.&lt;/li&gt;
  &lt;li&gt;Hợp hữu hạn các tập đóng là tập đóng.&lt;/li&gt;
  &lt;li&gt;\(\mathbb{R}^n\) và \(\emptyset\) đều là tập đóng.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;lưu-ý-quan-trọng&quot;&gt;Lưu ý quan trọng&lt;/h3&gt;

&lt;p&gt;Một tập hợp có thể rơi vào một trong bốn trường hợp:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mở nhưng không đóng:&lt;/strong&gt; \((0, 1)\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đóng nhưng không mở:&lt;/strong&gt; \([0, 1]\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vừa mở vừa đóng:&lt;/strong&gt; \(\mathbb{R}^n\), \(\emptyset\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không mở cũng không đóng:&lt;/strong&gt; \([0, 1)\), \((0, 1]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;biên-phần-trong-và-bao-đóng&quot;&gt;Biên, phần trong và bao đóng&lt;/h2&gt;

&lt;h3 id=&quot;biên&quot;&gt;Biên&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Biên&lt;/strong&gt; (&lt;em&gt;boundary&lt;/em&gt;) của tập \(S\), ký hiệu \(\partial S\), là tập hợp các điểm nằm trên “mép” của \(S\). Điểm \(\mathbf{x}\) là &lt;strong&gt;điểm biên&lt;/strong&gt; của \(S\) nếu mọi hình cầu mở tâm \(\mathbf{x}\) đều giao đồng thời với cả \(S\) và phần bù \(S^c\):&lt;/p&gt;

\[\partial S = \{\mathbf{x} : \forall \epsilon &amp;gt; 0, B(\mathbf{x}, \epsilon) \cap S \neq \emptyset \text{ và } B(\mathbf{x}, \epsilon) \cap S^c \neq \emptyset\}\]

&lt;h3 id=&quot;phần-trong&quot;&gt;Phần trong&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần trong&lt;/strong&gt; (&lt;em&gt;interior&lt;/em&gt;) của tập \(S\), ký hiệu \(S^\circ\) hoặc \(\text{int}(S)\), gồm mọi điểm nằm hoàn toàn bên trong \(S\) (không nằm trên biên):&lt;/p&gt;

\[S^\circ = \{\mathbf{x} \in S : \exists \epsilon &amp;gt; 0, B(\mathbf{x}, \epsilon) \subseteq S\}\]

&lt;h3 id=&quot;bao-đóng&quot;&gt;Bao đóng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Bao đóng&lt;/strong&gt; (&lt;em&gt;closure&lt;/em&gt;) của tập \(S\), ký hiệu \(\overline{S}\) hoặc \(\text{cl}(S)\), là tập đóng nhỏ nhất chứa \(S\):&lt;/p&gt;

\[\overline{S} = S \cup \partial S\]

&lt;h3 id=&quot;ví-dụ-minh-họa&quot;&gt;Ví dụ minh họa&lt;/h3&gt;

&lt;p&gt;Với nửa khoảng \(S = [0, 1)\) trong \(\mathbb{R}\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phần trong:&lt;/strong&gt; \(S^\circ = (0, 1)\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biên:&lt;/strong&gt; \(\partial S = \{0, 1\}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bao đóng:&lt;/strong&gt; \(\overline{S} = [0, 1]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Với hình tròn mở \(S = \{(x, y) : x^2 + y^2 &amp;lt; 1\}\) trong \(\mathbb{R}^2\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phần trong:&lt;/strong&gt; \(S^\circ = S\) (vì \(S\) vốn là tập mở)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Biên:&lt;/strong&gt; \(\partial S = \{(x, y) : x^2 + y^2 = 1\}\) (đường tròn đơn vị)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bao đóng:&lt;/strong&gt; \(\overline{S} = \{(x, y) : x^2 + y^2 \leq 1\}\) (hình tròn đơn vị đóng)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;tập-compact&quot;&gt;Tập compact&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Tập compact&lt;/strong&gt; (&lt;em&gt;compact set&lt;/em&gt;) là một trong những khái niệm trung tâm của lý thuyết tối ưu hóa.&lt;/p&gt;

&lt;h3 id=&quot;đặc-trưng-trong-không-gian-euclid&quot;&gt;Đặc trưng trong không gian Euclid&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Định lý Heine–Borel:&lt;/strong&gt; Trong không gian Euclid \(\mathbb{R}^n\), một tập hợp là compact khi và chỉ khi nó vừa &lt;strong&gt;đóng&lt;/strong&gt; vừa &lt;strong&gt;bị chặn&lt;/strong&gt;.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bị chặn:&lt;/strong&gt; tập \(S\) bị chặn nếu nó nằm trọn trong một hình cầu mở đủ lớn: \(\exists M &amp;gt; 0, \mathbf{x}_0\) sao cho \(S \subseteq B(\mathbf{x}_0, M)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đóng:&lt;/strong&gt; như đã định nghĩa ở mục trên.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;ví-dụ-về-tập-compact&quot;&gt;Ví dụ về tập compact&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Trong \(\mathbb{R}\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\([a, b]\) (mọi đoạn đóng, bị chặn)&lt;/li&gt;
  &lt;li&gt;\(\{0\}\) (tập một điểm)&lt;/li&gt;
  &lt;li&gt;Mọi tập hữu hạn&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trong \(\mathbb{R}^2\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\{(x, y) : x^2 + y^2 \leq 1\}\) (hình tròn đơn vị đóng)&lt;/li&gt;
  &lt;li&gt;\([0, 1] \times [0, 1]\) (hình vuông đơn vị đóng)&lt;/li&gt;
  &lt;li&gt;Mọi tập hữu hạn điểm&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Trong \(\mathbb{R}^n\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Mọi hình cầu đóng \(\overline{B}(\mathbf{x}_0, r)\)&lt;/li&gt;
  &lt;li&gt;Mọi hình hộp chữ nhật đóng, bị chặn \([a_1, b_1] \times [a_2, b_2] \times \cdots \times [a_n, b_n]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;các-tập-không-compact&quot;&gt;Các tập không compact&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;\((0, 1)\) (bị chặn nhưng không đóng)&lt;/li&gt;
  &lt;li&gt;\([0, \infty)\) (đóng nhưng không bị chặn)&lt;/li&gt;
  &lt;li&gt;\(\mathbb{R}^n\) (không bị chặn)&lt;/li&gt;
  &lt;li&gt;\(\{1, 1/2, 1/3, 1/4, \ldots\}\) (bị chặn nhưng không đóng, vì điểm giới hạn \(0\) không thuộc tập)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;tính-liên-tục-của-hàm-số&quot;&gt;Tính liên tục của hàm số&lt;/h2&gt;

&lt;h3 id=&quot;liên-tục-tại-một-điểm&quot;&gt;Liên tục tại một điểm&lt;/h3&gt;

&lt;p&gt;Hàm số \(f: A \to \mathbb{R}\) &lt;strong&gt;liên tục tại điểm&lt;/strong&gt; \(\mathbf{c} \in A\) nếu với mọi \(\varepsilon &amp;gt; 0\), tồn tại \(\delta &amp;gt; 0\) sao cho với mọi \(\mathbf{x} \in A\):&lt;/p&gt;

\[\|\mathbf{x} - \mathbf{c}\| &amp;lt; \delta \implies |f(\mathbf{x}) - f(\mathbf{c})| &amp;lt; \varepsilon\]

&lt;p&gt;&lt;strong&gt;Ý nghĩa trực quan:&lt;/strong&gt; thay đổi nhỏ ở đầu vào chỉ gây ra thay đổi nhỏ ở đầu ra.&lt;/p&gt;

&lt;h3 id=&quot;liên-tục-trên-tập-hợp&quot;&gt;Liên tục trên tập hợp&lt;/h3&gt;

&lt;p&gt;Hàm \(f\) &lt;strong&gt;liên tục trên \(A\)&lt;/strong&gt; nếu nó liên tục tại mọi điểm thuộc \(A\).&lt;/p&gt;

&lt;h3 id=&quot;đặc-trưng-theo-dãy&quot;&gt;Đặc trưng theo dãy&lt;/h3&gt;

&lt;p&gt;Hàm \(f\) liên tục tại \(\mathbf{c}\) khi và chỉ khi với mọi dãy \((\mathbf{x}_n)\) trong \(A\) hội tụ về \(\mathbf{c}\):&lt;/p&gt;

\[\lim_{n \to \infty} f(\mathbf{x}_n) = f(\mathbf{c})\]

&lt;hr /&gt;

&lt;h2 id=&quot;các-định-lý-quan-trọng-cho-tối-ưu-hóa&quot;&gt;Các định lý quan trọng cho tối ưu hóa&lt;/h2&gt;

&lt;h3 id=&quot;định-lý-giá-trị-cực-trị-extreme-value-theorem&quot;&gt;Định lý giá trị cực trị (&lt;em&gt;Extreme Value Theorem&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Nếu \(f\) liên tục trên tập compact khác rỗng \(K\), thì \(f\) đạt cả giá trị lớn nhất và giá trị nhỏ nhất trên \(K\).&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Đây là định lý nền tảng của tối ưu hóa vì nó bảo đảm mọi hàm mục tiêu liên tục trên miền khả thi compact đều có nghiệm tối ưu.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ý tưởng chứng minh:&lt;/strong&gt; tính compact bảo đảm supremum và infimum của \(f\) trên \(K\) thực sự đạt được tại các điểm nằm trong \(K\).&lt;/p&gt;

&lt;h3 id=&quot;định-lý-giá-trị-trung-gian-intermediate-value-theorem&quot;&gt;Định lý giá trị trung gian (&lt;em&gt;Intermediate Value Theorem&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Nếu \(f\) liên tục trên đoạn \([a, b]\) và \(y\) nằm giữa \(f(a)\) và \(f(b)\), thì tồn tại \(c \in [a, b]\) sao cho \(f(c) = y\).&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Định lý này thường được dùng để chứng minh sự tồn tại nghiệm của phương trình \(f(x) = 0\).&lt;/p&gt;

&lt;h3 id=&quot;định-lý-bolzanoweierstrass&quot;&gt;Định lý Bolzano–Weierstrass&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Mọi dãy bị chặn trong \(\mathbb{R}^n\) đều trích ra được ít nhất một dãy con hội tụ.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Đây là công cụ then chốt trong các chứng minh hội tụ của thuật toán tối ưu.&lt;/p&gt;

&lt;h3 id=&quot;định-lý-xấp-xỉ-weierstrass&quot;&gt;Định lý xấp xỉ Weierstrass&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Mọi hàm liên tục trên một đoạn đóng bị chặn đều có thể xấp xỉ đều với độ chính xác tùy ý bởi đa thức.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Định lý này tạo cơ sở lý thuyết cho việc sử dụng xấp xỉ đa thức trong các thuật toán tối ưu hóa.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ứng-dụng-trong-tối-ưu-hóa&quot;&gt;Ứng dụng trong tối ưu hóa&lt;/h2&gt;

&lt;h3 id=&quot;1-sự-tồn-tại-nghiệm&quot;&gt;1. Sự tồn tại nghiệm&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Miền khả thi compact bảo đảm tồn tại nghiệm tối ưu:&lt;/strong&gt; nếu miền khả thi \(S\) là tập compact khác rỗng và hàm mục tiêu \(f\) liên tục, thì bài toán \(\min_{\mathbf{x} \in S} f(\mathbf{x})\) chắc chắn có nghiệm.&lt;/p&gt;

&lt;h3 id=&quot;2-điều-kiện-chính-quy-ràng-buộc-constraint-qualification&quot;&gt;2. Điều kiện chính quy ràng buộc (&lt;em&gt;constraint qualification&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Các tính chất tôpô của tập ràng buộc quyết định tính hợp lệ của điều kiện tối ưu:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Điểm chính quy:&lt;/strong&gt; các điểm mà tại đó gradient của các ràng buộc kích hoạt độc lập tuyến tính.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương pháp điểm trong:&lt;/strong&gt; đòi hỏi miền khả thi có phần trong khác rỗng.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-phân-tích-hội-tụ&quot;&gt;3. Phân tích hội tụ&lt;/h3&gt;

&lt;p&gt;Để đánh giá khả năng hội tụ của thuật toán lặp:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tính đóng:&lt;/strong&gt; bảo đảm điểm giới hạn của một dãy điểm khả thi vẫn là điểm khả thi.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính compact:&lt;/strong&gt; bảo đảm dãy lặp bị chặn luôn tồn tại dãy con hội tụ.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-cực-trị-địa-phương-và-toàn-cục&quot;&gt;4. Cực trị địa phương và toàn cục&lt;/h3&gt;

&lt;p&gt;Khái niệm lân cận cho phép định nghĩa chặt chẽ hai loại cực trị:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cực tiểu địa phương:&lt;/strong&gt; \(f(\mathbf{x}^*) \leq f(\mathbf{x})\) với mọi \(\mathbf{x}\) khả thi nằm trong một lân cận đủ nhỏ của \(\mathbf{x}^*\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cực tiểu toàn cục:&lt;/strong&gt; \(f(\mathbf{x}^*) \leq f(\mathbf{x})\) với mọi \(\mathbf{x}\) thuộc toàn bộ miền khả thi.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;5-phân-tích-miền-khả-thi&quot;&gt;5. Phân tích miền khả thi&lt;/h3&gt;

&lt;p&gt;Tính chất tôpô của miền khả thi phụ thuộc trực tiếp vào dạng ràng buộc:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ràng buộc tuyến tính (bất đẳng thức yếu):&lt;/strong&gt; xác định các nửa không gian đóng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ràng buộc phi tuyến:&lt;/strong&gt; có thể tạo ra tập không đóng hoặc không mở tùy theo dạng bất đẳng thức.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Miền khả thi compact:&lt;/strong&gt; điều kiện đủ để hàm liên tục đạt cực trị.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;ví-dụ-tối-ưu-danh-mục-đầu-tư&quot;&gt;Ví dụ: Tối ưu danh mục đầu tư&lt;/h3&gt;

&lt;p&gt;Xét bài toán cực tiểu hóa rủi ro danh mục với các ràng buộc:&lt;/p&gt;

\[\begin{align}
\min_{\mathbf{w}} \quad &amp;amp; \mathbf{w}^T \mathbf{\Sigma} \mathbf{w} \\
\text{s.t.} \quad &amp;amp; \mathbf{1}^T \mathbf{w} = 1 \\
&amp;amp; \mathbf{w} \geq \mathbf{0}
\end{align}\]

&lt;p&gt;Miền khả thi \(S = \{\mathbf{w} : \mathbf{1}^T \mathbf{w} = 1, \mathbf{w} \geq \mathbf{0}\}\) có các tính chất:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Đóng:&lt;/strong&gt; là giao của các tập đóng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bị chặn:&lt;/strong&gt; ràng buộc \(\mathbf{1}^T \mathbf{w} = 1\) kết hợp với \(\mathbf{w} \geq \mathbf{0}\) suy ra mọi thành phần nằm trong \([0, 1]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compact:&lt;/strong&gt; vừa đóng vừa bị chặn trong \(\mathbb{R}^n\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Vì hàm mục tiêu \(\mathbf{w}^T \mathbf{\Sigma} \mathbf{w}\) liên tục và \(S\) compact, Định lý giá trị cực trị bảo đảm luôn tồn tại một danh mục tối ưu.&lt;/p&gt;

&lt;p&gt;Các khái niệm tôpô và giải tích thực cung cấp cơ sở chặt chẽ để chứng minh sự tồn tại nghiệm cũng như phân tích hội tụ cho cả lý thuyết lẫn thuật toán tối ưu hóa thực tiễn.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Intro to Open Sets (with Examples)&lt;/td&gt;
          &lt;td&gt;Real Analysis](https://www.youtube.com/watch?v=pnWgj8jjs3w) — Wrath of Math, tiếng Anh. Trình bày định nghĩa tập mở bằng hình cầu mở quanh từng điểm, khớp với phần mở đầu của bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Identifying Open, Closed, and Compact Sets&lt;/td&gt;
          &lt;td&gt;Real Analysis Exercises](https://www.youtube.com/watch?v=0_mottmadEU) — Wrath of Math, tiếng Anh. Hướng dẫn qua ví dụ cách phân biệt tập mở, tập đóng và tập compact, kèm khái niệm biên và bao đóng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Open Covers, Finite Subcovers, and Compact Sets&lt;/td&gt;
          &lt;td&gt;Real Analysis](https://www.youtube.com/watch?v=dAz9ax-bjzU) — Wrath of Math, tiếng Anh. Giới thiệu định nghĩa tính compact qua phủ mở — nền tảng cho các định lý cực trị trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-03-01 Cơ sở Lý thuyết tập hợp</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_03_01_Set_Theory_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_03_01_Set_Theory_Fundamentals</id>
   <content type="html">&lt;p&gt;Mọi khái niệm trong Khoa học Dữ liệu và Học sâu—từ phân chia tập train/validation/test không giao nhau, phép tính xác suất trên biến cố, cho đến ánh xạ nhiều tầng của mạng nơ-ron—đều đứng trên cùng một nền móng chung: &lt;strong&gt;lý thuyết tập hợp&lt;/strong&gt;. Đọc tài liệu nghiên cứu AI mà lúng túng trước các ký hiệu \(\in, \subseteq, \cap, \cup, A \times B, f^{-1}(B)\) giống như đọc bản nhạc mà không thuộc khóa Sol. Bài học này trang bị trọn bộ cú pháp và tư duy tập hợp để bạn đọc hiểu mượt mà các định lý toán học trong suốt khóa học.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-mảnh-ghép-căn-bản-của-lý-thuyết-tập-hợp&quot;&gt;Kiến thức cần nhớ: Bốn mảnh ghép căn bản của Lý thuyết Tập hợp&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Các phép toán tập hợp và Luật De Morgan&lt;/strong&gt;:
Hợp (\(\cup\)), giao (\(\cap\)), hiệu (\(\setminus\)) và phần bù (\(A^c\)) là công cụ phân vùng không gian dữ liệu, tính chỉ số IoU (&lt;em&gt;Intersection over Union&lt;/em&gt;) trong phát hiện vật thể và biến đổi biến cố xác suất.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tích Descartes (Cartesian Product \(A \times B\))&lt;/strong&gt;:
Xây dựng không gian đa chiều \(\mathbb{R}^n = \mathbb{R} \times \cdots \times \mathbb{R}\) và cặp dữ liệu có nhãn \((x, y) \in \mathcal{X} \times \mathcal{Y}\) cho bài toán học có giám sát.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ánh xạ: Đơn ánh, Toàn ánh và Song ánh (Injective, Surjective, Bijective)&lt;/strong&gt;:
Cho biết một tầng mạng có làm mất thông tin hay không (đơn ánh), có bao phủ được toàn bộ đầu ra mong muốn hay không (toàn ánh), và có thể đảo ngược hoàn hảo hay không (song ánh—nền tảng của Normalizing Flows).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Lực lượng tập hợp (Cardinality: Hữu hạn, Đếm được, Không đếm được)&lt;/strong&gt;:
Phân biệt rạch ròi giữa không gian rời rạc (từ vựng ngôn ngữ, nhãn lớp) dùng tổng \(\sum\) và không gian liên tục (trọng số thực \(\mathbb{R}^d\)) phải dùng tích phân \(\int\).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-chỉ-số-iou-bằng-phép-toán-tập-hợp-và-kiểm-tra-tính-song-ánh&quot;&gt;Giải thích: Tính tay chỉ số IoU bằng phép toán tập hợp và kiểm tra tính song ánh&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần A — Phép giao/hợp trong phát hiện vật thể (Object Detection):&lt;/strong&gt;
Giả sử khung dự đoán \(A\) phủ 60 điểm ảnh và khung chuẩn (&lt;em&gt;ground truth&lt;/em&gt;) \(B\) phủ 50 điểm ảnh, trong đó vùng chồng lấn \(A \cap B\) có đúng 30 điểm ảnh:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Lực lượng tập hợp hợp: \(\lvert A \cup B \rvert = \lvert A \rvert + \lvert B \rvert - \lvert A \cap B \rvert = 60 + 50 - 30 = 80\) điểm ảnh.&lt;/li&gt;
  &lt;li&gt;Chỉ số &lt;strong&gt;IoU&lt;/strong&gt;: \(\text{IoU}(A, B) = \frac{\lvert A \cap B \rvert}{\lvert A \cup B \rvert} = \frac{30}{80} = 0.375\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Phần B — So sánh hàm kích hoạt ReLU và Sigmoid dưới góc nhìn ánh xạ:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;ReLU&lt;/strong&gt; \(f(x) = \max(0, x)\) từ \(\mathbb{R} \to \mathbb{R}\): &lt;strong&gt;không đơn ánh&lt;/strong&gt; vì \(f(-2) = f(-5) = 0\) (mất thông tin phần âm), và &lt;strong&gt;không toàn ánh&lt;/strong&gt; lên \(\mathbb{R}\) vì không bao giờ tạo ra số âm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid&lt;/strong&gt; \(\sigma(x) = \frac{1}{1+e^{-x}}\) từ \(\mathbb{R} \to (0, 1)\): đồng biến chặt nên &lt;strong&gt;đơn ánh&lt;/strong&gt;, và mọi giá trị \(p \in (0, 1)\) đều có nghịch ảnh \(x = \ln\frac{p}{1-p}\) nên &lt;strong&gt;toàn ánh&lt;/strong&gt; \(\implies\) &lt;strong&gt;song ánh&lt;/strong&gt; giữa \(\mathbb{R}\) và \((0, 1)\), cho phép quy đổi 1-1 giữa logit và xác suất!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bài học này trình bày các khái niệm cơ bản của lý thuyết tập hợp, làm nền tảng toán học để phát biểu bài toán tối ưu hóa, ràng buộc và miền khả thi.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;giới-thiệu-về-lý-thuyết-tập-hợp&quot;&gt;Giới thiệu về lý thuyết tập hợp&lt;/h2&gt;

&lt;p&gt;Lý thuyết tập hợp là nền móng của toán học hiện đại và đóng vai trò thiết yếu khi mô tả các bài toán tối ưu hóa. Một &lt;strong&gt;tập hợp&lt;/strong&gt; là một bộ sưu tập các đối tượng phân biệt, gọi là các phần tử.&lt;/p&gt;

&lt;h3 id=&quot;ký-hiệu-cơ-bản&quot;&gt;Ký hiệu cơ bản&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ký hiệu liệt kê:&lt;/strong&gt; \(A = \{1, 2, 3, 4\}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quan hệ thuộc:&lt;/strong&gt; \(x \in A\) (\(x\) thuộc \(A\)) hoặc \(x \notin A\) (\(x\) không thuộc \(A\))&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tập rỗng:&lt;/strong&gt; \(\emptyset = \{\}\) (tập hợp không chứa phần tử nào)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ký hiệu theo tính chất đặc trưng:&lt;/strong&gt; \(A = \{x : P(x)\}\) (tập hợp mọi phần tử \(x\) thỏa mãn tính chất \(P(x)\))&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;ví-dụ&quot;&gt;Ví dụ&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;\(A = \{1, 2, 3, 4\}\) (liệt kê tường minh)&lt;/li&gt;
  &lt;li&gt;\(B = \{x \in \mathbb{R} : x^2 &amp;lt; 4\} = (-2, 2)\) (chỉ ra tính chất đặc trưng)&lt;/li&gt;
  &lt;li&gt;\(C = \{x \in \mathbb{Z} : x \text{ là số chẵn}\}\) (tập hợp các số nguyên chẵn)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;các-phép-toán-tập-hợp-cơ-bản&quot;&gt;Các phép toán tập hợp cơ bản&lt;/h2&gt;

&lt;h3 id=&quot;tập-hợp-và-tập-con&quot;&gt;Tập hợp và tập con&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Tập con:&lt;/strong&gt; \(A \subseteq B\) nghĩa là mọi phần tử của \(A\) đều thuộc \(B\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tập con thực sự:&lt;/strong&gt; \(A \subset B\) nghĩa là \(A \subseteq B\) và \(A \neq B\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hai tập hợp bằng nhau:&lt;/strong&gt; \(A = B\) khi và chỉ khi \(A \subseteq B\) và \(B \subseteq A\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[\{1, 2\} \subseteq \{1, 2, 3, 4\}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\{1, 2\} \subset \{1, 2, 3, 4\}\]
  &lt;/li&gt;
  &lt;li&gt;\(\emptyset \subseteq A\) với mọi tập hợp \(A\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;phép-hợp-và-phép-giao&quot;&gt;Phép hợp và phép giao&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Hợp (\(A \cup B\)):&lt;/strong&gt; tập hợp tất cả các phần tử thuộc \(A\) hoặc thuộc \(B\) (hoặc cả hai):
\(A \cup B = \{x : x \in A \text{ hoặc } x \in B\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Giao (\(A \cap B\)):&lt;/strong&gt; tập hợp tất cả các phần tử thuộc đồng thời cả \(A\) và \(B\):
\(A \cap B = \{x : x \in A \text{ và } x \in B\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nếu \(A = \{1, 2, 3\}\) và \(B = \{3, 4, 5\}\), thì:
    &lt;ul&gt;
      &lt;li&gt;
\[A \cup B = \{1, 2, 3, 4, 5\}\]
      &lt;/li&gt;
      &lt;li&gt;
\[A \cap B = \{3\}\]
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hai tập hợp rời nhau:&lt;/strong&gt; \(A\) và \(B\) rời nhau nếu \(A \cap B = \emptyset\).&lt;/p&gt;

&lt;h3 id=&quot;phần-bù-và-hiệu-tập-hợp&quot;&gt;Phần bù và hiệu tập hợp&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phần bù (\(A^c\)):&lt;/strong&gt; tập hợp tất cả các phần tử không thuộc \(A\) (trong một tập vũ trụ \(U\) cho trước):
\(A^c = \{x \in U : x \notin A\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiệu tập hợp (\(A \setminus B\)):&lt;/strong&gt; tập hợp các phần tử thuộc \(A\) nhưng không thuộc \(B\):
\(A \setminus B = \{x : x \in A \text{ và } x \notin B\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hiệu đối xứng:&lt;/strong&gt; \((A \setminus B) \cup (B \setminus A) = (A \cup B) \setminus (A \cap B)\)&lt;/p&gt;

&lt;h3 id=&quot;các-luật-đại-số-tập-hợp&quot;&gt;Các luật đại số tập hợp&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Luật giao hoán:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[A \cup B = B \cup A\]
  &lt;/li&gt;
  &lt;li&gt;
\[A \cap B = B \cap A\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Luật kết hợp:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[(A \cup B) \cup C = A \cup (B \cup C)\]
  &lt;/li&gt;
  &lt;li&gt;
\[(A \cap B) \cap C = A \cap (B \cap C)\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Luật phân phối:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[A \cap (B \cup C) = (A \cap B) \cup (A \cap C)\]
  &lt;/li&gt;
  &lt;li&gt;
\[A \cup (B \cap C) = (A \cup B) \cap (A \cup C)\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Luật De Morgan:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[(A \cup B)^c = A^c \cap B^c\]
  &lt;/li&gt;
  &lt;li&gt;
\[(A \cap B)^c = A^c \cup B^c\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;các-tập-hợp-số-quan-trọng&quot;&gt;Các tập hợp số quan trọng&lt;/h2&gt;

&lt;p&gt;Nắm rõ hệ thống phân cấp các tập số giúp xác định chính xác miền biến thiên của bài toán tối ưu:&lt;/p&gt;

&lt;h3 id=&quot;số-tự-nhiên&quot;&gt;Số tự nhiên&lt;/h3&gt;
&lt;p&gt;\(\mathbb{N} = \{1, 2, 3, 4, \ldots\}\)
(Đôi khi quy ước gồm cả số 0: \(\mathbb{N}_0 = \{0, 1, 2, 3, \ldots\}\))&lt;/p&gt;

&lt;h3 id=&quot;số-nguyên&quot;&gt;Số nguyên&lt;/h3&gt;
&lt;p&gt;\(\mathbb{Z} = \{\ldots, -2, -1, 0, 1, 2, \ldots\}\)&lt;/p&gt;

&lt;h3 id=&quot;số-hữu-tỉ&quot;&gt;Số hữu tỉ&lt;/h3&gt;
&lt;p&gt;\(\mathbb{Q} = \left\{\frac{p}{q} : p, q \in \mathbb{Z}, q \neq 0\right\}\)&lt;/p&gt;

&lt;p&gt;Gồm tất cả các số biểu diễn được dưới dạng phân số của hai số nguyên.&lt;/p&gt;

&lt;h3 id=&quot;số-thực&quot;&gt;Số thực&lt;/h3&gt;
&lt;p&gt;\(\mathbb{R}\) bao gồm tất cả các số hữu tỉ và số vô tỉ (như \(\pi\), \(e\), \(\sqrt{2}\)).&lt;/p&gt;

&lt;h3 id=&quot;số-phức&quot;&gt;Số phức&lt;/h3&gt;
&lt;p&gt;\(\mathbb{C} = \{a + bi : a, b \in \mathbb{R}, i^2 = -1\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quan hệ bao hàm:&lt;/strong&gt; \(\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q} \subset \mathbb{R} \subset \mathbb{C}\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;hàm-số-miền-xác-định-và-miền-giá-trị&quot;&gt;Hàm số: Miền xác định và miền giá trị&lt;/h2&gt;

&lt;p&gt;Một &lt;strong&gt;hàm số&lt;/strong&gt; \(f: A \to B\) là quy tắc gán cho mỗi phần tử thuộc tập \(A\) đúng một phần tử thuộc tập \(B\).&lt;/p&gt;

&lt;h3 id=&quot;các-khái-niệm-chính&quot;&gt;Các khái niệm chính&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Miền xác định (&lt;em&gt;domain&lt;/em&gt;):&lt;/strong&gt; tập hợp \(A\) gồm tất cả các giá trị đầu vào hợp lệ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tập đích (&lt;em&gt;codomain&lt;/em&gt;):&lt;/strong&gt; tập hợp \(B\) chứa các giá trị đầu ra có thể có.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Miền giá trị / Ảnh (&lt;em&gt;range/image&lt;/em&gt;):&lt;/strong&gt; tập hợp tất cả các giá trị đầu ra thực sự nhận được: \(\text{Range}(f) = \{f(x) : x \in A\} \subseteq B\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; Với \(f(x) = x^2\) xét như ánh xạ \(f: \mathbb{R} \to \mathbb{R}\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Miền xác định: \(\mathbb{R}\)&lt;/li&gt;
  &lt;li&gt;Tập đích: \(\mathbb{R}\)&lt;/li&gt;
  &lt;li&gt;Miền giá trị: \([0, \infty)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;phân-loại-ánh-xạ&quot;&gt;Phân loại ánh xạ&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Đơn ánh (&lt;em&gt;injective&lt;/em&gt;):&lt;/strong&gt; hai đầu vào khác nhau luôn cho hai đầu ra khác nhau:
\(f(x_1) = f(x_2) \implies x_1 = x_2\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Toàn ánh (&lt;em&gt;surjective&lt;/em&gt;):&lt;/strong&gt; mọi phần tử của tập đích đều có ít nhất một tạo ảnh trong miền xác định:
Với mọi \(y \in B\), tồn tại \(x \in A\) sao cho \(f(x) = y\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Song ánh (&lt;em&gt;bijective&lt;/em&gt;):&lt;/strong&gt; ánh xạ vừa đơn ánh vừa toàn ánh, thiết lập tương ứng một-một giữa miền xác định và tập đích.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(f(x) = 2x\) từ \(\mathbb{R}\) vào \(\mathbb{R}\) là song ánh.&lt;/li&gt;
  &lt;li&gt;\(f(x) = x^2\) từ \(\mathbb{R}\) vào \(\mathbb{R}\) không đơn ánh và cũng không toàn ánh.&lt;/li&gt;
  &lt;li&gt;\(f(x) = x^2\) từ \([0, \infty)\) vào \([0, \infty)\) là song ánh.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;bất-đẳng-thức&quot;&gt;Bất đẳng thức&lt;/h2&gt;

&lt;p&gt;Bất đẳng thức xuất hiện rất phổ biến trong tối ưu hóa vì phần lớn ràng buộc thực tế được biểu diễn dưới dạng bất đẳng thức.&lt;/p&gt;

&lt;h3 id=&quot;các-ký-hiệu-cơ-bản&quot;&gt;Các ký hiệu cơ bản&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;\(a &amp;lt; b\): \(a\) nhỏ hơn ngặt \(b\)&lt;/li&gt;
  &lt;li&gt;\(a \leq b\): \(a\) nhỏ hơn hoặc bằng \(b\)&lt;/li&gt;
  &lt;li&gt;\(a &amp;gt; b\): \(a\) lớn hơn ngặt \(b\)&lt;/li&gt;
  &lt;li&gt;\(a \geq b\): \(a\) lớn hơn hoặc bằng \(b\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;tính-chất-của-bất-đẳng-thức&quot;&gt;Tính chất của bất đẳng thức&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính bắc cầu:&lt;/strong&gt; nếu \(a \leq b\) và \(b \leq c\), thì \(a \leq c\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phép cộng:&lt;/strong&gt; nếu \(a \leq b\), thì \(a + c \leq b + c\) với mọi \(c \in \mathbb{R}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhân với số dương:&lt;/strong&gt; nếu \(a \leq b\) và \(c &amp;gt; 0\), thì \(ac \leq bc\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nhân với số âm:&lt;/strong&gt; nếu \(a \leq b\) và \(c &amp;lt; 0\), thì \(ac \geq bc\) (bất đẳng thức đổi chiều).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ký-hiệu-khoảng-và-đoạn&quot;&gt;Ký hiệu khoảng và đoạn&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng mở:&lt;/strong&gt; \((a, b) = \{x \in \mathbb{R} : a &amp;lt; x &amp;lt; b\}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đoạn đóng:&lt;/strong&gt; \([a, b] = \{x \in \mathbb{R} : a \leq x \leq b\}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nửa khoảng:&lt;/strong&gt; \([a, b)\), \((a, b]\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng không bị chặn:&lt;/strong&gt; \((-\infty, a)\), \([a, \infty)\), \((-\infty, \infty) = \mathbb{R}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ứng-dụng-trong-tối-ưu-hóa&quot;&gt;Ứng dụng trong tối ưu hóa&lt;/h2&gt;

&lt;p&gt;Các khái niệm của lý thuyết tập hợp được dùng trực tiếp trong việc mô hình hóa bài toán tối ưu:&lt;/p&gt;

&lt;h3 id=&quot;1-miền-khả-thi&quot;&gt;1. Miền khả thi&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Miền khả thi&lt;/strong&gt; (&lt;em&gt;feasible region&lt;/em&gt;) là tập hợp tất cả các điểm thỏa mãn toàn bộ ràng buộc của bài toán:
\(S = \{x \in \mathbb{R}^n : g_i(x) \leq 0, i = 1, \ldots, m; h_j(x) = 0, j = 1, \ldots, p\}\)&lt;/p&gt;

&lt;h3 id=&quot;2-tập-mức&quot;&gt;2. Tập mức&lt;/h3&gt;

&lt;p&gt;Với hàm số \(f: \mathbb{R}^n \to \mathbb{R}\), &lt;strong&gt;tập mức&lt;/strong&gt; tại mức \(c\) là:
\(L_c = \{x \in \mathbb{R}^n : f(x) = c\}\)&lt;/p&gt;

&lt;h3 id=&quot;3-tính-chất-của-tập-ràng-buộc&quot;&gt;3. Tính chất của tập ràng buộc&lt;/h3&gt;

&lt;p&gt;Việc tập ràng buộc có các tính chất tôpô thuận lợi (như tính đóng hay có phần trong khác rỗng) ảnh hưởng trực tiếp đến sự tồn tại và đặc trưng của nghiệm tối ưu.&lt;/p&gt;

&lt;h3 id=&quot;4-phân-tích-hội-tụ&quot;&gt;4. Phân tích hội tụ&lt;/h3&gt;

&lt;p&gt;Khái niệm dãy và giới hạn trên tập hợp là công cụ cần thiết để kiểm tra xem thuật toán tối ưu có hội tụ về nghiệm mong muốn hay không.&lt;/p&gt;

&lt;h3 id=&quot;5-phép-toán-tập-hợp-trong-biểu-diễn-bài-toán&quot;&gt;5. Phép toán tập hợp trong biểu diễn bài toán&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Giao:&lt;/strong&gt; xác định tập các điểm thỏa mãn đồng thời nhiều ràng buộc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hợp:&lt;/strong&gt; gộp các miền khả thi từ nhiều kịch bản khác nhau.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phần bù:&lt;/strong&gt; xác định miền không khả thi.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; Trong quy hoạch tuyến tính, miền khả thi có dạng:
\(S = \{x \in \mathbb{R}^n : Ax \leq b, x \geq 0\} = \bigcap_{i=1}^{m} \{x : a_i^T x \leq b_i\} \cap \{x : x \geq 0\}\)&lt;/p&gt;

&lt;p&gt;Đây là giao của các nửa không gian, minh họa cách các phép toán tập hợp xuất hiện tự nhiên khi phát biểu bài toán tối ưu.&lt;/p&gt;

&lt;p&gt;Nắm vững lý thuyết tập hợp giúp đặt bài toán tối ưu hóa một cách chặt chẽ và phân tích tính chất của bài toán một cách có hệ thống.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Intro to Sets&lt;/td&gt;
          &lt;td&gt;Examples, Notation &amp;amp; Properties](https://www.youtube.com/watch?v=B1v2-nGXNzs) — Dr. Trefor Bazett, tiếng Anh. Giới thiệu ký hiệu tập hợp, các phép toán cơ bản cùng miền xác định và miền giá trị của hàm số.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=tyDKR4FG3Yw&quot;&gt;INTRODUCTION to SET THEORY - DISCRETE MATHEMATICS&lt;/a&gt; — TrevTutor, tiếng Anh. Trình bày đầy đủ hơn về phép hợp, phép giao và các tập số xuất hiện trong bài.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JzIjCkouIGg&quot;&gt;MaDL - Sets, Scalars, Vectors, Matrices and Tensors&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Kết nối ngôn ngữ tập hợp với vô hướng, vector, ma trận và tensor dùng xuyên suốt khóa học.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-02 Đại số tuyến tính cơ bản</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_02_Basic_Linear_Algebra/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_02_Basic_Linear_Algebra</id>
   <content type="html">&lt;p&gt;Một bức ảnh màu độ phân giải Full HD không gì khác hơn là một mảng số gồm hơn 6 triệu tọa độ; một câu tiếng Việt trước khi đi vào Transformer cũng được hóa thành chuỗi các vector hàng nghìn chiều. Toàn bộ thế giới dữ liệu của Học sâu vận hành bên trong không gian đại số tuyến tính, nơi GPU có thể thực hiện hàng nghìn tỷ phép nhân ma trận mỗi giây. Bài tổng quan này phác họa ba mảnh ghép cốt lõi—vector, ma trận và giá trị riêng—để bạn nhìn đại số tuyến tính bằng con mắt hình học thay vì những bảng số vô hồn.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-trụ-cột-đại-số-tuyến-tính-cho-học-sâu&quot;&gt;Kiến thức cần nhớ: Ba trụ cột Đại số Tuyến tính cho Học sâu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vector, Tích vô hướng và Chuẩn (Vectors &amp;amp; Norms)&lt;/strong&gt;:
Mã hóa từng mẫu dữ liệu hoặc embedding ngữ nghĩa thành một điểm/mũi tên trong \(\mathbb{R}^n\); tích vô hướng đo độ tương đồng góc (cơ chế Attention), còn chuẩn \(L_1, L_2\) đo độ lớn và kiểm soát regularization.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ma trận như Phép biến đổi Không gian (Linear Transformations)&lt;/strong&gt;:
Mỗi lớp tuyến tính &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Linear&lt;/code&gt; không chỉ là một bảng trọng số mà là phép xoay, kéo giãn, nén chiếu toàn bộ không gian đầu vào sang một không gian đặc trưng mới dễ phân tách hơn.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Giá trị riêng và Vector riêng (Eigenvalues &amp;amp; Eigenvectors)&lt;/strong&gt;:
Tiết lộ các “trục chính bất biến” của ma trận—chìa khóa để hiểu PCA giảm chiều dữ liệu, phân tích độ cong Hessian của hàm mất mát, và giải thích hiện tượng gradient bùng nổ/biến mất khi nhân lặp ma trận qua nhiều tầng sâu.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-theo-dõi-một-vector-đặc-trưng-đi-qua-một-lớp-tuyến-tính&quot;&gt;Giải thích: Theo dõi một vector đặc trưng đi qua một lớp tuyến tính&lt;/h3&gt;

&lt;p&gt;Giả sử ta có vector đầu vào 2 chiều \(\mathbf{x} = \begin{bmatrix} 1 \\ 2 \end{bmatrix}\) đi qua lớp tuyến tính \(\mathbf{y} = \mathbf{W}\mathbf{x} + \mathbf{b}\) với ma trận trọng số \(\mathbf{W} = \begin{bmatrix} 2 &amp;amp; -1 \\ 0 &amp;amp; 3 \end{bmatrix}\) và độ lệch \(\mathbf{b} = \begin{bmatrix} 1 \\ -2 \end{bmatrix}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Phép biến đổi tuyến tính \(\mathbf{W}\mathbf{x}\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Thành phần thứ nhất: \(2(1) + (-1)(2) = 0\).&lt;/li&gt;
      &lt;li&gt;Thành phần thứ hai: \(0(1) + 3(2) = 6\).
Ta thu được vector \(\begin{bmatrix} 0 \\ 6 \end{bmatrix}\): không gian đã bị kéo giãn mạnh theo trục dọc (gấp 3) và trượt nghiêng theo trục ngang.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phép tịnh tiến cộng bias \(\mathbf{b}\)&lt;/strong&gt;:
\(\mathbf{y} = \begin{bmatrix} 0 \\ 6 \end{bmatrix} + \begin{bmatrix} 1 \\ -2 \end{bmatrix} = \begin{bmatrix} 1 \\ 4 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Đo chuẩn \(L_2\) trước và sau lớp&lt;/strong&gt;: \(\|\mathbf{x}\|_2 = \sqrt{1^2 + 2^2} = \sqrt{5} \approx 2.236\), còn \(\|\mathbf{y}\|_2 = \sqrt{1^2 + 4^2} = \sqrt{17} \approx 4.123\). Chỉ một ma trận nhỏ đã khuếch đại độ lớn vector gần gấp đôi—nếu xếp 50 lớp như vậy liên tiếp mà không khởi tạo trọng số chuẩn, tín hiệu sẽ tăng theo cấp số nhân!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Phần này trình bày các khái niệm đại số tuyến tính cốt lõi cho tối ưu hóa, được chia thành ba bài học chính giúp bạn tiếp cận một cách có hệ thống.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Vectors&lt;/td&gt;
          &lt;td&gt;Chapter 1, Essence of linear algebra](https://www.youtube.com/watch?v=fNk_zzaMoSs) — 3Blue1Brown, tiếng Anh. Giới thiệu trực quan về vector trong \(\mathbb{R}^n\) — đối tượng trung tâm của toàn bộ phần đại số tuyến tính.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Linear transformations and matrices&lt;/td&gt;
          &lt;td&gt;Chapter 3, Essence of linear algebra](https://www.youtube.com/watch?v=kYB8IZa5AuE) — 3Blue1Brown, tiếng Anh. Trình bày cách nhìn ma trận như phép biến đổi tuyến tính, tương ứng với bài thứ hai.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Eigenvectors and eigenvalues&lt;/td&gt;
          &lt;td&gt;Chapter 14, Essence of linear algebra](https://www.youtube.com/watch?v=PFDu9oVAE-g) — 3Blue1Brown, tiếng Anh. Minh họa trực giác hình học về giá trị riêng và vector riêng trước khi đi vào các thuật toán tính toán.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-02-03 Giá trị riêng và Vector riêng</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_02_03_Eigenvalues_and_Eigenvectors/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_02_03_Eigenvalues_and_Eigenvectors</id>
   <content type="html">&lt;p&gt;Khi một ma trận tác động lên không gian, hầu hết mọi vector đều bị xoay lệch khỏi phương ban đầu. Thế nhưng luôn tồn tại những hướng đặc biệt—gọi là &lt;strong&gt;vector riêng&lt;/strong&gt; (&lt;em&gt;eigenvectors&lt;/em&gt;)—mà sau phép biến đổi, chúng không hề đổi phương, chỉ bị kéo dài ra hoặc co ngắn lại đúng bằng một hệ số gọi là &lt;strong&gt;giá trị riêng&lt;/strong&gt; (&lt;em&gt;eigenvalue&lt;/em&gt;). Khái niệm tưởng chừng thuần túy đại số này lại nắm giữ chìa khóa của hai hiện tượng nổi tiếng nhất trong Deep Learning: lý do gradient bùng nổ hoặc biến mất trong mạng hồi tiếp (RNN), và lý do dữ liệu hàng nghìn chiều có thể nén gọn qua PCA mà giữ nguyên cấu trúc chính.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-ứng-dụng-cốt-lõi-của-giá-trị-riêng-và-vector-riêng&quot;&gt;Kiến thức cần nhớ: Bốn ứng dụng cốt lõi của Giá trị riêng và Vector riêng&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phương trình đặc trưng \(\mathbf{A}\mathbf{v} = \lambda\mathbf{v}\)&lt;/strong&gt;:
Tìm các hướng bất biến bằng cách giải \(\det(\mathbf{A} - \lambda\mathbf{I}) = 0\); dấu và độ lớn của \(\lambda\) cho biết hướng đó bị phóng đại (\(\lvert\lambda\rvert &amp;gt; 1\)), triệt tiêu (\(\lvert\lambda\rvert &amp;lt; 1\)) hay đảo chiều (\(\lambda &amp;lt; 0\)).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Chéo hóa và Lũy thừa ma trận (\(\mathbf{A}^k = \mathbf{P}\mathbf{\Lambda}^k\mathbf{P}^{-1}\))&lt;/strong&gt;:
Khi nhân lặp một ma trận trọng số \(k\) lần (như RNN chạy qua \(k\) bước thời gian), mọi thành phần tăng hoặc tắt theo \(\lambda_i^k\). Chỉ cần \(\lvert\lambda_{\max}\rvert = 1.2\) thì sau 50 bước, \(1.2^{50} \approx 9100\) (bùng nổ gradient); còn nếu \(\lvert\lambda_{\max}\rvert = 0.8\) thì \(0.8^{50} \approx 0.000014\) (biến mất gradient)!&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Định lý phổ cho ma trận đối xứng (Spectral Theorem)&lt;/strong&gt;:
Ma trận hiệp phương sai và ma trận Hessian đều đối xứng, nên chúng luôn có giá trị riêng thực và hệ vector riêng trực giao—cơ sở trực tiếp của phân tích thành phần chính (PCA) và phân tích độ cong tối ưu hóa.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Số điều kiện (Condition Number \(\kappa = \lvert\lambda_{\max}/\lambda_{\min}\rvert\))&lt;/strong&gt;:
Đo mức độ “méo dẹt” của thung lũng mất mát: \(\kappa\) càng lớn, Gradient Descent càng dao động mạnh và hội tụ càng chậm.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-giá-trị-riêng-vector-riêng-và-kiểm-chứng-lũy-thừa-mathbfa10&quot;&gt;Giải thích: Tính tay giá trị riêng, vector riêng và kiểm chứng lũy thừa \(\mathbf{A}^{10}\)&lt;/h3&gt;

&lt;p&gt;Xét ma trận đối xứng \(\mathbf{A} = \begin{bmatrix} 3 &amp;amp; 1 \\ 1 &amp;amp; 3 \end{bmatrix}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Lập phương trình đặc trưng&lt;/strong&gt;:
\(\det(\mathbf{A} - \lambda\mathbf{I}) = \det\begin{bmatrix} 3 - \lambda &amp;amp; 1 \\ 1 &amp;amp; 3 - \lambda \end{bmatrix} = (3 - \lambda)^2 - 1 = \lambda^2 - 6\lambda + 8 = (\lambda - 4)(\lambda - 2) = 0.\)
Vậy hai giá trị riêng là \(\lambda_1 = 4\) và \(\lambda_2 = 2\). (Kiểm tra nhanh: vết \(\text{tr}(\mathbf{A}) = 3 + 3 = 6 = 4 + 2\); định thức \(\det(\mathbf{A}) = 9 - 1 = 8 = 4 \times 2\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tìm vector riêng tương ứng&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Với \(\lambda_1 = 4\): \((\mathbf{A} - 4\mathbf{I})\mathbf{v}_1 = \begin{bmatrix} -1 &amp;amp; 1 \\ 1 &amp;amp; -1 \end{bmatrix}\mathbf{v}_1 = \mathbf{0} \implies \mathbf{v}_1 = \begin{bmatrix} 1 \\ 1 \end{bmatrix}\).&lt;/li&gt;
      &lt;li&gt;Với \(\lambda_2 = 2\): \((\mathbf{A} - 2\mathbf{I})\mathbf{v}_2 = \begin{bmatrix} 1 &amp;amp; 1 \\ 1 &amp;amp; 1 \end{bmatrix}\mathbf{v}_2 = \mathbf{0} \implies \mathbf{v}_2 = \begin{bmatrix} 1 \\ -1 \end{bmatrix}\).
Dễ thấy \(\mathbf{v}_1 \cdot \mathbf{v}_2 = 1(1) + 1(-1) = 0\) (hai trục chính vuông góc nhau).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính nhanh \(\mathbf{A}^{10}\mathbf{x}\) cho \(\mathbf{x} = \begin{bmatrix} 2 \\ 0 \end{bmatrix} = \mathbf{v}_1 + \mathbf{v}_2\)&lt;/strong&gt;:
\(\mathbf{A}^{10}\mathbf{x} = 4^{10}\mathbf{v}_1 + 2^{10}\mathbf{v}_2 = 1{,}048{,}576\begin{bmatrix} 1 \\ 1 \end{bmatrix} + 1{,}024\begin{bmatrix} 1 \\ -1 \end{bmatrix} = \begin{bmatrix} 1{,}049{,}600 \\ 1{,}047{,}552 \end{bmatrix}.\)
Sau 10 bước, thành phần dọc theo \(\mathbf{v}_1\) đã lớn gấp hơn 1000 lần thành phần dọc theo \(\mathbf{v}_2\)—minh họa sống động cách giá trị riêng lớn nhất thống trị hoàn toàn động lực học của mạng sâu!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bài học này trình bày giá trị riêng (&lt;em&gt;eigenvalue&lt;/em&gt;) và vector riêng (&lt;em&gt;eigenvector&lt;/em&gt;) — những khái niệm cốt lõi để phân tích hành vi của phép biến đổi tuyến tính và các hàm bậc hai trong tối ưu hóa.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;định-nghĩa-và-trực-giác&quot;&gt;Định nghĩa và trực giác&lt;/h2&gt;

&lt;p&gt;Khi một ma trận tác động lên vector, thông thường cả hướng lẫn độ dài của vector đều thay đổi. Tuy nhiên, &lt;strong&gt;vector riêng&lt;/strong&gt; là những vector đặc biệt: dưới tác động của ma trận, phương của chúng không đổi mà chỉ bị co giãn theo một hệ số tỉ lệ.&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa-toán-học&quot;&gt;Định nghĩa toán học&lt;/h3&gt;

&lt;p&gt;Với ma trận vuông \(\mathbf{A}\) và vector khác không \(\mathbf{v}\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathbf{v}\) là &lt;strong&gt;vector riêng&lt;/strong&gt; của \(\mathbf{A}\),&lt;/li&gt;
  &lt;li&gt;\(\lambda\) là &lt;strong&gt;giá trị riêng&lt;/strong&gt; tương ứng,&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;nếu chúng thỏa mãn &lt;strong&gt;phương trình giá trị riêng&lt;/strong&gt;:&lt;/p&gt;

\[\mathbf{A}\mathbf{v} = \lambda\mathbf{v}\]

&lt;h3 id=&quot;diễn-giải-hình-học&quot;&gt;Diễn giải hình học&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Vector riêng:&lt;/strong&gt; các vector khác không giữ nguyên phương dưới phép biến đổi \(\mathbf{A}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Giá trị riêng:&lt;/strong&gt; hệ số vô hướng quy định mức co giãn của vector riêng tương ứng.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ý nghĩa theo giá trị của \(\lambda\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Nếu \(\lambda &amp;gt; 1\): vector riêng bị kéo giãn.&lt;/li&gt;
  &lt;li&gt;Nếu \(0 &amp;lt; \lambda &amp;lt; 1\): vector riêng bị co lại.&lt;/li&gt;
  &lt;li&gt;Nếu \(\lambda &amp;lt; 0\): vector riêng vừa bị co giãn vừa đổi chiều ngược lại.&lt;/li&gt;
  &lt;li&gt;Nếu \(\lambda = 0\): vector riêng bị ánh xạ về vector không.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;cách-tìm-giá-trị-riêng-và-vector-riêng&quot;&gt;Cách tìm giá trị riêng và vector riêng&lt;/h2&gt;

&lt;h3 id=&quot;bước-1-tìm-giá-trị-riêng&quot;&gt;Bước 1: Tìm giá trị riêng&lt;/h3&gt;

&lt;p&gt;Biến đổi phương trình giá trị riêng:
\(\mathbf{A}\mathbf{v} = \lambda\mathbf{v}\)
\(\mathbf{A}\mathbf{v} - \lambda\mathbf{v} = \mathbf{0}\)
\((\mathbf{A} - \lambda\mathbf{I})\mathbf{v} = \mathbf{0}\)&lt;/p&gt;

&lt;p&gt;Để hệ có nghiệm không tầm thường (\(\mathbf{v} \neq \mathbf{0}\)), ma trận \((\mathbf{A} - \lambda\mathbf{I})\) phải suy biến (&lt;em&gt;singular&lt;/em&gt;), tức là:&lt;/p&gt;

\[\det(\mathbf{A} - \lambda\mathbf{I}) = 0\]

&lt;p&gt;Phương trình này được gọi là &lt;strong&gt;phương trình đặc trưng&lt;/strong&gt; (&lt;em&gt;characteristic equation&lt;/em&gt;).&lt;/p&gt;

&lt;h3 id=&quot;bước-2-tìm-vector-riêng&quot;&gt;Bước 2: Tìm vector riêng&lt;/h3&gt;

&lt;p&gt;Với mỗi giá trị riêng \(\lambda_i\), ta giải hệ phương trình tuyến tính thuần nhất:
\((\mathbf{A} - \lambda_i\mathbf{I})\mathbf{v} = \mathbf{0}\)&lt;/p&gt;

&lt;p&gt;Tập nghiệm của hệ tạo thành &lt;strong&gt;không gian riêng&lt;/strong&gt; (&lt;em&gt;eigenspace&lt;/em&gt;) ứng với \(\lambda_i\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ví-dụ-chi-tiết&quot;&gt;Ví dụ chi tiết&lt;/h2&gt;

&lt;p&gt;Tìm giá trị riêng và vector riêng của ma trận \(\mathbf{A} = \begin{pmatrix} 3 &amp;amp; 1 \\ 0 &amp;amp; 2 \end{pmatrix}\).&lt;/p&gt;

&lt;h3 id=&quot;bước-1-tìm-giá-trị-riêng-1&quot;&gt;Bước 1: Tìm giá trị riêng&lt;/h3&gt;

\[\mathbf{A} - \lambda\mathbf{I} = \begin{pmatrix} 3 &amp;amp; 1 \\ 0 &amp;amp; 2 \end{pmatrix} - \lambda\begin{pmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{pmatrix} = \begin{pmatrix} 3-\lambda &amp;amp; 1 \\ 0 &amp;amp; 2-\lambda \end{pmatrix}\]

\[\det(\mathbf{A} - \lambda\mathbf{I}) = (3-\lambda)(2-\lambda) - (1)(0) = (3-\lambda)(2-\lambda) = 0\]

&lt;p&gt;Suy ra \(\lambda_1 = 3\) và \(\lambda_2 = 2\).&lt;/p&gt;

&lt;h3 id=&quot;bước-2-tìm-vector-riêng-1&quot;&gt;Bước 2: Tìm vector riêng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Với \(\lambda_1 = 3\):&lt;/strong&gt;
\((\mathbf{A} - 3\mathbf{I})\mathbf{v} = \begin{pmatrix} 0 &amp;amp; 1 \\ 0 &amp;amp; -1 \end{pmatrix}\begin{pmatrix} v_1 \\ v_2 \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;Hệ cho \(v_2 = 0\) và \(v_1\) tùy ý khác không. Chọn \(\mathbf{v}_1 = \begin{pmatrix} 1 \\ 0 \end{pmatrix}\) (mọi bội khác không của nó cũng là vector riêng).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Với \(\lambda_2 = 2\):&lt;/strong&gt;
\((\mathbf{A} - 2\mathbf{I})\mathbf{v} = \begin{pmatrix} 1 &amp;amp; 1 \\ 0 &amp;amp; 0 \end{pmatrix}\begin{pmatrix} v_1 \\ v_2 \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;Hệ cho \(v_1 + v_2 = 0\), hay \(v_2 = -v_1\). Chọn \(\mathbf{v}_2 = \begin{pmatrix} 1 \\ -1 \end{pmatrix}\) (hoặc mọi bội khác không của nó).&lt;/p&gt;

&lt;h3 id=&quot;kiểm-tra-lại-kết-quả&quot;&gt;Kiểm tra lại kết quả&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathbf{A}\mathbf{v}_1 = \begin{pmatrix} 3 &amp;amp; 1 \\ 0 &amp;amp; 2 \end{pmatrix}\begin{pmatrix} 1 \\ 0 \end{pmatrix} = \begin{pmatrix} 3 \\ 0 \end{pmatrix} = 3\begin{pmatrix} 1 \\ 0 \end{pmatrix} = 3\mathbf{v}_1\) ✓&lt;/li&gt;
  &lt;li&gt;\(\mathbf{A}\mathbf{v}_2 = \begin{pmatrix} 3 &amp;amp; 1 \\ 0 &amp;amp; 2 \end{pmatrix}\begin{pmatrix} 1 \\ -1 \end{pmatrix} = \begin{pmatrix} 2 \\ -2 \end{pmatrix} = 2\begin{pmatrix} 1 \\ -1 \end{pmatrix} = 2\mathbf{v}_2\) ✓&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;tính-chất-và-các-định-lý-quan-trọng&quot;&gt;Tính chất và các định lý quan trọng&lt;/h2&gt;

&lt;h3 id=&quot;các-tính-chất-chính&quot;&gt;Các tính chất chính&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tổng các giá trị riêng bằng vết của ma trận:&lt;/strong&gt;
\(\sum_{i=1}^n \lambda_i = \text{tr}(\mathbf{A}) = \sum_{i=1}^n a_{ii}\)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tích các giá trị riêng bằng định thức của ma trận:&lt;/strong&gt;
\(\prod_{i=1}^n \lambda_i = \det(\mathbf{A})\)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Các vector riêng ứng với các giá trị riêng phân biệt thì độc lập tuyến tính.&lt;/strong&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Nếu \(\mathbf{A}\) là ma trận thực đối xứng, mọi giá trị riêng đều là số thực và các vector riêng ứng với các giá trị riêng khác nhau trực giao với nhau.&lt;/strong&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;bội-số-của-giá-trị-riêng&quot;&gt;Bội số của giá trị riêng&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bội đại số&lt;/strong&gt; (&lt;em&gt;algebraic multiplicity&lt;/em&gt;): số lần \(\lambda\) xuất hiện với tư cách nghiệm của đa thức đặc trưng.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bội hình học&lt;/strong&gt; (&lt;em&gt;geometric multiplicity&lt;/em&gt;): số chiều của không gian riêng (số vector riêng độc lập tuyến tính tối đa ứng với \(\lambda\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Luôn có bất đẳng thức: bội hình học ≤ bội đại số.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;chéo-hóa-ma-trận-diagonalization&quot;&gt;Chéo hóa ma trận (&lt;em&gt;diagonalization&lt;/em&gt;)&lt;/h2&gt;

&lt;p&gt;Ma trận vuông \(\mathbf{A}\) được gọi là &lt;strong&gt;chéo hóa được&lt;/strong&gt; nếu tồn tại ma trận khả nghịch \(\mathbf{P}\) và ma trận đường chéo \(\mathbf{D}\) sao cho:&lt;/p&gt;

\[\mathbf{A} = \mathbf{P}\mathbf{D}\mathbf{P}^{-1}\]

&lt;p&gt;trong đó:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{D}\) là ma trận đường chéo chứa các giá trị riêng của \(\mathbf{A}\),&lt;/li&gt;
  &lt;li&gt;các cột của \(\mathbf{P}\) là các vector riêng tương ứng.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;lợi-ích-của-phép-chéo-hóa&quot;&gt;Lợi ích của phép chéo hóa&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính lũy thừa nhanh chóng:&lt;/strong&gt; \(\mathbf{A}^k = \mathbf{P}\mathbf{D}^k\mathbf{P}^{-1}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân tách hành vi biến đổi:&lt;/strong&gt; từng giá trị riêng mô tả riêng rẽ tác động co giãn của phép biến đổi dọc theo từng hướng vector riêng.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ứng-dụng-trong-tối-ưu-hóa&quot;&gt;Ứng dụng trong tối ưu hóa&lt;/h2&gt;

&lt;p&gt;Giá trị riêng và vector riêng đóng vai trò trọng tâm trong nhiều bài toán tối ưu:&lt;/p&gt;

&lt;h3 id=&quot;1-dạng-bậc-hai-và-tính-xác-định&quot;&gt;1. Dạng bậc hai và tính xác định&lt;/h3&gt;

&lt;p&gt;Với dạng bậc hai \(f(\mathbf{x}) = \mathbf{x}^T\mathbf{Q}\mathbf{x}\) (\(\mathbf{Q}\) đối xứng):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xác định dương&lt;/strong&gt; (&lt;em&gt;positive definite&lt;/em&gt;, \(f(\mathbf{x}) &amp;gt; 0\) với mọi \(\mathbf{x} \neq \mathbf{0}\)): mọi giá trị riêng của \(\mathbf{Q}\) đều dương.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nửa xác định dương&lt;/strong&gt; (&lt;em&gt;positive semidefinite&lt;/em&gt;, \(f(\mathbf{x}) \geq 0\)): mọi giá trị riêng đều không âm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xác định âm&lt;/strong&gt; (&lt;em&gt;negative definite&lt;/em&gt;, \(f(\mathbf{x}) &amp;lt; 0\) với mọi \(\mathbf{x} \neq \mathbf{0}\)): mọi giá trị riêng đều âm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Không xác định&lt;/strong&gt; (&lt;em&gt;indefinite&lt;/em&gt;, \(f(\mathbf{x})\) nhận cả giá trị dương và âm): có cả giá trị riêng dương lẫn âm.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-điều-kiện-tối-ưu-bậc-hai&quot;&gt;2. Điều kiện tối ưu bậc hai&lt;/h3&gt;

&lt;p&gt;Tại điểm tới hạn \(\mathbf{x}^*\) (thỏa mãn \(\nabla f(\mathbf{x}^*) = \mathbf{0}\)):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cực tiểu địa phương:&lt;/strong&gt; ma trận Hessian \(\nabla^2 f(\mathbf{x}^*)\) xác định dương (mọi giá trị riêng \(&amp;gt; 0\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cực đại địa phương:&lt;/strong&gt; ma trận Hessian xác định âm (mọi giá trị riêng \(&amp;lt; 0\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điểm yên ngựa:&lt;/strong&gt; ma trận Hessian không xác định (có cả giá trị riêng dương và âm).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-phân-tích-thành-phần-chính-pca&quot;&gt;3. Phân tích thành phần chính (PCA)&lt;/h3&gt;

&lt;p&gt;PCA tìm các phương có phương sai dữ liệu lớn nhất:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Các vector riêng của ma trận hiệp phương sai xác định các trục thành phần chính.&lt;/li&gt;
  &lt;li&gt;Các giá trị riêng tương ứng đo phương sai dữ liệu dọc theo từng trục đó.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-phân-tích-tốc-độ-hội-tụ&quot;&gt;4. Phân tích tốc độ hội tụ&lt;/h3&gt;

&lt;p&gt;Trong các thuật toán tối ưu lặp (với Hessian đối xứng xác định dương):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Số điều kiện&lt;/strong&gt; (&lt;em&gt;condition number&lt;/em&gt;) \(\kappa = \frac{\lambda_{\max}}{\lambda_{\min}}\) chi phối trực tiếp tốc độ hội tụ.&lt;/li&gt;
  &lt;li&gt;Số điều kiện càng lớn thì tốc độ hội tụ của các phương pháp bậc nhất càng chậm.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;5-phương-pháp-newton&quot;&gt;5. Phương pháp Newton&lt;/h3&gt;

&lt;p&gt;Phương pháp Newton sử dụng nghịch đảo của ma trận Hessian:
\(\mathbf{x}_{k+1} = \mathbf{x}_k - [\nabla^2 f(\mathbf{x}_k)]^{-1} \nabla f(\mathbf{x}_k)\)&lt;/p&gt;

&lt;p&gt;Các giá trị riêng của Hessian quyết định tính khả nghịch, độ ổn định và tốc độ hội tụ của thuật toán.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ví-dụ-ứng-dụng-trong-tối-ưu-hóa&quot;&gt;Ví dụ: Ứng dụng trong tối ưu hóa&lt;/h2&gt;

&lt;p&gt;Xét bài toán cực tiểu hóa \(f(x, y) = 2x^2 + 3y^2 + 2xy\).&lt;/p&gt;

&lt;p&gt;Ma trận Hessian của hàm là: \(\mathbf{H} = \begin{pmatrix} 4 &amp;amp; 2 \\ 2 &amp;amp; 6 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tìm giá trị riêng:&lt;/strong&gt;
\(\det(\mathbf{H} - \lambda\mathbf{I}) = (4-\lambda)(6-\lambda) - 4 = \lambda^2 - 10\lambda + 20 = 0\)&lt;/p&gt;

\[\lambda = \frac{10 \pm \sqrt{100-80}}{2} = \frac{10 \pm 2\sqrt{5}}{2} = 5 \pm \sqrt{5}\]

&lt;p&gt;Vì cả hai giá trị riêng đều dương (\(\lambda_1 = 5 + \sqrt{5} &amp;gt; 0\) và \(\lambda_2 = 5 - \sqrt{5} &amp;gt; 0\)), ma trận Hessian xác định dương, khẳng định gốc tọa độ \((0, 0)\) là cực tiểu toàn cục.&lt;/p&gt;

&lt;p&gt;Số điều kiện là \(\kappa = \frac{5 + \sqrt{5}}{5 - \sqrt{5}} \approx 2{,}62\), cho thấy bài toán có điều kiện số khá tốt đối với các thuật toán tối ưu hóa.&lt;/p&gt;

&lt;p&gt;Hiểu rõ giá trị riêng và vector riêng giúp nắm bắt sâu cấu trúc hình học và giải tích của bài toán tối ưu, từ đó lựa chọn thuật toán và đánh giá hội tụ hiệu quả hơn.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Eigenvectors and eigenvalues&lt;/td&gt;
          &lt;td&gt;Chapter 14, Essence of linear algebra](https://www.youtube.com/watch?v=PFDu9oVAE-g) — 3Blue1Brown, tiếng Anh. Trực quan hóa định nghĩa hình học: \(\mathbf{A}\mathbf{v}\) chỉ là bản co giãn của \(\mathbf{v}\) dọc theo cùng một phương.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=-GcrsEqzmsA&quot;&gt;MaDL - Eigenvalue and Singular Value Decomposition&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Trình bày phân tích giá trị riêng và phân tích giá trị suy biến (SVD), nối tiếp phần chéo hóa trong bài.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Phân tích giá trị riêng&lt;/td&gt;
          &lt;td&gt;Khoa học dữ liệu cơ bản](https://www.youtube.com/watch?v=OnLGH_5Ovg4) — Mat-chan, tiếng Việt. Video tiếng Việt giải thích phân tích giá trị riêng gắn với ngữ cảnh khoa học dữ liệu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-02-02 Ma trận và Phép biến đổi tuyến tính</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_02_02_Matrices_and_Linear_Transformations/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_02_02_Matrices_and_Linear_Transformations</id>
   <content type="html">&lt;p&gt;Nếu chỉ nhìn ma trận như một bảng Excel chứa đầy con số, phép nhân ma trận sẽ trông như một quy tắc nhân-rồi-cộng kỳ quặc và vô nghĩa. Nhưng ngay khi bạn đeo cặp kính hình học vào, mọi thứ bỗng bừng sáng: một ma trận \(m \times n\) chính là một cỗ máy biến đổi toàn bộ không gian \(\mathbb{R}^n\) sang \(\mathbb{R}^m\)—xoay, lật, kéo giãn hoặc chiếu bẹp nó xuống chiều thấp hơn. Mỗi tầng &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear&lt;/code&gt; hay tích chập trong mạng nơ-ron sâu đều là một phép biến đổi ma trận như vậy, và nhân nhiều ma trận liên tiếp chính là ghép nối các tầng mạng lại với nhau.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-góc-nhìn-thiết-yếu-về-ma-trận-và-phép-biến-đổi-tuyến-tính&quot;&gt;Kiến thức cần nhớ: Bốn góc nhìn thiết yếu về Ma trận và Phép biến đổi Tuyến tính&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phép nhân ma trận là phép hợp hàm (Composition of Transformations)&lt;/strong&gt;:
Áp dụng ma trận \(\mathbf{A}\) rồi đến \(\mathbf{B}\) tương đương với một phép biến đổi duy nhất \(\mathbf{B}\mathbf{A}\). Điều này giải thích ngay vì sao mạng nhiều tầng &lt;em&gt;không có hàm kích hoạt phi tuyến&lt;/em&gt; chỉ tương đương một ma trận duy nhất!&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tính không giao hoán và Chuyển vị (Non-commutativity &amp;amp; Transpose)&lt;/strong&gt;:
Thứ tự biến đổi cực kỳ quan trọng (\(\mathbf{A}\mathbf{B} \ne \mathbf{B}\mathbf{A}\)); còn ma trận chuyển vị \(\mathbf{W}^\top\) đóng vai trò truyền gradient ngược từ tầng sau về tầng trước trong lan truyền ngược.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hạng ma trận và Không gian ảnh/hạt nhân (Rank, Column Space, Null Space)&lt;/strong&gt;:
Hạng (&lt;em&gt;rank&lt;/em&gt;) đo số chiều thực sự sống sót sau phép biến đổi. Khi hạng bị sụt giảm (ma trận suy biến), thông tin bị nén mất không thể phục hồi—đây cũng chính là tư duy phía sau kỹ thuật nén mô hình &lt;strong&gt;LoRA (Low-Rank Adaptation)&lt;/strong&gt;.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Định thức và Ma trận nghịch đảo (Determinant &amp;amp; Inverse)&lt;/strong&gt;:
Định thức \(\det(\mathbf{A})\) đo hệ số phóng đại diện tích/thể tích của phép biến đổi; khi \(\det(\mathbf{A}) = 0\), không gian bị ép phẳng và phép biến đổi không còn khả nghịch.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-kiểm-chứng-bằng-tay-tính-không-giao-hoán-và-sự-ép-chiều&quot;&gt;Giải thích: Kiểm chứng bằng tay tính không giao hoán và sự ép chiều&lt;/h3&gt;

&lt;p&gt;Xét hai ma trận \(2 \times 2\): ma trận xoay \(90^\circ\) ngược chiều kim đồng hồ \(\mathbf{R} = \begin{bmatrix} 0 &amp;amp; -1 \\ 1 &amp;amp; 0 \end{bmatrix}\) và ma trận kéo giãn trục ngang gấp 2 lần \(\mathbf{S} = \begin{bmatrix} 2 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{bmatrix}\). Tác động lên điểm \(\mathbf{x} = \begin{bmatrix} 1 \\ 1 \end{bmatrix}\) theo hai thứ tự:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Kéo giãn trước, xoay sau (\(\mathbf{R}\mathbf{S}\)):&lt;/strong&gt;
\(\mathbf{R}\mathbf{S} = \begin{bmatrix} 0 &amp;amp; -1 \\ 1 &amp;amp; 0 \end{bmatrix}\begin{bmatrix} 2 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{bmatrix} = \begin{bmatrix} 0 &amp;amp; -1 \\ 2 &amp;amp; 0 \end{bmatrix} \implies (\mathbf{R}\mathbf{S})\mathbf{x} = \begin{bmatrix} -1 \\ 2 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xoay trước, kéo giãn sau (\(\mathbf{S}\mathbf{R}\)):&lt;/strong&gt;
\(\mathbf{S}\mathbf{R} = \begin{bmatrix} 2 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{bmatrix}\begin{bmatrix} 0 &amp;amp; -1 \\ 1 &amp;amp; 0 \end{bmatrix} = \begin{bmatrix} 0 &amp;amp; -2 \\ 1 &amp;amp; 0 \end{bmatrix} \implies (\mathbf{S}\mathbf{R})\mathbf{x} = \begin{bmatrix} -2 \\ 1 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra định thức (hệ số diện tích)&lt;/strong&gt;:
\(\det(\mathbf{R}) = 0(0) - (-1)(1) = 1\) (phép xoay bảo toàn diện tích), \(\det(\mathbf{S}) = 2(1) - 0 = 2\) (tăng gấp đôi diện tích), và \(\det(\mathbf{R}\mathbf{S}) = 0 - (-2) = 2 = \det(\mathbf{R})\det(\mathbf{S})\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Thứ tự nhân ma trận hoàn toàn thay đổi điểm đến, nhưng tổng hệ số phóng đại diện tích vẫn luôn bằng tích các định thức thành phần.&lt;/p&gt;

&lt;p&gt;Bài học này trình bày ma trận (&lt;em&gt;matrix&lt;/em&gt;), các phép toán ma trận và phép biến đổi tuyến tính (&lt;em&gt;linear transformation&lt;/em&gt;) — những công cụ cơ bản để biểu diễn và giải các bài toán tối ưu hóa.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ma-trận-và-các-phép-toán-ma-trận&quot;&gt;Ma trận và các phép toán ma trận&lt;/h2&gt;

&lt;h3 id=&quot;ma-trận-là-gì&quot;&gt;Ma trận là gì?&lt;/h3&gt;

&lt;p&gt;Một &lt;strong&gt;ma trận&lt;/strong&gt; là bảng chữ nhật gồm các số được sắp xếp theo hàng và cột. Ma trận dùng để biểu diễn dữ liệu, phép biến đổi, hệ phương trình và quan hệ giữa các biến.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dạng tổng quát:&lt;/strong&gt;
\(\mathbf{A} = \begin{pmatrix} 
a_{11} &amp;amp; a_{12} &amp;amp; \cdots &amp;amp; a_{1n} \\
a_{21} &amp;amp; a_{22} &amp;amp; \cdots &amp;amp; a_{2n} \\
\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\
a_{m1} &amp;amp; a_{m2} &amp;amp; \cdots &amp;amp; a_{mn}
\end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;Đây là ma trận kích thước \(m \times n\) (\(m\) hàng, \(n\) cột).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;
\(\mathbf{A} = \begin{pmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 4 &amp;amp; 5 &amp;amp; 6 \end{pmatrix}\) là ma trận kích thước \(2 \times 3\).&lt;/p&gt;

&lt;h3 id=&quot;phép-cộng-ma-trận&quot;&gt;Phép cộng ma trận&lt;/h3&gt;

&lt;p&gt;Hai ma trận cùng kích thước được cộng bằng cách cộng từng cặp phần tử tương ứng:&lt;/p&gt;

\[\mathbf{A} + \mathbf{B} = \begin{pmatrix} a_{11} + b_{11} &amp;amp; a_{12} + b_{12} \\ a_{21} + b_{21} &amp;amp; a_{22} + b_{22} \end{pmatrix}\]

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;
\(\begin{pmatrix} 1 &amp;amp; 2 \\ 3 &amp;amp; 4 \end{pmatrix} + \begin{pmatrix} 5 &amp;amp; 6 \\ 7 &amp;amp; 8 \end{pmatrix} = \begin{pmatrix} 6 &amp;amp; 8 \\ 10 &amp;amp; 12 \end{pmatrix}\)&lt;/p&gt;

&lt;h3 id=&quot;phép-nhân-với-vô-hướng&quot;&gt;Phép nhân với vô hướng&lt;/h3&gt;

&lt;p&gt;Nhân mọi phần tử của ma trận với cùng một số thực \(c\):&lt;/p&gt;

\[c\mathbf{A} = \begin{pmatrix} ca_{11} &amp;amp; ca_{12} \\ ca_{21} &amp;amp; ca_{22} \end{pmatrix}\]

&lt;h3 id=&quot;phép-nhân-ma-trận&quot;&gt;Phép nhân ma trận&lt;/h3&gt;

&lt;p&gt;Với hai ma trận \(\mathbf{A}_{m \times n}\) và \(\mathbf{B}_{n \times p}\), tích \(\mathbf{C}_{m \times p} = \mathbf{AB}\) có phần tử ở hàng \(i\), cột \(j\) bằng tích vô hướng của hàng \(i\) thuộc \(\mathbf{A}\) với cột \(j\) thuộc \(\mathbf{B}\):&lt;/p&gt;

\[c_{ij} = \sum_{k=1}^{n} a_{ik} b_{kj}\]

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;
\(\begin{pmatrix} 1 &amp;amp; 2 \\ 3 &amp;amp; 4 \end{pmatrix} \begin{pmatrix} 5 &amp;amp; 6 \\ 7 &amp;amp; 8 \end{pmatrix} = \begin{pmatrix} 1 \cdot 5 + 2 \cdot 7 &amp;amp; 1 \cdot 6 + 2 \cdot 8 \\ 3 \cdot 5 + 4 \cdot 7 &amp;amp; 3 \cdot 6 + 4 \cdot 8 \end{pmatrix} = \begin{pmatrix} 19 &amp;amp; 22 \\ 43 &amp;amp; 50 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lưu ý quan trọng:&lt;/strong&gt; Phép nhân ma trận &lt;strong&gt;không có tính giao hoán&lt;/strong&gt;; nhìn chung \(\mathbf{AB} \neq \mathbf{BA}\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;phép-biến-đổi-tuyến-tính&quot;&gt;Phép biến đổi tuyến tính&lt;/h2&gt;

&lt;p&gt;Một &lt;strong&gt;phép biến đổi tuyến tính&lt;/strong&gt; là ánh xạ \(T: \mathbb{R}^n \to \mathbb{R}^m\) bảo toàn phép cộng vector và phép nhân vô hướng. Mọi phép biến đổi tuyến tính giữa các không gian hữu hạn chiều đều có thể biểu diễn bằng một ma trận.&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa&quot;&gt;Định nghĩa&lt;/h3&gt;

&lt;p&gt;Ánh xạ \(T(\mathbf{v}) = \mathbf{Av}\) là tuyến tính khi và chỉ khi thỏa mãn hai tính chất:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính cộng tính (&lt;em&gt;additivity&lt;/em&gt;):&lt;/strong&gt; \(T(\mathbf{u} + \mathbf{v}) = T(\mathbf{u}) + T(\mathbf{v})\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính thuần nhất (&lt;em&gt;homogeneity&lt;/em&gt;):&lt;/strong&gt; \(T(c\mathbf{v}) = cT(\mathbf{v})\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Hai điều kiện này có thể gộp thành: \(T(c_1\mathbf{u} + c_2\mathbf{v}) = c_1T(\mathbf{u}) + c_2T(\mathbf{v})\).&lt;/p&gt;

&lt;h3 id=&quot;phép-nhân-ma-trậnvector&quot;&gt;Phép nhân ma trận–vector&lt;/h3&gt;

&lt;p&gt;Nếu \(\mathbf{A}\) là ma trận \(m \times n\) và \(\mathbf{v}\) là vector cột \(n \times 1\), thì tích \(\mathbf{Av}\) là vector cột \(m \times 1\):&lt;/p&gt;

\[\mathbf{w} = \mathbf{Av} = \begin{pmatrix} 
a_{11}v_1 + a_{12}v_2 + \cdots + a_{1n}v_n \\
a_{21}v_1 + a_{22}v_2 + \cdots + a_{2n}v_n \\
\vdots \\
a_{m1}v_1 + a_{m2}v_2 + \cdots + a_{mn}v_n
\end{pmatrix}\]

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;
\(\begin{pmatrix} 2 &amp;amp; 1 \\ 0 &amp;amp; 3 \end{pmatrix} \begin{pmatrix} 4 \\ 5 \end{pmatrix} = \begin{pmatrix} 2 \cdot 4 + 1 \cdot 5 \\ 0 \cdot 4 + 3 \cdot 5 \end{pmatrix} = \begin{pmatrix} 13 \\ 15 \end{pmatrix}\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;các-phép-biến-đổi-hai-chiều-thông-dụng&quot;&gt;Các phép biến đổi hai chiều thông dụng&lt;/h2&gt;

&lt;p&gt;Xét các phép biến đổi hình học trong mặt phẳng giúp ta dễ hình dung cách ma trận tác động lên vector.&lt;/p&gt;

&lt;h3 id=&quot;phép-co-giãn-scaling&quot;&gt;Phép co giãn (&lt;em&gt;scaling&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ma trận co giãn:&lt;/strong&gt;
\(\mathbf{S} = \begin{pmatrix} s_x &amp;amp; 0 \\ 0 &amp;amp; s_y \end{pmatrix}\)&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Co giãn tọa độ \(x\) theo hệ số \(s_x\) và tọa độ \(y\) theo hệ số \(s_y\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; \(\begin{pmatrix} 2 &amp;amp; 0 \\ 0 &amp;amp; 3 \end{pmatrix}\) nhân đôi hoành độ \(x\) và nhân ba tung độ \(y\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;phép-quay-rotation&quot;&gt;Phép quay (&lt;em&gt;rotation&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ma trận quay ngược chiều kim đồng hồ một góc \(\theta\):&lt;/strong&gt;
\(\mathbf{R} = \begin{pmatrix} \cos\theta &amp;amp; -\sin\theta \\ \sin\theta &amp;amp; \cos\theta \end{pmatrix}\)&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; phép quay \(90^\circ\) có ma trận \(\begin{pmatrix} 0 &amp;amp; -1 \\ 1 &amp;amp; 0 \end{pmatrix}\), ánh xạ \((x, y) \mapsto (-y, x)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;phép-phản-xạ-reflection&quot;&gt;Phép phản xạ (&lt;em&gt;reflection&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phản xạ qua trục \(x\):&lt;/strong&gt;
\(\mathbf{F}_x = \begin{pmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; -1 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phản xạ qua trục \(y\):&lt;/strong&gt;
\(\mathbf{F}_y = \begin{pmatrix} -1 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phản xạ qua đường thẳng \(y = x\):&lt;/strong&gt;
\(\mathbf{F}_{y=x} = \begin{pmatrix} 0 &amp;amp; 1 \\ 1 &amp;amp; 0 \end{pmatrix}\)&lt;/p&gt;

&lt;h3 id=&quot;phép-cắt-shearing&quot;&gt;Phép cắt (&lt;em&gt;shearing&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phép cắt theo phương ngang:&lt;/strong&gt;
\(\mathbf{H} = \begin{pmatrix} 1 &amp;amp; k \\ 0 &amp;amp; 1 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;Ánh xạ \((x, y) \mapsto (x + ky, y)\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;các-loại-ma-trận-đặc-biệt&quot;&gt;Các loại ma trận đặc biệt&lt;/h2&gt;

&lt;h3 id=&quot;ma-trận-đơn-vị-identity-matrix&quot;&gt;Ma trận đơn vị (&lt;em&gt;identity matrix&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ma trận đơn vị&lt;/strong&gt; \(\mathbf{I}\) đóng vai trò phần tử đơn vị (tương tự số 1) trong phép nhân ma trận:&lt;/p&gt;

\[\mathbf{I}_n = \begin{pmatrix} 
1 &amp;amp; 0 &amp;amp; \cdots &amp;amp; 0 \\
0 &amp;amp; 1 &amp;amp; \cdots &amp;amp; 0 \\
\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\
0 &amp;amp; 0 &amp;amp; \cdots &amp;amp; 1
\end{pmatrix}\]

&lt;p&gt;&lt;strong&gt;Tính chất:&lt;/strong&gt; \(\mathbf{AI} = \mathbf{IA} = \mathbf{A}\) với mọi ma trận \(\mathbf{A}\) có kích thước phù hợp.&lt;/p&gt;

&lt;h3 id=&quot;ma-trận-chuyển-vị-transpose&quot;&gt;Ma trận chuyển vị (&lt;em&gt;transpose&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ma trận chuyển vị&lt;/strong&gt; \(\mathbf{A}^T\) thu được bằng cách đổi hàng thành cột (đối xứng qua đường chéo chính):&lt;/p&gt;

\[\text{Nếu } \mathbf{A} = \begin{pmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 4 &amp;amp; 5 &amp;amp; 6 \end{pmatrix}, \text{ thì } \mathbf{A}^T = \begin{pmatrix} 1 &amp;amp; 4 \\ 2 &amp;amp; 5 \\ 3 &amp;amp; 6 \end{pmatrix}\]

&lt;p&gt;&lt;strong&gt;Các tính chất:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[(\mathbf{A}^T)^T = \mathbf{A}\]
  &lt;/li&gt;
  &lt;li&gt;
\[(\mathbf{A} + \mathbf{B})^T = \mathbf{A}^T + \mathbf{B}^T\]
  &lt;/li&gt;
  &lt;li&gt;
\[(\mathbf{AB})^T = \mathbf{B}^T\mathbf{A}^T\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;ma-trận-đối-xứng-symmetric-matrix&quot;&gt;Ma trận đối xứng (&lt;em&gt;symmetric matrix&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Một ma trận vuông được gọi là &lt;strong&gt;đối xứng&lt;/strong&gt; nếu \(\mathbf{A} = \mathbf{A}^T\):&lt;/p&gt;

\[\mathbf{A} = \begin{pmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 2 &amp;amp; 4 &amp;amp; 5 \\ 3 &amp;amp; 5 &amp;amp; 6 \end{pmatrix}\]

&lt;p&gt;Ma trận đối xứng sở hữu nhiều tính chất đặc biệt quan trọng trong tối ưu hóa.&lt;/p&gt;

&lt;h3 id=&quot;ma-trận-nghịch-đảo-inverse&quot;&gt;Ma trận nghịch đảo (&lt;em&gt;inverse&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ma trận nghịch đảo&lt;/strong&gt; \(\mathbf{A}^{-1}\) của ma trận vuông \(\mathbf{A}\) thỏa mãn:&lt;/p&gt;

\[\mathbf{A}\mathbf{A}^{-1} = \mathbf{A}^{-1}\mathbf{A} = \mathbf{I}\]

&lt;p&gt;&lt;strong&gt;Trường hợp ma trận \(2 \times 2\):&lt;/strong&gt;
\(\mathbf{A}^{-1} = \frac{1}{\det(\mathbf{A})} \begin{pmatrix} d &amp;amp; -b \\ -c &amp;amp; a \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;trong đó \(\mathbf{A} = \begin{pmatrix} a &amp;amp; b \\ c &amp;amp; d \end{pmatrix}\) và \(\det(\mathbf{A}) = ad - bc\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Lưu ý:&lt;/strong&gt; Không phải mọi ma trận vuông đều có nghịch đảo. Ma trận &lt;strong&gt;khả nghịch&lt;/strong&gt; (&lt;em&gt;invertible&lt;/em&gt;, hay không suy biến — &lt;em&gt;non-singular&lt;/em&gt;) khi và chỉ khi định thức của nó khác không.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ứng-dụng-trong-tối-ưu-hóa&quot;&gt;Ứng dụng trong tối ưu hóa&lt;/h2&gt;

&lt;p&gt;Ma trận và phép biến đổi tuyến tính xuất hiện xuyên suốt trong tối ưu hóa:&lt;/p&gt;

&lt;h3 id=&quot;1-hệ-phương-trình-tuyến-tính&quot;&gt;1. Hệ phương trình tuyến tính&lt;/h3&gt;

&lt;p&gt;Nhiều bài toán tối ưu quy về việc giải hệ \(\mathbf{Ax} = \mathbf{b}\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Nghiệm duy nhất:&lt;/strong&gt; \(\mathbf{x} = \mathbf{A}^{-1}\mathbf{b}\) (khi \(\mathbf{A}\) khả nghịch).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bình phương tối thiểu:&lt;/strong&gt; cực tiểu hóa \(\|\mathbf{Ax} - \mathbf{b}\|^2\) khi hệ không có nghiệm chính xác.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-dạng-bậc-hai-quadratic-form&quot;&gt;2. Dạng bậc hai (&lt;em&gt;quadratic form&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Hàm mục tiêu bậc hai xuất hiện rất phổ biến trong tối ưu hóa:
\(f(\mathbf{x}) = \mathbf{x}^T\mathbf{Q}\mathbf{x} + \mathbf{c}^T\mathbf{x} + d\)&lt;/p&gt;

&lt;p&gt;Ma trận \(\mathbf{Q}\) quyết định độ cong và tính lồi của hàm số.&lt;/p&gt;

&lt;h3 id=&quot;3-quy-hoạch-tuyến-tính-linear-programming&quot;&gt;3. Quy hoạch tuyến tính (&lt;em&gt;linear programming&lt;/em&gt;)&lt;/h3&gt;

&lt;p&gt;Dạng chuẩn: cực tiểu hóa \(\mathbf{c}^T\mathbf{x}\) với các ràng buộc \(\mathbf{Ax} = \mathbf{b}\), \(\mathbf{x} \geq \mathbf{0}\).&lt;/p&gt;

&lt;h3 id=&quot;4-biểu-diễn-ràng-buộc&quot;&gt;4. Biểu diễn ràng buộc&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ràng buộc đẳng thức:&lt;/strong&gt; \(\mathbf{Ax} = \mathbf{b}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ràng buộc bất đẳng thức:&lt;/strong&gt; \(\mathbf{Ax} \leq \mathbf{b}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;5-phép-đổi-biến&quot;&gt;5. Phép đổi biến&lt;/h3&gt;

&lt;p&gt;Phép đổi biến tuyến tính \(\mathbf{y} = \mathbf{T}\mathbf{x}\) thường giúp đơn giản hóa cấu trúc của bài toán tối ưu.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-tối-ưu-danh-mục-đầu-tư&quot;&gt;Ví dụ: Tối ưu danh mục đầu tư&lt;/h3&gt;

&lt;p&gt;Trong tài chính, bài toán cực tiểu hóa rủi ro danh mục đầu tư có dạng:
\(\text{minimize } \mathbf{w}^T\mathbf{\Sigma}\mathbf{w}\)&lt;/p&gt;

&lt;p&gt;trong đó \(\mathbf{w}\) là vector trọng số phân bổ vốn và \(\mathbf{\Sigma}\) là ma trận hiệp phương sai lợi suất của các tài sản.&lt;/p&gt;

&lt;p&gt;Nắm vững ma trận và phép biến đổi tuyến tính giúp ta mô hình hóa, phân tích và giải hiệu quả nhiều lớp bài toán tối ưu hóa khác nhau.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Linear transformations and matrices&lt;/td&gt;
          &lt;td&gt;Chapter 3, Essence of linear algebra](https://www.youtube.com/watch?v=kYB8IZa5AuE) — 3Blue1Brown, tiếng Anh. Giải thích bản chất ma trận như một phép biến đổi tuyến tính chứ không chỉ là bảng số.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Matrix multiplication as composition&lt;/td&gt;
          &lt;td&gt;Chapter 4, Essence of linear algebra](https://www.youtube.com/watch?v=XkY2DOUCWMU) — 3Blue1Brown, tiếng Anh. Minh họa phép nhân ma trận chính là phép hợp hai phép biến đổi tuyến tính liên tiếp.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Inverse matrices, column space and null space&lt;/td&gt;
          &lt;td&gt;Chapter 7, Essence of linear algebra](https://www.youtube.com/watch?v=uQhTuRlWMxw) — 3Blue1Brown, tiếng Anh. Trình bày trực quan về ma trận nghịch đảo, không gian cột và không gian hạch, gắn với điều kiện giải hệ phương trình ở cuối bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-02-01 Vector và Không gian Vector</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_02_01_Vectors_and_Vector_Spaces/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_02_01_Vectors_and_Vector_Spaces</id>
   <content type="html">&lt;p&gt;Trong những mô hình ngôn ngữ nổi tiếng, phép toán huyền thoại \(\text{vector}(\text{&quot;Vua&quot;}) - \text{vector}(\text{&quot;Nam&quot;}) + \text{vector}(\text{&quot;Nữ&quot;}) \approx \text{vector}(\text{&quot;Hoàng hậu&quot;})\) từng khiến cả giới công nghệ kinh ngạc. Điều kỳ diệu ấy không phải phép thuật—nó là hệ quả trực tiếp của cấu trúc &lt;strong&gt;không gian vector&lt;/strong&gt;, nơi ngữ nghĩa được ánh xạ thành hướng và khoảng cách hình học. Bài học này xây dựng nền tảng chặt chẽ về vector, tổ hợp tuyến tính, độc lập tuyến tính, chuẩn và tích vô hướng để bạn làm chủ ngôn ngữ biểu diễn dữ liệu của Deep Learning.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-khái-niệm-xương-sống-của-không-gian-vector&quot;&gt;Kiến thức cần nhớ: Bốn khái niệm xương sống của Không gian Vector&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tổ hợp tuyến tính và Không gian sinh (Linear Combination &amp;amp; Span)&lt;/strong&gt;:
Mô tả tập hợp tất cả các điểm có thể tạo ra từ một bộ vector cơ sở; một lớp mạng tuyến tính thực chất đang lấy tổ hợp tuyến tính các cột của ma trận trọng số.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Độc lập tuyến tính và Số chiều (Linear Independence &amp;amp; Dimension)&lt;/strong&gt;:
Phát hiện sự dư thừa trong dữ liệu: nếu một đặc trưng là tổ hợp tuyến tính của các đặc trưng khác, không gian biểu diễn thực tế có chiều nhỏ hơn số cột bạn tưởng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Chuẩn vector (Vector Norms — \(L_1, L_2, L_\infty\))&lt;/strong&gt;:
Định nghĩa “độ dài” và “khoảng cách”: chuẩn \(L_2\) gắn với khoảng cách Euclid và Weight Decay (Ridge), còn chuẩn \(L_1\) tạo ra tính thưa (&lt;em&gt;sparsity&lt;/em&gt;), đẩy nhiều trọng số về đúng \(0\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tích vô hướng và Độ tương đồng Cosine (Dot Product &amp;amp; Cosine Similarity)&lt;/strong&gt;:
Liên kết đại số với hình học qua công thức \(\mathbf{u} \cdot \mathbf{v} = \|\mathbf{u}\|_2 \|\mathbf{v}\|_2 \cos\theta\)—phép toán trung tâm của cả phép chiếu, phân loại tuyến tính lẫn cơ chế Self-Attention trong Transformer.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-chuẩn-l_1-l_2-và-độ-tương-đồng-cosine-giữa-hai-embedding&quot;&gt;Giải thích: Tính tay chuẩn \(L_1, L_2\) và độ tương đồng Cosine giữa hai embedding&lt;/h3&gt;

&lt;p&gt;Giả sử hai câu văn được mã hóa thành hai vector embedding 3 chiều: \(\mathbf{u} = (1, 2, 2)\) và \(\mathbf{v} = (2, 1, -2)\). Hãy tính tay toàn bộ các đại lượng hình học quan trọng:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Chuẩn \(L_1\) và \(L_2\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(\|\mathbf{u}\|_1 = \lvert 1 \rvert + \lvert 2 \rvert + \lvert 2 \rvert = 5\); \(\|\mathbf{u}\|_2 = \sqrt{1^2 + 2^2 + 2^2} = \sqrt{9} = 3\).&lt;/li&gt;
      &lt;li&gt;\(\|\mathbf{v}\|_1 = \lvert 2 \rvert + \lvert 1 \rvert + \lvert -2 \rvert = 5\); \(\|\mathbf{v}\|_2 = \sqrt{2^2 + 1^2 + (-2)^2} = \sqrt{9} = 3\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích vô hướng&lt;/strong&gt;:
\(\mathbf{u} \cdot \mathbf{v} = 1(2) + 2(1) + 2(-2) = 2 + 2 - 4 = 0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Góc và Độ tương đồng Cosine&lt;/strong&gt;:
\(\cos\theta = \frac{\mathbf{u} \cdot \mathbf{v}}{\|\mathbf{u}\|_2 \|\mathbf{v}\|_2} = \frac{0}{3 \times 3} = 0 \implies \theta = 90^\circ.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng cách Euclid giữa hai điểm&lt;/strong&gt;:
\(\|\mathbf{u} - \mathbf{v}\|_2 = \sqrt{(1-2)^2 + (2-1)^2 + (2 - (-2))^2} = \sqrt{1 + 1 + 16} = \sqrt{18} \approx 4.243.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Dù hai vector có cùng độ dài (\(3\)), tích vô hướng bằng \(0\) chứng tỏ chúng &lt;strong&gt;trực giao&lt;/strong&gt; (độc lập về mặt hướng)—trong hệ thống tìm kiếm ngữ nghĩa (RAG), cặp văn bản này sẽ bị chấm điểm tương đồng bằng \(0\).&lt;/p&gt;

&lt;p&gt;Bài học này giới thiệu vector, không gian vector và các khái niệm nền tảng của đại số tuyến tính trong bối cảnh tối ưu hóa.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;vector-và-không-gian-vector-mathbbrn&quot;&gt;Vector và không gian vector (\(\mathbb{R}^n\))&lt;/h2&gt;

&lt;h3 id=&quot;vector-là-gì&quot;&gt;Vector là gì?&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Vector:&lt;/strong&gt; Có thể hình dung vector như một mũi tên trong không gian, mang cả hướng lẫn độ lớn (độ dài). Về mặt đại số, vector là một bộ số thực có thứ tự, tương tự như tọa độ. Chẳng hạn, trong mặt phẳng 2D, vector \(\mathbf{v} = \begin{pmatrix} 3 \\ 4 \end{pmatrix}\) biểu diễn dịch chuyển 3 đơn vị theo trục \(x\) và 4 đơn vị theo trục \(y\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hai cách nhìn — hình học và đại số:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Hình học:&lt;/strong&gt; vector là mũi tên có hướng và độ lớn.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Đại số:&lt;/strong&gt; vector là một bộ có thứ tự các số thực.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;không-gian-vector&quot;&gt;Không gian vector&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Không gian vector (\(\mathbb{R}^n\)):&lt;/strong&gt; là tập hợp tất cả các vector gồm \(n\) thành phần thực. Chẳng hạn, \(\mathbb{R}^2\) gồm mọi vector 2 thành phần, tương ứng với các điểm hoặc mũi tên trên mặt phẳng 2D.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;\(\mathbb{R}^2 = \left\{\begin{pmatrix} x \\ y \end{pmatrix} : x, y \in \mathbb{R}\right\}\) (mặt phẳng)&lt;/li&gt;
      &lt;li&gt;\(\mathbb{R}^3 = \left\{\begin{pmatrix} x \\ y \\ z \end{pmatrix} : x, y, z \in \mathbb{R}\right\}\) (không gian 3D)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;các-phép-toán-trên-vector&quot;&gt;Các phép toán trên vector&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phép cộng vector:&lt;/strong&gt;
\(\mathbf{u} + \mathbf{v} = \begin{pmatrix} u_1 \\ u_2 \\ \vdots \\ u_n \end{pmatrix} + \begin{pmatrix} v_1 \\ v_2 \\ \vdots \\ v_n \end{pmatrix} = \begin{pmatrix} u_1 + v_1 \\ u_2 + v_2 \\ \vdots \\ u_n + v_n \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phép nhân với vô hướng:&lt;/strong&gt;
\(c\mathbf{v} = c \begin{pmatrix} v_1 \\ v_2 \\ \vdots \\ v_n \end{pmatrix} = \begin{pmatrix} cv_1 \\ cv_2 \\ \vdots \\ cv_n \end{pmatrix}\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;độc-lập-tuyến-tính-cơ-sở-và-số-chiều&quot;&gt;Độc lập tuyến tính, cơ sở và số chiều&lt;/h2&gt;

&lt;h3 id=&quot;độc-lập-tuyến-tính&quot;&gt;Độc lập tuyến tính&lt;/h3&gt;

&lt;p&gt;Một hệ vector \(\{\mathbf{v}_1, \mathbf{v}_2, \ldots, \mathbf{v}_k\}\) được gọi là &lt;strong&gt;độc lập tuyến tính&lt;/strong&gt; nếu phương trình&lt;/p&gt;

\[c_1\mathbf{v}_1 + c_2\mathbf{v}_2 + \cdots + c_k\mathbf{v}_k = \mathbf{0}\]

&lt;p&gt;chỉ có nghiệm duy nhất \(c_1 = c_2 = \cdots = c_k = 0\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ý nghĩa trực quan:&lt;/strong&gt; Một hệ vector độc lập tuyến tính khi không có vector nào trong hệ có thể biểu diễn dưới dạng tổ hợp tuyến tính (nhân vô hướng rồi cộng) của các vector còn lại. Mỗi vector đóng góp thêm một hướng độc lập mới.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ trong \(\mathbb{R}^2\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{v}_1 = \begin{pmatrix} 1 \\ 0 \end{pmatrix}\) và \(\mathbf{v}_2 = \begin{pmatrix} 0 \\ 1 \end{pmatrix}\) là độc lập tuyến tính.&lt;/li&gt;
  &lt;li&gt;\(\mathbf{v}_1 = \begin{pmatrix} 1 \\ 2 \end{pmatrix}\) và \(\mathbf{v}_2 = \begin{pmatrix} 2 \\ 4 \end{pmatrix}\) là phụ thuộc tuyến tính (vì \(\mathbf{v}_2 = 2\mathbf{v}_1\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;cơ-sở&quot;&gt;Cơ sở&lt;/h3&gt;

&lt;p&gt;Một &lt;strong&gt;cơ sở&lt;/strong&gt; (&lt;em&gt;basis&lt;/em&gt;) của không gian vector là tập hợp tối thiểu các vector độc lập tuyến tính sao cho &lt;em&gt;mọi&lt;/em&gt; vector trong không gian đó đều có thể biểu diễn bằng tổ hợp tuyến tính của chúng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính chất của một cơ sở:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Các vector trong cơ sở độc lập tuyến tính.&lt;/li&gt;
  &lt;li&gt;Chúng sinh ra toàn bộ không gian vector.&lt;/li&gt;
  &lt;li&gt;Mọi vector trong không gian đều có biểu diễn duy nhất dưới dạng tổ hợp tuyến tính của các vector cơ sở.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Cơ sở chính tắc của \(\mathbb{R}^n\):&lt;/strong&gt;
\(\mathbf{e}_1 = \begin{pmatrix} 1 \\ 0 \\ \vdots \\ 0 \end{pmatrix}, \mathbf{e}_2 = \begin{pmatrix} 0 \\ 1 \\ \vdots \\ 0 \end{pmatrix}, \ldots, \mathbf{e}_n = \begin{pmatrix} 0 \\ 0 \\ \vdots \\ 1 \end{pmatrix}\)&lt;/p&gt;

&lt;h3 id=&quot;số-chiều&quot;&gt;Số chiều&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Số chiều&lt;/strong&gt; (&lt;em&gt;dimension&lt;/em&gt;) của một không gian vector là số lượng vector có trong một cơ sở bất kỳ của nó, cho biết cần bao nhiêu hướng độc lập để xác định mọi điểm trong không gian.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
\[\dim(\mathbb{R}^2) = 2\]
  &lt;/li&gt;
  &lt;li&gt;
\[\dim(\mathbb{R}^3) = 3\]
  &lt;/li&gt;
  &lt;li&gt;
\[\dim(\mathbb{R}^n) = n\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;chuẩn-của-vector&quot;&gt;Chuẩn của vector&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Chuẩn&lt;/strong&gt; (&lt;em&gt;norm&lt;/em&gt;) là một hàm gán “độ dài” hay “độ lớn” cho mỗi vector, mở rộng khái niệm khoảng cách từ gốc tọa độ.&lt;/p&gt;

&lt;h3 id=&quot;tính-chất-của-chuẩn&quot;&gt;Tính chất của chuẩn&lt;/h3&gt;

&lt;p&gt;Mọi chuẩn \(\|\cdot\|\) đều phải thỏa mãn ba tính chất:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính không âm:&lt;/strong&gt; \(\|\mathbf{x}\| \geq 0\), và \(\|\mathbf{x}\| = 0\) khi và chỉ khi \(\mathbf{x} = \mathbf{0}\).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Tính thuần nhất tuyệt đối:&lt;/strong&gt; $$|t\mathbf{x}| =&lt;/td&gt;
          &lt;td&gt;t&lt;/td&gt;
          &lt;td&gt;|\mathbf{x}|\(với mọi số thực\)t$$.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bất đẳng thức tam giác:&lt;/strong&gt; \(\|\mathbf{x} + \mathbf{y}\| \leq \|\mathbf{x}\| + \|\mathbf{y}\|\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;các-chuẩn-thông-dụng&quot;&gt;Các chuẩn thông dụng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Chuẩn Euclid (chuẩn \(L_2\)):&lt;/strong&gt;
\(\|\mathbf{x}\|_2 = \sqrt{\sum_{i=1}^n x_i^2} = \sqrt{x_1^2 + x_2^2 + \cdots + x_n^2}\)&lt;/p&gt;

&lt;p&gt;Đây là khoảng cách hình học quen thuộc theo đường thẳng.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chuẩn Manhattan (chuẩn \(L_1\)):&lt;/strong&gt;
\(\|\mathbf{x}\|_1 = \sum_{i=1}^n |x_i| = |x_1| + |x_2| + \cdots + |x_n|\)&lt;/p&gt;

&lt;p&gt;Còn được gọi là khoảng cách taxi — quãng đường di chuyển theo các trục vuông góc trên mạng lưới đường phố dạng ô bàn cờ.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chuẩn cực đại (chuẩn \(L_\infty\)):&lt;/strong&gt;
\(\|\mathbf{x}\|_\infty = \max_{i} |x_i|\)&lt;/p&gt;

&lt;p&gt;Đây là giá trị tuyệt đối lớn nhất trong các thành phần của vector.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt; Với \(\mathbf{x} = \begin{pmatrix} 3 \\ -4 \\ 1 \end{pmatrix}\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[\|\mathbf{x}\|_2 = \sqrt{3^2 + (-4)^2 + 1^2} = \sqrt{26} \approx 5{,}1\]
  &lt;/li&gt;
  &lt;li&gt;
\[\|\mathbf{x}\|_1 = |3| + |-4| + |1| = 8\]
  &lt;/li&gt;
  &lt;li&gt;
\[\|\mathbf{x}\|_\infty = \max\{|3|, |-4|, |1|\} = 4\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;tích-vô-hướng&quot;&gt;Tích vô hướng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Tích vô hướng&lt;/strong&gt; (&lt;em&gt;dot product&lt;/em&gt; hay &lt;em&gt;inner product&lt;/em&gt;) là phép nhân phổ biến nhất giữa hai vector, trả về một số thực.&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa&quot;&gt;Định nghĩa&lt;/h3&gt;

&lt;p&gt;Với hai vector \(\mathbf{x}\) và \(\mathbf{y}\) trong \(\mathbb{R}^n\):&lt;/p&gt;

\[\mathbf{x}^T \mathbf{y} = \mathbf{x} \cdot \mathbf{y} = \sum_{i=1}^n x_i y_i = x_1 y_1 + x_2 y_2 + \cdots + x_n y_n\]

&lt;h3 id=&quot;diễn-giải-hình-học&quot;&gt;Diễn giải hình học&lt;/h3&gt;

\[\mathbf{x} \cdot \mathbf{y} = \|\mathbf{x}\| \|\mathbf{y}\| \cos \theta\]

&lt;p&gt;trong đó \(\theta\) là góc giữa hai vector.&lt;/p&gt;

&lt;h3 id=&quot;tính-chất&quot;&gt;Tính chất&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giao hoán:&lt;/strong&gt; \(\mathbf{x} \cdot \mathbf{y} = \mathbf{y} \cdot \mathbf{x}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân phối:&lt;/strong&gt; \(\mathbf{x} \cdot (\mathbf{y} + \mathbf{z}) = \mathbf{x} \cdot \mathbf{y} + \mathbf{x} \cdot \mathbf{z}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thuần nhất:&lt;/strong&gt; \((c\mathbf{x}) \cdot \mathbf{y} = c(\mathbf{x} \cdot \mathbf{y})\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;các-trường-hợp-đặc-biệt&quot;&gt;Các trường hợp đặc biệt&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hai vector trực giao (vuông góc):&lt;/strong&gt; \(\mathbf{x} \cdot \mathbf{y} = 0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hai vector cùng phương (song song):&lt;/strong&gt; \(\mathbf{x} \cdot \mathbf{y} = \pm \|\mathbf{x}\| \|\mathbf{y}\|\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tích vô hướng với chính nó:&lt;/strong&gt; \(\mathbf{x} \cdot \mathbf{x} = \|\mathbf{x}\|_2^2\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;ví-dụ&quot;&gt;Ví dụ&lt;/h3&gt;

&lt;p&gt;Với \(\mathbf{x} = \begin{pmatrix} 1 \\ 2 \end{pmatrix}\) và \(\mathbf{y} = \begin{pmatrix} 3 \\ 4 \end{pmatrix}\):&lt;/p&gt;

\[\mathbf{x}^T \mathbf{y} = (1)(3) + (2)(4) = 3 + 8 = 11\]

&lt;hr /&gt;

&lt;h2 id=&quot;ứng-dụng-trong-tối-ưu-hóa&quot;&gt;Ứng dụng trong tối ưu hóa&lt;/h2&gt;

&lt;p&gt;Vector và không gian vector là công cụ nền tảng trong tối ưu hóa ở nhiều khía cạnh:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Biến quyết định:&lt;/strong&gt; bài toán tối ưu nhiều biến biểu diễn tự nhiên dưới dạng một vector tham số.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient:&lt;/strong&gt; gradient của hàm mục tiêu là vector chỉ theo hướng tăng dốc nhất.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ràng buộc:&lt;/strong&gt; ràng buộc tuyến tính được viết gọn bằng tích vô hướng: \(\mathbf{a}^T \mathbf{x} \leq b\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khoảng cách và độ tương đồng:&lt;/strong&gt; các loại chuẩn khác nhau giúp đo khoảng cách giữa các nghiệm hoặc độ lớn của bước cập nhật.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính trực giao:&lt;/strong&gt; nhiều tính chất tối ưu dựa trên quan hệ vuông góc, chẳng hạn gradient vuông góc với đường mức.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tổ hợp tuyến tính:&lt;/strong&gt; miền khả thi thường được mô tả qua tổ hợp tuyến tính của các vector (bao lồi, nón lồi, v.v.).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Khung lý thuyết về không gian vector cung cấp ngôn ngữ toán học chặt chẽ để phát biểu và giải quyết các bài toán tối ưu hóa một cách có hệ thống.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Vectors&lt;/td&gt;
          &lt;td&gt;Chapter 1, Essence of linear algebra](https://www.youtube.com/watch?v=fNk_zzaMoSs) — 3Blue1Brown, tiếng Anh. Giới thiệu khái niệm vector trước khi bước vào không gian sinh (&lt;em&gt;span&lt;/em&gt;), cơ sở và số chiều.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Linear combinations, span, and basis vectors&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of linear algebra](https://www.youtube.com/watch?v=k7RM-ot2NWY) — 3Blue1Brown, tiếng Anh. Trực quan hóa tổ hợp tuyến tính, không gian sinh và cơ sở, tương ứng với phần độc lập tuyến tính và số chiều trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Dot products and duality&lt;/td&gt;
          &lt;td&gt;Chapter 9, Essence of linear algebra](https://www.youtube.com/watch?v=LyGKycYT2v0) — 3Blue1Brown, tiếng Anh. Giải thích tích vô hướng và mối liên hệ với chuẩn Euclid — độ dài được cảm sinh trực tiếp từ tích vô hướng.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01 Giải tích</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_01_Calculus/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_01_Calculus</id>
   <content type="html">&lt;p&gt;Mỗi khi một mô hình AI học nhận diện khuôn mặt hay dịch một đoạn văn, nó thực chất đang dò đường xuống đáy một thung lũng có hàng tỷ chiều trong bóng tối. Thứ duy nhất giúp nó biết bước tiếp theo nên nghiêng sang trái hay sang phải chính là &lt;strong&gt;giải tích vi phân&lt;/strong&gt;. Trước khi đi sâu vào bốn bài học chi tiết về liên tục, đạo hàm đa biến, gradient và chuỗi Taylor, bài tổng quan này giúp bạn ghép bức tranh lớn: giải tích không phải những công thức tính đạo hàm khô khan thời phổ thông, mà là công cụ xấp xỉ cục bộ mạnh nhất của khoa học tính toán.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-mảnh-ghép-giải-tích-phục-vụ-tối-ưu-hóa&quot;&gt;Kiến thức cần nhớ: Bốn mảnh ghép giải tích phục vụ tối ưu hóa&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tính liên tục và tính Lipschitz (Smoothness)&lt;/strong&gt;:
Đo lường độ “gồ ghề” của bề mặt hàm mất mát; một hàm có hằng số Lipschitz nhỏ sẽ không đột ngột nhảy vọt khi trọng số thay đổi chút ít, giúp huấn luyện ổn định.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đạo hàm riêng và Ma trận Jacobian&lt;/strong&gt;:
Mở rộng ý tưởng độ dốc một chiều sang không gian nhiều biến, cho biết khi ta nhích từng tham số \(w_i\) lên một lượng nhỏ thì đầu ra mạng thay đổi ra sao.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vector Gradient và Đạo hàm theo hướng&lt;/strong&gt;:
Xác định chính xác hướng tăng nhanh nhất (và ngược lại, hướng giảm nhanh nhất \(-\nabla f\)) của hàm mục tiêu—nền tảng trực tiếp của mọi thuật toán Gradient Descent.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Khai triển chuỗi Taylor (Bậc 1 và Bậc 2)&lt;/strong&gt;:
Biến những hàm phi tuyến phức tạp thành đa thức bậc nhất (tiếp tuyến) hoặc bậc hai (parabol/Hessian) trong lân cận nhỏ để dễ dàng tìm bước nhảy tối ưu.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-thấy-ngay-sức-mạnh-xấp-xỉ-tuyến-tính-cục-bộ-bằng-tay&quot;&gt;Giải thích: Thấy ngay sức mạnh xấp xỉ tuyến tính cục bộ bằng tay&lt;/h3&gt;

&lt;p&gt;Xét hàm mất mát phi tuyến đơn giản \(f(w) = w^3 - 2w + 4\) tại điểm hiện tại \(w_0 = 1\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Giá trị hiện tại&lt;/strong&gt;: \(f(1) = 1^3 - 2(1) + 4 = 3\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Độ dốc cục bộ (đạo hàm)&lt;/strong&gt;: \(f&apos;(w) = 3w^2 - 2 \implies f&apos;(1) = 3(1)^2 - 2 = 1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xấp xỉ tuyến tính (Taylor bậc 1)&lt;/strong&gt;: Khi dịch chuyển một bước nhỏ \(\Delta w = -0.1\) (ngược dấu đạo hàm để giảm \(f\)), giải tích dự đoán:
\(f(0.9) \approx f(1) + f&apos;(1)\Delta w = 3 + 1 \times (-0.1) = 2.90.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm chứng giá trị thật&lt;/strong&gt;: Tính trực tiếp \(f(0.9) = (0.9)^3 - 2(0.9) + 4 = 0.729 - 1.8 + 4 = 2.929\). Sai số xấp xỉ chỉ là \(0.029\) (bậc \((\Delta w)^2\)).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Chính vì xấp xỉ tuyến tính cực kỳ chuẩn xác ở bước nhỏ như vậy, mạng nơ-ron mới có thể yên tâm cập nhật từng bước nhỏ ngược chiều gradient mà không cần biết toàn bộ hình thù hàm mất mát từ xa.&lt;/p&gt;

&lt;p&gt;Phần này trình bày các khái niệm giải tích thiết yếu cho tối ưu hóa, được chia thành bốn bài học chính nhằm giúp bạn nắm vững từng nội dung một cách có hệ thống.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=WUvTyaaNkzM&quot;&gt;The essence of calculus&lt;/a&gt; — 3Blue1Brown, tiếng Anh. Video giới thiệu trực quan ý tưởng cốt lõi xem đạo hàm như xấp xỉ tuyến tính cục bộ, làm nền tảng cho bốn bài giải tích tiếp theo.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[The paradox of the derivative&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of calculus](https://www.youtube.com/watch?v=9vKqVkMQHKk) — 3Blue1Brown, tiếng Anh. Khái niệm đạo hàm được xây dựng chặt chẽ hơn, đồng thời giải thích vì sao định nghĩa qua giới hạn dễ gây nhầm lẫn.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YNYwUWH-04w&quot;&gt;MaDL - Differential Calculus&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Lược giảng ngắn về phép tính vi phân theo hướng phục vụ học sâu, sát với cách khóa học sử dụng giải tích hơn so với giáo trình giải tích truyền thống.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01-04 Chuỗi Taylor</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_01_04_Taylor_Series/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_01_04_Taylor_Series</id>
   <content type="html">&lt;p&gt;Bạn đã bao giờ tự hỏi làm sao máy tính tính được \(e^{-0.3}\), \(\sin(0.5)\) hay hàm kích hoạt Sigmoid chỉ bằng phép cộng và phép nhân, hoặc vì sao các thuật toán tối ưu như Newton’s Method lại hội tụ nhanh hơn Gradient Descent cả chục lần? Bí mật đứng sau cả hai câu chuyện đó đều là &lt;strong&gt;chuỗi Taylor&lt;/strong&gt;—nghệ thuật thay thế một hàm cong phức tạp bằng một đa thức dễ tính toán trong lân cận một điểm. Hiểu sâu chuỗi Taylor giúp bạn đọc vị được bản chất của bước học (learning rate), độ cong bề mặt mất mát và giới hạn của các phép xấp xỉ bậc nhất trong Deep Learning.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-vai-trò-chiến-lược-của-chuỗi-taylor-trong-học-sâu&quot;&gt;Kiến thức cần nhớ: Bốn vai trò chiến lược của Chuỗi Taylor trong Học sâu&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Xấp xỉ tuyến tính bậc 1 (Linear Approximation)&lt;/strong&gt;:
\(f(\mathbf{x} + \Delta\mathbf{x}) \approx f(\mathbf{x}) + \nabla f(\mathbf{x})^\top \Delta\mathbf{x}\) là cơ sở toán học chứng minh chọn \(\Delta\mathbf{x} = -\eta \nabla f(\mathbf{x})\) với \(\eta\) đủ nhỏ sẽ chắc chắn làm giảm hàm mất mát.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Xấp xỉ bậc 2 và Ma trận Hessian (Quadratic Approximation)&lt;/strong&gt;:
Thêm số hạng \(\frac{1}{2}\Delta\mathbf{x}^\top \mathbf{H} \Delta\mathbf{x}\) nắm bắt độ cong của thung lũng, mở đường cho phương pháp Newton, L-BFGS và phân tích điểm yên ngựa (&lt;em&gt;saddle points&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phần dư và Sai số cắt cụt (Truncation Error)&lt;/strong&gt;:
Cho biết xấp xỉ đáng tin trong bán kính nào: nếu bước nhảy \(\|\Delta\mathbf{x}\|\) quá lớn, số hạng bậc hai và bậc ba sẽ áp đảo số hạng bậc nhất khiến Gradient Descent nhảy vọt qua đáy và phân kỳ.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Khởi nguồn của các công thức xấp xỉ kỹ thuật&lt;/strong&gt;:
Từ khai triển \(\ln(1 + x) \approx x\), \(e^x \approx 1 + x + \frac{x^2}{2}\) đến phân tích độ ổn định số học của hàm Softmax và GELU, chuỗi Taylor xuất hiện dày đặc trong các bài báo nghiên cứu Deep Learning.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-xấp-xỉ-tay-hàm-fx--ex-tại-x--02-qua-từng-bậc&quot;&gt;Giải thích: Xấp xỉ tay hàm \(f(x) = e^x\) tại \(x = 0.2\) qua từng bậc&lt;/h3&gt;

&lt;p&gt;Xét hàm mũ \(f(x) = e^x\) (cốt lõi của Softmax và Sigmoid) khai triển quanh \(a = 0\) (chuỗi Maclaurin), với giá trị chính xác \(e^{0.2} \approx 1.221403\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Bậc khai triển&lt;/th&gt;
      &lt;th style=&quot;text-align: left&quot;&gt;Công thức đa thức \(P_n(x)\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Thay \(x = 0.2\)&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;Sai số tuyệt đối \(\lvert e^{0.2} - P_n(0.2) \rvert\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Bậc 0 (Hằng số)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1.000000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.221403\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Bậc 1 (Tuyến tính)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1 + x\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1.200000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.021403\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Bậc 2 (Parabol)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1 + x + \frac{x^2}{2}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1 + 0.2 + 0.02 = 1.220000\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.001403\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;&lt;strong&gt;Bậc 3 (Bậc ba)&lt;/strong&gt;&lt;/td&gt;
      &lt;td style=&quot;text-align: left&quot;&gt;\(1 + x + \frac{x^2}{2} + \frac{x^3}{6}\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(1.22 + \frac{0.008}{6} \approx 1.221333\)&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;\(0.000070\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Hãy thử tăng bước lên \(x = 2.0\) (giá trị thật \(e^2 \approx 7.389\)): khi đó xấp xỉ bậc 1 chỉ cho \(1 + 2 = 3.0\) (lệch hơn 59%!). Con số này minh họa trực quan bài học quan trọng trong tối ưu hóa: &lt;strong&gt;xấp xỉ bậc 1 chỉ đáng tin khi bước nhảy đủ nhỏ&lt;/strong&gt;. Nếu đặt learning rate quá lớn, bản đồ tuyến tính mà Gradient Descent dựa vào sẽ hoàn toàn sai lệch.&lt;/p&gt;

&lt;p&gt;Bài học này trình bày khai triển chuỗi Taylor — công cụ nền tảng để xấp xỉ hàm số bằng đa thức và phân tích hành vi cục bộ của hàm trong các thuật toán tối ưu hóa.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;định-nghĩa-chuỗi-taylor&quot;&gt;Định nghĩa chuỗi Taylor&lt;/h2&gt;

&lt;p&gt;Chuỗi Taylor biểu diễn một hàm số dưới dạng tổng vô hạn các số hạng được tính từ các đạo hàm của hàm tại một điểm duy nhất. Nhờ đó, ta có thể xấp xỉ các hàm phức tạp bằng những đa thức đơn giản hơn.&lt;/p&gt;

&lt;h3 id=&quot;chuỗi-taylor-một-biến&quot;&gt;Chuỗi Taylor một biến&lt;/h3&gt;

&lt;p&gt;Khai triển chuỗi Taylor của hàm số \(f(x)\) quanh điểm \(a\) có dạng:&lt;/p&gt;

\[f(x) = \sum_{n=0}^{\infty} \frac{f^{(n)}(a)}{n!}(x-a)^n\]

&lt;p&gt;Viết tường minh từng số hạng:&lt;/p&gt;

\[f(x) = f(a) + \frac{f&apos;(a)}{1!}(x-a) + \frac{f&apos;&apos;(a)}{2!}(x-a)^2 + \frac{f&apos;&apos;&apos;(a)}{3!}(x-a)^3 + \dots\]

&lt;h3 id=&quot;chuỗi-maclaurin&quot;&gt;Chuỗi Maclaurin&lt;/h3&gt;

&lt;p&gt;Khi chọn điểm khai triển \(a = 0\), chuỗi Taylor được gọi là &lt;strong&gt;chuỗi Maclaurin&lt;/strong&gt;:&lt;/p&gt;

\[f(x) = f(0) + f&apos;(0)x + \frac{f&apos;&apos;(0)}{2!}x^2 + \frac{f&apos;&apos;&apos;(0)}{3!}x^3 + \dots\]

&lt;h3 id=&quot;một-số-chuỗi-maclaurin-thông-dụng&quot;&gt;Một số chuỗi Maclaurin thông dụng&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Hàm mũ:&lt;/strong&gt;
\(e^x = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \dots = \sum_{n=0}^{\infty} \frac{x^n}{n!}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hàm sin:&lt;/strong&gt;
\(\sin x = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \dots = \sum_{n=0}^{\infty} \frac{(-1)^n x^{2n+1}}{(2n+1)!}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hàm cosin:&lt;/strong&gt;
\(\cos x = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \dots = \sum_{n=0}^{\infty} \frac{(-1)^n x^{2n}}{(2n)!}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Logarit tự nhiên (với \(|x| &amp;lt; 1\)):&lt;/strong&gt;
\(\ln(1 + x) = x - \frac{x^2}{2} + \frac{x^3}{3} - \frac{x^4}{4} + \dots = \sum_{n=1}^{\infty} \frac{(-1)^{n+1} x^n}{n}\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;chuỗi-taylor-đa-biến&quot;&gt;Chuỗi Taylor đa biến&lt;/h2&gt;

&lt;p&gt;Với hàm nhiều biến, biểu thức chuỗi Taylor phức tạp hơn nhưng vẫn dựa trên cùng nguyên lý: khai triển quanh điểm \(\mathbf{x}_0\) thông qua các đạo hàm riêng.&lt;/p&gt;

&lt;h3 id=&quot;khai-triển-taylor-bậc-nhất&quot;&gt;Khai triển Taylor bậc nhất&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Xấp xỉ tuyến tính&lt;/strong&gt; của \(f(\mathbf{x})\) quanh \(\mathbf{x}_0\):&lt;/p&gt;

\[f(\mathbf{x}) \approx f(\mathbf{x}_0) + \nabla f(\mathbf{x}_0)^T (\mathbf{x} - \mathbf{x}_0)\]

&lt;p&gt;Đây chính là phương trình siêu phẳng tiếp tuyến với đồ thị hàm số tại \(\mathbf{x}_0\).&lt;/p&gt;

&lt;h3 id=&quot;khai-triển-taylor-bậc-hai&quot;&gt;Khai triển Taylor bậc hai&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Xấp xỉ bậc hai&lt;/strong&gt; bổ sung thêm thông tin về độ cong:&lt;/p&gt;

\[f(\mathbf{x}) \approx f(\mathbf{x}_0) + \nabla f(\mathbf{x}_0)^T (\mathbf{x} - \mathbf{x}_0) + \frac{1}{2} (\mathbf{x} - \mathbf{x}_0)^T \nabla^2 f(\mathbf{x}_0) (\mathbf{x} - \mathbf{x}_0)\]

&lt;p&gt;trong đó \(\nabla^2 f(\mathbf{x}_0)\) là ma trận Hessian tại \(\mathbf{x}_0\).&lt;/p&gt;

&lt;h3 id=&quot;dạng-tổng-quát&quot;&gt;Dạng tổng quát&lt;/h3&gt;

&lt;p&gt;Chuỗi Taylor đa biến đầy đủ sử dụng các đạo hàm bậc cao:&lt;/p&gt;

\[f(\mathbf{x}) = \sum_{|\alpha|=0}^{\infty} \frac{D^{\alpha} f(\mathbf{x}_0)}{\alpha!} (\mathbf{x} - \mathbf{x}_0)^{\alpha}\]

&lt;p&gt;trong đó \(\alpha = (\alpha_1, \alpha_2, \ldots, \alpha_n)\) là đa chỉ số (&lt;em&gt;multi-index&lt;/em&gt;).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ứng-dụng-trong-tối-ưu-hóa&quot;&gt;Ứng dụng trong tối ưu hóa&lt;/h2&gt;

&lt;p&gt;Chuỗi Taylor là công cụ nền tảng trong lý thuyết và thuật toán tối ưu hóa ở ba khía cạnh chính:&lt;/p&gt;

&lt;h3 id=&quot;1-xấp-xỉ-hàm-cục-bộ&quot;&gt;1. Xấp xỉ hàm cục bộ&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Xấp xỉ tuyến tính (phương pháp bậc nhất):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Dùng trong các thuật toán gradient descent.&lt;/li&gt;
  &lt;li&gt;Xem hàm số xấp xỉ tuyến tính trong một lân cận nhỏ quanh điểm hiện tại.&lt;/li&gt;
  &lt;li&gt;Độ dài bước phải đủ nhỏ để xấp xỉ còn chính xác.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Xấp xỉ bậc hai (phương pháp bậc hai):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Dùng trong phương pháp Newton và các phương pháp tựa Newton (&lt;em&gt;quasi-Newton&lt;/em&gt;).&lt;/li&gt;
  &lt;li&gt;Khai thác thông tin độ cong thông qua ma trận Hessian.&lt;/li&gt;
  &lt;li&gt;Thường hội tụ nhanh hơn so với phương pháp bậc nhất.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-điều-kiện-tối-ưu&quot;&gt;2. Điều kiện tối ưu&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Điều kiện cần bậc nhất:&lt;/strong&gt;
Tại một điểm cực tiểu địa phương \(\mathbf{x}^*\), ta phải có \(\nabla f(\mathbf{x}^*) = \mathbf{0}\).&lt;/p&gt;

&lt;p&gt;Điều này suy ra trực tiếp từ khai triển Taylor bậc nhất: nếu \(\nabla f(\mathbf{x}^*) \neq \mathbf{0}\), ta luôn có thể di chuyển một bước đủ nhỏ theo hướng \(-\nabla f(\mathbf{x}^*)\) để làm giảm giá trị hàm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Điều kiện đủ bậc hai:&lt;/strong&gt;
Nếu \(\nabla f(\mathbf{x}^*) = \mathbf{0}\) và \(\nabla^2 f(\mathbf{x}^*)\) là ma trận xác định dương, thì \(\mathbf{x}^*\) là cực tiểu địa phương.&lt;/p&gt;

&lt;p&gt;Kết luận này đến từ khai triển Taylor bậc hai, vì số hạng bậc hai quyết định dấu biến thiên của hàm trong lân cận \(\mathbf{x}^*\).&lt;/p&gt;

&lt;h3 id=&quot;3-thiết-kế-thuật-toán&quot;&gt;3. Thiết kế thuật toán&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Phương pháp Newton:&lt;/strong&gt;
Cực tiểu hóa trực tiếp mô hình xấp xỉ Taylor bậc hai ở mỗi bước lặp:&lt;/p&gt;

\[\mathbf{x}_{k+1} = \mathbf{x}_k - [\nabla^2 f(\mathbf{x}_k)]^{-1} \nabla f(\mathbf{x}_k)\]

&lt;p&gt;&lt;strong&gt;Phương pháp vùng tin cậy (&lt;em&gt;Trust Region&lt;/em&gt;):&lt;/strong&gt;
Dùng xấp xỉ Taylor trong một vùng lân cận mà mô hình xấp xỉ được xem là đủ chính xác.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Phương pháp tìm kiếm theo đường thẳng (&lt;em&gt;Line Search&lt;/em&gt;):&lt;/strong&gt;
Dựa vào khai triển Taylor để chọn độ dài bước phù hợp dọc theo hướng tìm kiếm.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;ví-dụ-phân-tích-hàm-bậc-hai&quot;&gt;Ví dụ: Phân tích hàm bậc hai&lt;/h2&gt;

&lt;p&gt;Xét hàm số \(f(x, y) = x^2 + 2xy + 3y^2\) tại điểm \((0, 0)\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gradient:&lt;/strong&gt;
\(\nabla f = \begin{pmatrix} 2x + 2y \\ 2x + 6y \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;Tại \((0, 0)\): \(\nabla f(0, 0) = \begin{pmatrix} 0 \\ 0 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hessian:&lt;/strong&gt;
\(\nabla^2 f = \begin{pmatrix} 2 &amp;amp; 2 \\ 2 &amp;amp; 6 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Khai triển Taylor bậc hai tại \((0, 0)\):&lt;/strong&gt;
\(f(x, y) \approx f(0, 0) + 0 + \frac{1}{2} \begin{pmatrix} x &amp;amp; y \end{pmatrix} \begin{pmatrix} 2 &amp;amp; 2 \\ 2 &amp;amp; 6 \end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix}\)&lt;/p&gt;

\[= 0 + \frac{1}{2}(2x^2 + 4xy + 6y^2) = x^2 + 2xy + 3y^2\]

&lt;p&gt;Vì \(f\) vốn là một hàm bậc hai nên khai triển Taylor bậc hai trùng khớp hoàn toàn với hàm gốc.&lt;/p&gt;

&lt;p&gt;Ma trận Hessian có các giá trị riêng \(\lambda_1 = 4 + 2\sqrt{2} &amp;gt; 0\) và \(\lambda_2 = 4 - 2\sqrt{2} &amp;gt; 0\), tức là ma trận xác định dương. Do đó, điểm \((0, 0)\) là cực tiểu địa phương (đồng thời là cực tiểu toàn cục) của hàm số.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;lưu-ý-thực-tế&quot;&gt;Lưu ý thực tế&lt;/h2&gt;

&lt;h3 id=&quot;hội-tụ-và-độ-chính-xác&quot;&gt;Hội tụ và độ chính xác&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bán kính hội tụ:&lt;/strong&gt; chuỗi Taylor chỉ hội tụ trong một bán kính nhất định quanh điểm khai triển.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sai số cắt cụt:&lt;/strong&gt; việc chỉ giữ lại hữu hạn số hạng tạo ra sai số xấp xỉ.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chi phí tính toán:&lt;/strong&gt; giữ lại các số hạng bậc càng cao thì chi phí tính đạo hàm càng lớn.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;lựa-chọn-thuật-toán-tối-ưu-hóa&quot;&gt;Lựa chọn thuật toán tối ưu hóa&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Phương pháp bậc nhất&lt;/strong&gt; (gradient descent): chỉ dùng gradient, tốc độ hội tụ chậm hơn nhưng chi phí mỗi bước lặp thấp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương pháp bậc hai&lt;/strong&gt; (Newton): dùng thêm ma trận Hessian, hội tụ nhanh hơn nhưng chi phí mỗi bước lặp cao.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phương pháp tựa Newton (&lt;em&gt;quasi-Newton&lt;/em&gt;):&lt;/strong&gt; xấp xỉ ma trận Hessian nhằm cân bằng giữa tốc độ hội tụ và chi phí tính toán.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Khai triển chuỗi Taylor cho phép xấp xỉ các hàm phức tạp bằng đa thức đơn giản quanh một điểm, tạo cơ sở trực tiếp để phân tích hành vi cục bộ và thiết kế các thuật toán tối ưu hóa.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Taylor series&lt;/td&gt;
          &lt;td&gt;Chapter 11, Essence of calculus](https://www.youtube.com/watch?v=3d6DsjIBzJ4) — 3Blue1Brown, tiếng Anh. Trình bày đa thức Taylor như phép xấp xỉ cục bộ, bao gồm số hạng bậc hai thường dùng trong học sâu.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YNYwUWH-04w&quot;&gt;MaDL - Differential Calculus&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Số hạng bậc nhất trong khai triển Taylor chính là vi phân được tính trong bài giảng ngắn này.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=wH-mvAPIlT8&quot;&gt;MaDL - The Argmin and Argmax Operators&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Giải thích cách cực tiểu hóa (argmin) mô hình bậc hai cục bộ biến khai triển Taylor thành một bước cập nhật tối ưu hóa.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01-03 Gradient và Đạo hàm theo hướng</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_01_03_Gradient_and_Directional_Derivatives/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_01_03_Gradient_and_Directional_Derivatives</id>
   <content type="html">&lt;p&gt;Giữa màn sương dày đặc trên sườn núi, bạn không thấy đỉnh núi cũng chẳng thấy thung lũng, nhưng đôi chân bạn cảm nhận được mặt đất đang dốc về hướng nào. Nếu muốn xuống núi nhanh nhất có thể trong bước tiếp theo, bạn nên bước theo hướng nào? Câu hỏi hình học đơn giản ấy dẫn thẳng tới &lt;strong&gt;vector gradient&lt;/strong&gt; và &lt;strong&gt;đạo hàm theo hướng&lt;/strong&gt;—hai khái niệm định nghĩa nên chiếc la bàn vạn năng của toàn bộ ngành Học sâu hiện đại.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-góc-nhìn-cốt-lõi-về-gradient-và-đạo-hàm-theo-hướng&quot;&gt;Kiến thức cần nhớ: Bốn góc nhìn cốt lõi về Gradient và Đạo hàm theo hướng&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vector Gradient (\(\nabla f\))&lt;/strong&gt;:
Gom mọi đạo hàm riêng thành một vector duy nhất sống trong không gian tham số, đóng vai trò mũi tên chỉ chính xác hướng tăng dốc nhất của hàm số.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đạo hàm theo hướng (Directional Derivative)&lt;/strong&gt;:
Đo tốc độ biến thiên của \(f\) khi đi theo một vector đơn vị \(\mathbf{u}\) bất kỳ bằng tích vô hướng \(D_{\mathbf{u}} f(\mathbf{x}) = \nabla f(\mathbf{x}) \cdot \mathbf{u} = \|\nabla f(\mathbf{x})\|\cos\theta\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Tính vuông góc với đường mức (Orthogonality to Contours)&lt;/strong&gt;:
Tại mọi điểm, vector gradient luôn vuông góc với đường mức đi qua điểm đó—lý giải vì sao trên thung lũng hình elip dẹt, Gradient Descent lại chạy zig-zag qua lại hai vách núi thay vì đi thẳng tới đáy.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hướng giảm nhanh nhất (Steepest Descent)&lt;/strong&gt;:
Vì \(\cos\theta\) đạt cực tiểu bằng \(-1\) khi \(\theta = 180^\circ\), bước đi theo hướng \(\mathbf{u} = -\frac{\nabla f}{\|\nabla f\|}\) đảm bảo hàm mất mát giảm nhanh nhất trong lân cận vô cùng bé.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-tốc-độ-giảm-khi-bước-theo-nhiều-hướng-khác-nhau&quot;&gt;Giải thích: So sánh tốc độ giảm khi bước theo nhiều hướng khác nhau&lt;/h3&gt;

&lt;p&gt;Xét hàm mất mát hai biến \(f(x, y) = x^2 + 4y^2\) (một thung lũng elip) tại điểm hiện tại \(\mathbf{p} = (2, 1)\), nơi \(f(2, 1) = 4 + 4 = 8\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính vector gradient tại \(\mathbf{p} = (2, 1)\)&lt;/strong&gt;:
\(\nabla f(x, y) = (2x, 8y) \implies \nabla f(2, 1) = (4, 8).\)
Độ lớn gradient là \(\|\nabla f(2, 1)\| = \sqrt{4^2 + 8^2} = \sqrt{80} \approx 8.944\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Thử đi theo 3 hướng đơn vị khác nhau&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Hướng sang trái&lt;/strong&gt; \(\mathbf{u}_1 = (-1, 0)\): \(D_{\mathbf{u}_1} f = (4, 8) \cdot (-1, 0) = -4\) (hàm giảm với tốc độ 4).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Hướng đi thẳng về gốc tọa độ&lt;/strong&gt; \(\mathbf{u}_2 = \frac{(-2, -1)}{\sqrt{5}} \approx (-0.894, -0.447)\): \(D_{\mathbf{u}_2} f = \frac{4(-2) + 8(-1)}{\sqrt{5}} = \frac{-16}{\sqrt{5}} \approx -7.155\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Hướng ngược gradient&lt;/strong&gt; \(\mathbf{u}_3 = \frac{(-4, -8)}{\sqrt{80}} \approx (-0.447, -0.894)\): \(D_{\mathbf{u}_3} f = -\sqrt{80} \approx -8.944\) (giảm nhanh nhất!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Điểm tinh tế đáng suy ngẫm&lt;/strong&gt;: Hướng ngược gradient \(\mathbf{u}_3\) giảm nhanh nhất &lt;em&gt;tại chỗ&lt;/em&gt;, nhưng lại &lt;strong&gt;không&lt;/strong&gt; chỉ thẳng về đáy \((0, 0)\) (là hướng \(\mathbf{u}_2\)) do trục \(y\) dốc gấp 4 lần trục \(x\). Đây chính là nguồn gốc của hiện tượng zig-zag và lý do ra đời của Momentum và Adam sau này!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bài học này trình bày vector gradient (&lt;em&gt;gradient&lt;/em&gt;) và đạo hàm theo hướng (&lt;em&gt;directional derivative&lt;/em&gt;) — hai khái niệm trung tâm trong tối ưu hóa, giúp ta xác định tốc độ biến thiên của hàm số theo từng hướng khác nhau.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;vector-gradient&quot;&gt;Vector gradient&lt;/h2&gt;

&lt;p&gt;Gradient \(\nabla f\) là vector gồm tất cả các đạo hàm riêng của hàm \(f\) theo từng biến. Tại một điểm cho trước, gradient chỉ theo hướng tăng dốc nhất của hàm số.&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa-và-cách-tính&quot;&gt;Định nghĩa và cách tính&lt;/h3&gt;

&lt;p&gt;Với hàm hai biến \(f(x, y)\), gradient được xác định bởi:&lt;/p&gt;

\[\nabla f = \begin{pmatrix} \frac{\partial f}{\partial x} \\ \frac{\partial f}{\partial y} \end{pmatrix}\]

&lt;p&gt;Với hàm \(n\) biến \(f(x_1, x_2, \ldots, x_n)\):&lt;/p&gt;

\[\nabla f = \begin{pmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_n} \end{pmatrix}\]

&lt;h3 id=&quot;ví-dụ-tính-gradient&quot;&gt;Ví dụ: Tính gradient&lt;/h3&gt;

&lt;p&gt;Xét hàm số \(f(x, y) = x^2 + 3xy + y^2\):&lt;/p&gt;

&lt;p&gt;\(\frac{\partial f}{\partial x} = 2x + 3y\)
\(\frac{\partial f}{\partial y} = 3x + 2y\)&lt;/p&gt;

&lt;p&gt;Do đó: \(\nabla f = \begin{pmatrix} 2x + 3y \\ 3x + 2y \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;Tại điểm \((1, 2)\): \(\nabla f(1, 2) = \begin{pmatrix} 2(1) + 3(2) \\ 3(1) + 2(2) \end{pmatrix} = \begin{pmatrix} 8 \\ 7 \end{pmatrix}\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;đạo-hàm-theo-hướng&quot;&gt;Đạo hàm theo hướng&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Đạo hàm theo hướng&lt;/strong&gt; đo tốc độ biến thiên của \(f\) khi di chuyển theo một hướng bất kỳ \(\mathbf{u}\), trong đó \(\mathbf{u}\) là vector đơn vị (có độ dài bằng 1).&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa&quot;&gt;Định nghĩa&lt;/h3&gt;

&lt;p&gt;Với hàm \(f(\mathbf{x})\) và vector đơn vị \(\mathbf{u} = \langle u_1, u_2, \ldots, u_n \rangle\):&lt;/p&gt;

\[D_{\mathbf{u}}f(\mathbf{x}) = \nabla f(\mathbf{x}) \cdot \mathbf{u} = \sum_{i=1}^{n} \frac{\partial f}{\partial x_i} u_i\]

&lt;h3 id=&quot;diễn-giải-hình-học&quot;&gt;Diễn giải hình học&lt;/h3&gt;

&lt;p&gt;Đạo hàm theo hướng có thể biểu diễn dưới dạng:&lt;/p&gt;

\[D_{\mathbf{u}}f = \lvert \nabla f \rvert \cos \theta\]

&lt;p&gt;trong đó \(\theta\) là góc giữa \(\nabla f\) và \(\mathbf{u}\), còn \(\lvert \nabla f \rvert\) là độ lớn của gradient.&lt;/p&gt;

&lt;h3 id=&quot;ví-dụ-tính-đạo-hàm-theo-hướng&quot;&gt;Ví dụ: Tính đạo hàm theo hướng&lt;/h3&gt;

&lt;p&gt;Tiếp tục xét \(f(x, y) = x^2 + 3xy + y^2\) tại điểm \((1, 2)\) với \(\nabla f(1, 2) = \begin{pmatrix} 8 \\ 7 \end{pmatrix}\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hướng 1:&lt;/strong&gt; \(\mathbf{u}_1 = \begin{pmatrix} 1 \\ 0 \end{pmatrix}\) (chiều dương trục \(x\))
\(D_{\mathbf{u}_1}f(1, 2) = 8 \cdot 1 + 7 \cdot 0 = 8\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hướng 2:&lt;/strong&gt; \(\mathbf{u}_2 = \begin{pmatrix} 0 \\ 1 \end{pmatrix}\) (chiều dương trục \(y\))
\(D_{\mathbf{u}_2}f(1, 2) = 8 \cdot 0 + 7 \cdot 1 = 7\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hướng 3:&lt;/strong&gt; \(\mathbf{u}_3 = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 \\ 1 \end{pmatrix}\) (hướng đường chéo \(45^\circ\))
\(D_{\mathbf{u}_3}f(1, 2) = 8 \cdot \frac{1}{\sqrt{2}} + 7 \cdot \frac{1}{\sqrt{2}} = \frac{15}{\sqrt{2}} \approx 10{,}61\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;tốc-độ-biến-thiên-cực-đại-và-cực-tiểu&quot;&gt;Tốc độ biến thiên cực đại và cực tiểu&lt;/h2&gt;

&lt;h3 id=&quot;các-tính-chất-chính&quot;&gt;Các tính chất chính&lt;/h3&gt;

&lt;p&gt;Từ công thức \(D_{\mathbf{u}}f = \lvert \nabla f \rvert \cos \theta\), ta suy ra:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tốc độ biến thiên cực đại:&lt;/strong&gt; đạt được khi \(\cos \theta = 1\) (tức \(\theta = 0^\circ\)).
    &lt;ul&gt;
      &lt;li&gt;Hướng: \(\mathbf{u} = \frac{\nabla f}{\lvert \nabla f \rvert}\) (cùng hướng với gradient).&lt;/li&gt;
      &lt;li&gt;Giá trị cực đại: \(D_{\max}f = \lvert \nabla f \rvert\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tốc độ biến thiên cực tiểu:&lt;/strong&gt; đạt được khi \(\cos \theta = -1\) (tức \(\theta = 180^\circ\)).
    &lt;ul&gt;
      &lt;li&gt;Hướng: \(\mathbf{u} = -\frac{\nabla f}{\lvert \nabla f \rvert}\) (ngược hướng gradient).&lt;/li&gt;
      &lt;li&gt;Giá trị cực tiểu: \(D_{\min}f = -\lvert \nabla f \rvert\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tốc độ biến thiên bằng không:&lt;/strong&gt; xảy ra khi \(\cos \theta = 0\) (tức \(\theta = 90^\circ\)).
    &lt;ul&gt;
      &lt;li&gt;Hướng: mọi vector vuông góc với \(\nabla f\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;tóm-tắt-các-tính-chất-của-gradient&quot;&gt;Tóm tắt các tính chất của gradient&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Gradient \(\nabla f\) chỉ theo hướng &lt;strong&gt;tăng dốc nhất&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Hướng \(-\nabla f\) chỉ theo hướng &lt;strong&gt;giảm dốc nhất&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Độ lớn \(\lvert \nabla f \rvert\) là &lt;strong&gt;tốc độ biến thiên cực đại&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Điểm thỏa mãn \(\nabla f = \mathbf{0}\) được gọi là &lt;strong&gt;điểm tới hạn&lt;/strong&gt; (&lt;em&gt;critical point&lt;/em&gt;) — vị trí tiềm năng của cực trị.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;quan-hệ-với-đường-mức&quot;&gt;Quan hệ với đường mức&lt;/h2&gt;

&lt;p&gt;Tại mọi điểm trên đường mức \(f(x, y) = c\), vector gradient \(\nabla f\) luôn &lt;strong&gt;trực giao (vuông góc)&lt;/strong&gt; với tiếp tuyến của đường mức tại điểm đó.&lt;/p&gt;

&lt;h3 id=&quot;ý-nghĩa-của-tính-trực-giao&quot;&gt;Ý nghĩa của tính trực giao&lt;/h3&gt;

&lt;p&gt;Tính chất này đặc biệt quan trọng vì:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Đường mức biểu diễn giá trị hàm không đổi:&lt;/strong&gt; di chuyển dọc theo đường mức không làm thay đổi giá trị hàm, nên đạo hàm theo hướng tiếp tuyến bằng không.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient chỉ hướng tăng dốc nhất:&lt;/strong&gt; hướng làm giá trị hàm tăng nhanh nhất phải vuông góc với hướng mà hàm không đổi.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ứng dụng trong tối ưu hóa:&lt;/strong&gt; để tìm cực trị, ta tìm các điểm có gradient bằng không (điểm tới hạn), hoặc các điểm mà gradient vuông góc với biên của miền ràng buộc.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ứng-dụng-trong-tối-ưu-hóa&quot;&gt;Ứng dụng trong tối ưu hóa&lt;/h3&gt;

&lt;p&gt;Hiểu rõ gradient và đạo hàm theo hướng giúp ta làm việc hiệu quả với:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gradient descent:&lt;/strong&gt; di chuyển theo hướng \(-\nabla f\) để cực tiểu hóa \(f\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient ascent:&lt;/strong&gt; di chuyển theo hướng \(+\nabla f\) để cực đại hóa \(f\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tối ưu có ràng buộc:&lt;/strong&gt; khai thác quan hệ hình học giữa gradient và đường mức.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân tích hội tụ:&lt;/strong&gt; xác định điều kiện để thuật toán hội tụ về nghiệm tối ưu.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chọn độ dài bước:&lt;/strong&gt; quyết định khoảng di chuyển phù hợp dọc theo hướng gradient.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Vì cung cấp đồng thời cả hướng di chuyển lẫn tốc độ biến thiên của hàm số, gradient là nền tảng của hầu hết các thuật toán tối ưu hóa.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Directional Derivatives&lt;/td&gt;
          &lt;td&gt;What’s the slope in any direction?](https://www.youtube.com/watch?v=GJODOGq7cAY) — Dr. Trefor Bazett, tiếng Anh. Trực quan hóa đạo hàm theo hướng như độ dốc theo một hướng bất kỳ và vai trò của gradient là hướng tăng nhanh nhất.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=rh885pI4lPA&quot;&gt;MaDL - Vector Calculus&lt;/a&gt; — Tübingen Machine Learning, tiếng Anh. Trình bày gradient, đạo hàm theo hướng và ma trận Jacobian theo hệ thống ký hiệu dùng cho ánh xạ nhận giá trị vector trong khóa học.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Continuity vs Partial Derivatives vs Differentiability&lt;/td&gt;
          &lt;td&gt;My Favorite Multivariable Function](https://www.youtube.com/watch?v=6Wi1kT9kR1M) — Dr. Trefor Bazett, tiếng Anh. Minh họa vì sao sự tồn tại của đạo hàm riêng là điều kiện yếu hơn khả vi toàn phần — điểm phân biệt quan trọng cho phần đường mức.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01-02 Đạo hàm và Giải tích đa biến</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_01_02_Derivatives_and_Multivariable_Calculus/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_01_02_Derivatives_and_Multivariable_Calculus</id>
   <content type="html">&lt;p&gt;Khi huấn luyện một mạng nơ-ron nhỏ nhất cũng có hàng nghìn trọng số cùng lúc tác động lên hàm mất mát, ta không còn đứng trên một đường cong 2D nữa mà đang đứng giữa một địa hình núi non nghìn chiều. Làm thế nào để biết việc tăng trọng số \(w_{17}\) thêm \(0.001\) sẽ làm giảm sai số hay đẩy nó tăng vọt, trong khi mọi trọng số khác vẫn đang đồng thời thay đổi? Câu trả lời nằm ở &lt;strong&gt;đạo hàm riêng&lt;/strong&gt;, &lt;strong&gt;quy tắc dây chuyền đa biến&lt;/strong&gt; và &lt;strong&gt;ma trận Jacobian&lt;/strong&gt;—những viên gạch trực tiếp kiến tạo nên thuật toán lan truyền ngược.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-khái-niệm-trụ-cột-của-giải-tích-đa-biến&quot;&gt;Kiến thức cần nhớ: Bốn khái niệm trụ cột của Giải tích Đa biến&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đạo hàm riêng (Partial Derivatives)&lt;/strong&gt;:
Đóng băng tất cả các biến khác và chỉ đo độ nhạy của hàm theo duy nhất một tọa độ \(x_i\), tương ứng với độ dốc khi cắt mặt cong bằng một mặt phẳng song song trục tọa độ.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đường mức (Level Curves / Contours)&lt;/strong&gt;:
Tập hợp các điểm có cùng giá trị hàm \(f(x, y) = c\). Nhìn vào bản đồ đường mức (giống bản đồ địa hình), ta nhận diện ngay đáy thung lũng, yên ngựa và vùng khe hẹp khó hội tụ.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Ma trận Jacobian và Hessian&lt;/strong&gt;:
Jacobian tổng hợp toàn bộ đạo hàm riêng bậc nhất cho hàm nhận vector và trả về vector (như một lớp mạng nơ-ron), còn Hessian lưu đạo hàm bậc hai mô tả độ cong lồi/lõm của bề mặt mất mát.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Quy tắc dây chuyền đa biến (Multivariable Chain Rule)&lt;/strong&gt;:
Cộng dồn mọi đường lan truyền ảnh hưởng từ một biến đầu vào qua nhiều biến trung gian tới đầu ra cuối cùng—chính xác là cơ chế tính gradient qua các tầng nối tiếp và kết nối tắt (&lt;em&gt;skip connections&lt;/em&gt;) của ResNet.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-đạo-hàm-riêng-và-quy-tắc-dây-chuyền-cho-mạng-2-nhánh&quot;&gt;Giải thích: Tính tay đạo hàm riêng và quy tắc dây chuyền cho mạng 2 nhánh&lt;/h3&gt;

&lt;p&gt;Xét một hàm hợp mô phỏng mạng hai nhánh hội tụ: \(z = u^2 + 3uv\), trong đó hai nhánh trung gian phụ thuộc vào cùng một tham số \(t\) theo \(u(t) = 2t\) và \(v(t) = t + 1\). Hãy tính \(\frac{dz}{dt}\) tại \(t = 1\) theo đúng quy tắc dây chuyền đa biến:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính giá trị lan truyền xuôi tại \(t = 1\)&lt;/strong&gt;:
\(u(1) = 2(1) = 2, \quad v(1) = 1 + 1 = 2 \implies z(1) = 2^2 + 3(2)(2) = 4 + 12 = 16.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tính các đạo hàm riêng cục bộ&lt;/strong&gt;:
\(\frac{\partial z}{\partial u} = 2u + 3v = 2(2) + 3(2) = 10, \quad \frac{\partial z}{\partial v} = 3u = 3(2) = 6.\)
\(\frac{du}{dt} = 2, \quad \frac{dv}{dt} = 1.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cộng đóng góp từ cả hai nhánh (Chain Rule)&lt;/strong&gt;:
\(\frac{dz}{dt} = \frac{\partial z}{\partial u}\frac{du}{dt} + \frac{\partial z}{\partial v}\frac{dv}{dt} = 10 \times 2 + 6 \times 1 = 26.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm tra chéo bằng cách thế trực tiếp&lt;/strong&gt;: \(z(t) = (2t)^2 + 3(2t)(t+1) = 4t^2 + 6t^2 + 6t = 10t^2 + 6t \implies z&apos;(t) = 20t + 6 \implies z&apos;(1) = 26\). Khớp hoàn toàn! Đây chính là lý do trong đồ thị tính toán, mỗi khi một biến rẽ nhánh, gradient chảy ngược về nó phải được &lt;strong&gt;cộng dồn&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bài học này trình bày khái niệm đạo hàm và các công cụ giải tích đa biến cốt lõi làm nền tảng cho lý thuyết và thuật toán tối ưu hóa.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;đạo-hàm-và-tốc-độ-biến-thiên&quot;&gt;Đạo hàm và tốc độ biến thiên&lt;/h2&gt;

&lt;p&gt;Đạo hàm của hàm một biến biểu thị tốc độ biến thiên tức thời của hàm số, giúp ta mô tả chính xác hành vi cục bộ của hàm quanh một điểm.&lt;/p&gt;

&lt;h3 id=&quot;các-khái-niệm-cơ-bản-về-đạo-hàm&quot;&gt;Các khái niệm cơ bản về đạo hàm&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Độ dốc giữa hai điểm:&lt;/strong&gt;&lt;/p&gt;

\[\text{Độ dốc} = \frac{y_2 - y_1}{x_2 - x_1}\]

&lt;p&gt;&lt;strong&gt;Đạo hàm (tốc độ biến thiên tức thời):&lt;/strong&gt;&lt;/p&gt;

\[f&apos;(x_0) = \lim_{x_1 \to x_0} \frac{f(x_1) - f(x_0)}{x_1 - x_0} = \lim_{\Delta x \to 0} \frac{f(x_0 + \Delta x) - f(x_0)}{\Delta x}\]

&lt;p&gt;Đạo hàm cho biết hàm số thay đổi nhanh hay chậm tại từng điểm, từ đó hỗ trợ tìm các điểm tối ưu — nơi tốc độ biến thiên bằng không.&lt;/p&gt;

&lt;h3 id=&quot;đường-mức-của-hàm-số&quot;&gt;Đường mức của hàm số&lt;/h3&gt;

&lt;p&gt;Đường mức là công cụ quen thuộc trong giải tích đa biến để trực quan hóa hàm hai biến \(f(x, y)\), cho phép biểu diễn một bề mặt trong không gian 3D trên mặt phẳng 2D.&lt;/p&gt;

&lt;p&gt;Một &lt;strong&gt;đường mức&lt;/strong&gt; của hàm số \(f(x, y)\) là tập hợp tất cả các điểm \((x, y)\) trong miền xác định sao cho hàm số nhận cùng một giá trị hằng số:&lt;/p&gt;

\[f(x, y) = c\]

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Với \(f(x, y) = x^2 + y^2\), các đường mức là những đường tròn đồng tâm: \(x^2 + y^2 = c\).&lt;/li&gt;
  &lt;li&gt;Với \(f(x, y) = x + y\), các đường mức là những đường thẳng song song: \(x + y = c\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Đường mức giúp ta nhận diện:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Hình dạng địa hình của hàm số.&lt;/li&gt;
  &lt;li&gt;Hướng tăng và hướng giảm dốc nhất.&lt;/li&gt;
  &lt;li&gt;Vị trí của các điểm cực trị tiềm năng.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;các-khái-niệm-chính-của-giải-tích-đa-biến&quot;&gt;Các khái niệm chính của giải tích đa biến&lt;/h2&gt;

&lt;h3 id=&quot;đạo-hàm-riêng&quot;&gt;Đạo hàm riêng&lt;/h3&gt;

&lt;p&gt;Với hàm số \(f(x_1, x_2, \ldots, x_n)\), &lt;strong&gt;đạo hàm riêng&lt;/strong&gt; theo biến \(x_i\) được định nghĩa là:&lt;/p&gt;

\[\frac{\partial f}{\partial x_i} = \lim_{h \to 0} \frac{f(x_1, \ldots, x_i + h, \ldots, x_n) - f(x_1, \ldots, x_i, \ldots, x_n)}{h}\]

&lt;p&gt;Đại lượng này đo mức độ biến thiên của \(f\) khi chỉ riêng \(x_i\) thay đổi trong khi tất cả các biến còn lại được giữ cố định.&lt;/p&gt;

&lt;h3 id=&quot;vector-gradient&quot;&gt;Vector gradient&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Gradient&lt;/strong&gt; là vector tổng hợp tất cả các đạo hàm riêng của hàm số:&lt;/p&gt;

\[\nabla f(\mathbf{x}) = \begin{pmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_n} \end{pmatrix}\]

&lt;p&gt;Gradient chỉ theo hướng tăng dốc nhất của hàm số và luôn vuông góc với các đường mức.&lt;/p&gt;

&lt;h3 id=&quot;ma-trận-hessian&quot;&gt;Ma trận Hessian&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ma trận Hessian&lt;/strong&gt; tập hợp toàn bộ các đạo hàm riêng bậc hai của hàm số:&lt;/p&gt;

\[\nabla^2 f(\mathbf{x}) = \mathbf{H} = \begin{pmatrix} 
\frac{\partial^2 f}{\partial x_1^2} &amp;amp; \frac{\partial^2 f}{\partial x_1 \partial x_2} &amp;amp; \cdots &amp;amp; \frac{\partial^2 f}{\partial x_1 \partial x_n} \\
\frac{\partial^2 f}{\partial x_2 \partial x_1} &amp;amp; \frac{\partial^2 f}{\partial x_2^2} &amp;amp; \cdots &amp;amp; \frac{\partial^2 f}{\partial x_2 \partial x_n} \\
\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\
\frac{\partial^2 f}{\partial x_n \partial x_1} &amp;amp; \frac{\partial^2 f}{\partial x_n \partial x_2} &amp;amp; \cdots &amp;amp; \frac{\partial^2 f}{\partial x_n^2}
\end{pmatrix}\]

&lt;p&gt;Ma trận Hessian phản ánh độ cong của hàm số và đóng vai trò quan trọng trong:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Phân loại các điểm tới hạn (cực tiểu, cực đại hoặc điểm yên ngựa).&lt;/li&gt;
  &lt;li&gt;Các thuật toán tối ưu hóa bậc hai như phương pháp Newton.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;quy-tắc-dây-chuyền-cho-hàm-đa-biến&quot;&gt;Quy tắc dây chuyền cho hàm đa biến&lt;/h2&gt;

&lt;p&gt;Quy tắc dây chuyền (&lt;em&gt;chain rule&lt;/em&gt;) là công cụ cơ bản để tính đạo hàm của hàm hợp — dạng hàm xuất hiện rất thường xuyên trong các bài toán tối ưu hóa.&lt;/p&gt;

&lt;h3 id=&quot;quy-tắc-dây-chuyền-cơ-bản&quot;&gt;Quy tắc dây chuyền cơ bản&lt;/h3&gt;

&lt;p&gt;Với hàm số \(z = f(x, y)\) trong đó \(x = g(t)\) và \(y = h(t)\):&lt;/p&gt;

\[\frac{dz}{dt} = \frac{\partial f}{\partial x} \frac{dx}{dt} + \frac{\partial f}{\partial y} \frac{dy}{dt}\]

&lt;h3 id=&quot;quy-tắc-dây-chuyền-tổng-quát&quot;&gt;Quy tắc dây chuyền tổng quát&lt;/h3&gt;

&lt;p&gt;Với \(z = f(x_1, x_2, \ldots, x_n)\) trong đó mỗi \(x_i = x_i(t_1, t_2, \ldots, t_m)\):&lt;/p&gt;

\[\frac{\partial z}{\partial t_j} = \sum_{i=1}^{n} \frac{\partial f}{\partial x_i} \frac{\partial x_i}{\partial t_j}\]

&lt;h3 id=&quot;ứng-dụng-trong-tối-ưu-hóa&quot;&gt;Ứng dụng trong tối ưu hóa&lt;/h3&gt;

&lt;p&gt;Quy tắc dây chuyền được sử dụng trực tiếp trong:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính gradient:&lt;/strong&gt; tính gradient của các hàm mục tiêu dạng hàm hợp.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xử lý ràng buộc:&lt;/strong&gt; xử lý các biến phụ thuộc thông qua phương trình ràng buộc.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cài đặt thuật toán:&lt;/strong&gt; thuật toán lan truyền ngược (&lt;em&gt;backpropagation&lt;/em&gt;) trong mạng nơ-ron và vi phân tự động.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Phân tích độ nhạy:&lt;/strong&gt; đánh giá tác động của việc thay đổi tham số lên nghiệm tối ưu.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-tối-ưu-hóa-có-ràng-buộc&quot;&gt;Ví dụ: Tối ưu hóa có ràng buộc&lt;/h3&gt;

&lt;p&gt;Xét bài toán cực tiểu hóa \(f(x, y) = x^2 + y^2\) với ràng buộc \(g(x, y) = x + y - 1 = 0\).&lt;/p&gt;

&lt;p&gt;Từ phương trình ràng buộc, ta rút \(y = 1 - x\) để đưa về bài toán một biến:
\(h(x) = f(x, 1-x) = x^2 + (1-x)^2\)&lt;/p&gt;

&lt;p&gt;Áp dụng quy tắc dây chuyền:
\(h&apos;(x) = \frac{\partial f}{\partial x} \cdot 1 + \frac{\partial f}{\partial y} \cdot \frac{d(1-x)}{dx} = 2x + 2(1-x)(-1) = 4x - 2\)&lt;/p&gt;

&lt;p&gt;Giải phương trình \(h&apos;(x) = 0\) ta được \(x = 1/2\), suy ra điểm tối ưu là \((1/2, 1/2)\).&lt;/p&gt;

&lt;p&gt;Ví dụ này cho thấy cách các khái niệm giải tích đa biến phối hợp với nhau để giải bài toán tối ưu hóa một cách có hệ thống.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [The paradox of the derivative&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of calculus](https://www.youtube.com/watch?v=9vKqVkMQHKk) — 3Blue1Brown, tiếng Anh. Giới thiệu đạo hàm một biến dưới góc nhìn tốc độ biến thiên.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EoEV5-_mLeM&quot;&gt;What are derivatives in 3D? Intro to Partial Derivatives&lt;/a&gt; — Dr. Trefor Bazett, tiếng Anh. Giải thích đạo hàm riêng như tốc độ biến thiên theo từng trục tọa độ khi đầu vào là vector.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Visualizing the chain rule and product rule&lt;/td&gt;
          &lt;td&gt;Chapter 4, Essence of calculus](https://www.youtube.com/watch?v=YG15m2VwSjA) — 3Blue1Brown, tiếng Anh. Minh họa trực quan quy tắc dây chuyền ở trường hợp một biến; dạng đa biến trong bài là sự mở rộng trực tiếp của quy tắc này dọc theo phép hợp hàm.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01-01 Tính liên tục và Tính liên tục đều</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_01_01_Continuity_and_Uniform_Continuity/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_01_01_Continuity_and_Uniform_Continuity</id>
   <content type="html">&lt;p&gt;Tưởng tượng bạn đang tinh chỉnh núm vặn âm lượng: chỉ xoay nhẹ 1 milimet mà loa bất ngờ rú lên gấp nghìn lần, bạn sẽ không bao giờ chỉnh được mức nghe vừa ý. Trong Deep Learning, mạng nơ-ron gặp đúng thảm họa đó nếu hàm mất mát hay các tầng biến đổi thiếu &lt;strong&gt;tính liên tục&lt;/strong&gt;, &lt;strong&gt;liên tục đều&lt;/strong&gt;, và đặc biệt là &lt;strong&gt;tính liên tục Lipschitz&lt;/strong&gt;—khái niệm từng cứu sống kiến trúc Wasserstein GAN (WGAN) khỏi cảnh bất ổn định nổi tiếng. Bài học này sẽ bóc tách ba tầng “độ mượt” ngày càng chặt chẽ của hàm số để bạn nhìn rõ chúng bảo vệ quá trình huấn luyện như thế nào.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-ba-cấp-độ-mượt-của-hàm-số-trong-tối-ưu-hóa&quot;&gt;Kiến thức cần nhớ: Ba cấp độ mượt của hàm số trong tối ưu hóa&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Liên tục tại điểm và trên miền (Pointwise Continuity)&lt;/strong&gt;:
Đảm bảo hàm không bị đứt gãy đột ngột; tuy nhiên bán kính an toàn \(\delta\) có thể phải thu nhỏ vô hạn khi đi tới vùng hàm dốc đứng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Liên tục đều (Uniform Continuity)&lt;/strong&gt;:
Áp đặt một bán kính \(\delta\) dùng chung cho &lt;em&gt;mọi&lt;/em&gt; điểm trên toàn miền xác định, triệt tiêu tình huống hàm ngày càng dốc vô hạn ở gần biên (như \(1/x\) gần \(0\)).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Liên tục Lipschitz (Lipschitz Continuity)&lt;/strong&gt;:
Mạnh hơn cả liên tục đều: chặn trên trực tiếp tốc độ biến thiên \(\lvert f(x) - f(y) \rvert \le L \lvert x - y \rvert\) bằng một hằng số \(L\) cố định. Trong tối ưu hóa, gradient \(L\)-Lipschitz cho phép chọn bước học an toàn \(\eta \le 1/L\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vai trò trong Deep Learning hiện đại&lt;/strong&gt;:
Các kỹ thuật như Spectral Normalization, Gradient Clipping hay Weight Decay đều xoay quanh mục tiêu kiểm soát hằng số Lipschitz của mạng để chống bùng nổ gradient và tăng khả năng chống nhiễu đối kháng (&lt;em&gt;adversarial robustness&lt;/em&gt;).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-so-sánh-tay-fx--x2-trên-0-2-và-trên-mathbbr&quot;&gt;Giải thích: So sánh tay \(f(x) = x^2\) trên \([0, 2]\) và trên \(\mathbb{R}\)&lt;/h3&gt;

&lt;p&gt;Hãy kiểm tra trực tiếp bằng số vì sao \(f(x) = x^2\) là Lipschitz trên đoạn đóng \([0, 2]\) nhưng &lt;strong&gt;không&lt;/strong&gt; liên tục đều trên toàn trục thực \(\mathbb{R}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Trên đoạn \([0, 2]\)&lt;/strong&gt;: Với mọi \(x, y \in [0, 2]\), ta có:
\(\lvert x^2 - y^2 \rvert = \lvert x + y \rvert \cdot \lvert x - y \rvert \le (2 + 2)\lvert x - y \rvert = 4\lvert x - y \rvert.\)
Vậy \(f(x) = x^2\) là &lt;strong&gt;Lipschitz với hằng số \(L = 4\)&lt;/strong&gt; trên \([0, 2]\). Nếu muốn \(\lvert f(x) - f(y) \rvert &amp;lt; 0.04\), chỉ cần chọn duy nhất \(\delta = 0.01\) cho mọi cặp điểm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trên toàn \(\mathbb{R}\)&lt;/strong&gt;: Giả sử thử cố định bước nhỏ \(\delta = 0.01\) và đặt \(y = x + 0.01\):
    &lt;ul&gt;
      &lt;li&gt;Tại \(x = 1\): \(\lvert f(1.01) - f(1) \rvert = \lvert 1.0201 - 1 \rvert = 0.0201\).&lt;/li&gt;
      &lt;li&gt;Tại \(x = 100\): \(\lvert f(100.01) - f(100) \rvert = \lvert 10002.0001 - 10000 \rvert = 2.0001\).&lt;/li&gt;
      &lt;li&gt;Tại \(x = 10000\): hiệu vọt lên \(200.0001\)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kết luận trực giác&lt;/strong&gt;: Dù \(x^2\) rất mượt ở từng điểm, độ dốc \(2x\) tăng không giới hạn khi \(x \to \infty\), khiến một bước học cố định sẽ làm sai số nổ tung ở vùng trọng số lớn—đó là lý do chuẩn hóa dữ liệu và ràng buộc trọng số (như Weight Decay) cực kỳ quan trọng trong Deep Learning.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Bài học này giới thiệu các khái niệm cơ bản về tính liên tục, tính liên tục đều và tính liên tục Lipschitz — những công cụ quan trọng để phân tích hành vi của hàm số trong tối ưu hóa.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;tính-liên-tục-và-tính-liên-tục-đều&quot;&gt;Tính liên tục và tính liên tục đều&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Tính liên tục&lt;/strong&gt; và &lt;strong&gt;tính liên tục đều&lt;/strong&gt; đều mô tả mức độ “mượt” hay “ổn định” trong sự biến thiên của hàm số. Dù liên quan chặt chẽ với nhau, hai khái niệm này mang bản chất khác biệt: tính liên tục đều là điều kiện mạnh hơn so với tính liên tục thông thường.&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa-tính-liên-tục&quot;&gt;Định nghĩa tính liên tục&lt;/h3&gt;

&lt;p&gt;Một hàm số \(f: A \to \mathbb{R}\) được gọi là &lt;strong&gt;liên tục tại điểm&lt;/strong&gt; \(c \in A\) nếu với mọi số thực dương \(\varepsilon &amp;gt; 0\), tồn tại số thực dương \(\delta &amp;gt; 0\) sao cho với mọi \(x \in A\), hễ&lt;/p&gt;

\[\lvert x - c \rvert &amp;lt; \delta\]

&lt;p&gt;thì&lt;/p&gt;

\[\lvert f(x) - f(c) \rvert &amp;lt; \varepsilon.\]

&lt;p&gt;Về mặt trực quan, với bất kỳ sai số cho phép \(\varepsilon\) nào ở đầu ra \(f(x)\), ta luôn tìm được một lân cận đủ nhỏ quanh \(c\) (bán kính \(\delta\)) sao cho mọi điểm \(x\) trong lân cận đó đều có giá trị \(f(x)\) sai khác \(f(c)\) nhỏ hơn \(\varepsilon\). Điểm mấu chốt ở đây là \(\delta\) nhìn chung phụ thuộc vào cả \(\varepsilon\) lẫn điểm cụ thể \(c\).&lt;/p&gt;

&lt;p&gt;Một hàm số được gọi là &lt;strong&gt;liên tục trên tập hợp&lt;/strong&gt; \(A\) nếu nó liên tục tại mọi điểm \(c \in A\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Một số ví dụ về hàm liên tục&lt;/strong&gt; gồm các đa thức (như \(f(x) = x^2 + 3x - 1\)), các hàm lượng giác \(\sin(x)\), \(\cos(x)\) và hàm mũ \(e^x\) trên miền xác định tương ứng của chúng.&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa-tính-liên-tục-đều&quot;&gt;Định nghĩa tính liên tục đều&lt;/h3&gt;

&lt;p&gt;Ngược lại, &lt;strong&gt;tính liên tục đều&lt;/strong&gt; đặt ra yêu cầu chặt chẽ hơn. Một hàm số \(f: A \to \mathbb{R}\) được gọi là &lt;strong&gt;liên tục đều trên tập hợp&lt;/strong&gt; \(A\) nếu với mọi số thực dương \(\varepsilon &amp;gt; 0\), tồn tại số thực dương \(\delta &amp;gt; 0\) sao cho với mọi \(x, y \in A\), hễ&lt;/p&gt;

\[\lvert x - y \rvert &amp;lt; \delta\]

&lt;p&gt;thì&lt;/p&gt;

\[\lvert f(x) - f(y) \rvert &amp;lt; \varepsilon.\]

&lt;p&gt;&lt;strong&gt;Điểm khác biệt cốt lõi&lt;/strong&gt; so với tính liên tục từng điểm nằm ở thứ tự các lượng từ: với tính liên tục &lt;strong&gt;đều&lt;/strong&gt;, giá trị \(\delta\) chỉ phụ thuộc vào \(\varepsilon\) và áp dụng đồng thời cho mọi cặp điểm \(x, y\) trên toàn miền xác định.&lt;/p&gt;

&lt;h3 id=&quot;định-nghĩa-tính-liên-tục-lipschitz&quot;&gt;Định nghĩa tính liên tục Lipschitz&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Tính liên tục Lipschitz&lt;/strong&gt; đưa ra một điều kiện định lượng cụ thể hơn nữa. Một hàm số \(f: A \to \mathbb{R}\) được gọi là &lt;strong&gt;liên tục Lipschitz&lt;/strong&gt; (hay &lt;strong&gt;\(L\)-Lipschitz&lt;/strong&gt;) trên tập hợp \(A\) nếu tồn tại hằng số \(L \geq 0\) sao cho với mọi \(x, y \in A\):&lt;/p&gt;

\[\lvert f(x) - f(y) \rvert \leq L \lvert x - y \rvert.\]

&lt;p&gt;Hằng số \(L\) nhỏ nhất thỏa mãn bất đẳng thức trên được gọi là &lt;strong&gt;hằng số Lipschitz&lt;/strong&gt; (hay &lt;strong&gt;mô-đun Lipschitz&lt;/strong&gt;) của \(f\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Các tính chất chính của tính liên tục Lipschitz:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tốc độ biến thiên bị chặn:&lt;/strong&gt; Điều kiện Lipschitz đảm bảo hàm số không thể biến thiên nhanh hơn một tốc độ tuyến tính xác định bởi \(L\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Suy ra tính liên tục đều:&lt;/strong&gt; Mọi hàm liên tục Lipschitz đều liên tục đều (chỉ cần chọn \(\delta = \varepsilon/L\) khi \(L &amp;gt; 0\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Khả vi hầu khắp nơi:&lt;/strong&gt; Hàm liên tục Lipschitz khả vi hầu khắp nơi, và tại mọi điểm có đạo hàm thì \(\lvert f&apos;(x) \rvert \leq L\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(f(x) = \lvert x \rvert\) là hàm 1-Lipschitz trên \(\mathbb{R}\).&lt;/li&gt;
  &lt;li&gt;\(f(x) = \sin(x)\) là hàm 1-Lipschitz trên \(\mathbb{R}\) (vì \(\lvert \cos(x) \rvert \leq 1\)).&lt;/li&gt;
  &lt;li&gt;\(f(x) = x^2\) không liên tục Lipschitz trên toàn \(\mathbb{R}\), nhưng liên tục Lipschitz trên mọi khoảng bị chặn.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;so-sánh-và-quan-hệ-bao-hàm&quot;&gt;So sánh và quan hệ bao hàm&lt;/h3&gt;

&lt;p&gt;Ba lớp hàm trên tạo thành một quan hệ bao hàm theo chiều mạnh dần của điều kiện:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tính liên tục Lipschitz ⊆ Tính liên tục đều ⊆ Tính liên tục&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tính chất cục bộ so với toàn cục:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Tính liên tục:&lt;/strong&gt; tính chất cục bộ (xét riêng tại từng điểm).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tính liên tục đều:&lt;/strong&gt; tính chất toàn cục trên cả miền xác định.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tính liên tục Lipschitz:&lt;/strong&gt; tính chất toàn cục kèm chặn định lượng rõ ràng.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sự phụ thuộc của \(\delta\):&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Tính liên tục:&lt;/strong&gt; \(\delta\) có thể phụ thuộc vào cả \(\varepsilon\) và điểm \(c\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tính liên tục đều:&lt;/strong&gt; \(\delta\) chỉ phụ thuộc vào \(\varepsilon\), dùng chung cho mọi điểm.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tính liên tục Lipschitz:&lt;/strong&gt; có công thức tường minh \(\delta = \varepsilon/L\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kiểm soát tốc độ biến thiên:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Tính liên tục:&lt;/strong&gt; không kiểm soát tốc độ biến thiên.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tính liên tục đều:&lt;/strong&gt; đảm bảo mức biến thiên bị chặn trên các khoảng đủ nhỏ.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tính liên tục Lipschitz:&lt;/strong&gt; áp đặt chặn trên tuyến tính rõ ràng lên tốc độ biến thiên.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quan hệ suy diễn:&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Mọi hàm liên tục Lipschitz đều liên tục đều.&lt;/li&gt;
      &lt;li&gt;Mọi hàm liên tục đều đều liên tục.&lt;/li&gt;
      &lt;li&gt;Các chiều ngược lại nhìn chung không đúng.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;ví-dụ-minh-họa-và-so-sánh&quot;&gt;Ví dụ minh họa và so sánh&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ 1: \(f(x) = x^2\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Trên \(\mathbb{R}\):&lt;/strong&gt; liên tục nhưng không liên tục đều (vì tốc độ biến thiên \(\lvert f&apos;(x) \rvert = 2\lvert x \rvert\) không bị chặn).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trên \([0,1]\):&lt;/strong&gt; liên tục, liên tục đều và Lipschitz với \(L = 2\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ 2: \(f(x) = \sin(x)\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Trên \(\mathbb{R}\):&lt;/strong&gt; liên tục, liên tục đều và 1-Lipschitz (vì \(\lvert \cos(x) \rvert \leq 1\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ 3: \(f(x) = \lvert x \rvert\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Trên \(\mathbb{R}\):&lt;/strong&gt; liên tục, liên tục đều và 1-Lipschitz.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lưu ý:&lt;/strong&gt; hàm không khả vi tại \(x = 0\) nhưng vẫn thỏa mãn điều kiện Lipschitz.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Ví dụ 4: \(f(x) = \sqrt{x}\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Trên \([0,1]\):&lt;/strong&gt; liên tục và liên tục đều, nhưng không liên tục Lipschitz (đạo hàm tiến ra vô cùng khi \(x \to 0^+\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trên \([a,1]\) với \(a &amp;gt; 0\):&lt;/strong&gt; liên tục Lipschitz với \(L = 1/(2\sqrt{a})\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Continuity at a point&lt;/td&gt;
          &lt;td&gt;Limits and continuity&lt;/td&gt;
          &lt;td&gt;AP Calculus AB&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=3KMqU5j7irw) — Khan Academy, tiếng Anh. Giải thích định nghĩa liên tục tại một điểm, là điểm khởi đầu của bài học này.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Limits, L’Hôpital’s rule, and epsilon delta definitions&lt;/td&gt;
          &lt;td&gt;Chapter 7, Essence of calculus](https://www.youtube.com/watch?v=kfF40MiS7zA) — 3Blue1Brown, tiếng Anh. Nửa sau video trình bày ngôn ngữ \(\varepsilon\text{-}\delta\), công cụ dùng để mở rộng từ liên tục từng điểm lên liên tục đều.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Real Analysis&lt;/td&gt;
          &lt;td&gt;Intro to uniform continuity.](https://www.youtube.com/watch?v=gioaYgOQ3AQ) — Michael Penn, tiếng Anh. Tập trung trực tiếp vào tính liên tục đều: một giá trị \(\delta\) duy nhất dùng chung cho cả tập hợp.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-99 Ứng dụng và cập nhật hiện đại (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/vi/chapter00/00_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Một câu hỏi rất thực tế mà nhiều kỹ sư trẻ đặt ra trong giai đoạn 2022–2026 là: &lt;em&gt;“Khi đã có PyTorch, JAX, FlashAttention và các mô hình nền tảng hàng trăm tỷ tham số chạy sẵn qua API, liệu tôi còn cần học giải tích đa biến, giá trị riêng hay xác suất làm gì nữa?”&lt;/em&gt; Thực tế tại các phòng thí nghiệm AI hàng đầu cho thấy điều hoàn toàn ngược lại: chính ở biên giới hiện đại—từ tinh chỉnh mô hình hạng thấp (LoRA), mạng nơ-ron tích hợp vật lý (PINN), cho tới mô hình sinh Diffusion và căn chỉnh RLHF—toán học nền tảng lại là thứ phân biệt người chỉ biết gọi thư viện với kỹ sư có thể chẩn đoán, tối ưu và sáng tạo kiến trúc mới.&lt;/p&gt;

&lt;h2 id=&quot;kiến-thức-cần-nhớ-bốn-cầu-nối-từ-toán-nền-tảng-chương-00-đến-deep-learning-20222026&quot;&gt;Kiến thức cần nhớ: Bốn cầu nối từ Toán nền tảng Chương 00 đến Deep Learning 2022–2026&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Đại số tuyến tính hạng thấp \(\to\) Tinh chỉnh hiệu quả tham số (LoRA / QLoRA)&lt;/strong&gt;:
Thay vì cập nhật toàn bộ ma trận trọng số \(\mathbf{W} \in \mathbb{R}^{d \times d}\) của LLM, LoRA phân rã độ lệch \(\Delta \mathbf{W} = \mathbf{B}\mathbf{A}\) với hạng \(r \ll d\), cắt giảm tới &amp;gt;99% số tham số huấn luyện mà vẫn giữ nguyên hiệu năng.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Giải tích vi phân tự động bậc cao \(\to\) Học máy Khoa học (PINN &amp;amp; Neural ODE)&lt;/strong&gt;:
Đưa trực tiếp các phương trình đạo hàm riêng (PDE) như Navier–Stokes hay phương trình truyền nhiệt vào hàm mất mát để mạng nơ-ron học nghiệm tuân thủ định luật vật lý.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Phân phối Gaussian &amp;amp; Quá trình ngẫu nhiên \(\to\) Mô hình Diffusion &amp;amp; Flow Matching&lt;/strong&gt;:
Sinh ảnh/video độ phân giải cao bằng cách học đảo ngược quá trình cộng nhiễu Gaussian từng bước thông qua dự đoán hàm điểm (&lt;em&gt;score function&lt;/em&gt; \(\nabla_{\mathbf{x}} \log p(\mathbf{x})\)).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;KL-Divergence &amp;amp; Tối ưu có ràng buộc \(\to\) Căn chỉnh LLM (RLHF / DPO)&lt;/strong&gt;:
Giữ cho mô hình ngôn ngữ sau tinh chỉnh không trôi quá xa phân phối gốc bằng số hạng phạt \(\beta\, D_{\text{KL}}(\pi_\theta \| \pi_{\text{ref}})\).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;giải-thích-tính-tay-tỷ-lệ-tiết-kiệm-tham-số-của-lora-bằng-phép-nhân-ma-trận-hạng-thấp&quot;&gt;Giải thích: Tính tay tỷ lệ tiết kiệm tham số của LoRA bằng phép nhân ma trận hạng thấp&lt;/h3&gt;

&lt;p&gt;Giả sử một lớp chiếu (&lt;em&gt;projection layer&lt;/em&gt;) trong mô hình ngôn ngữ lớn có ma trận trọng số vuông \(\mathbf{W} \in \mathbb{R}^{4096 \times 4096}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tinh chỉnh toàn phần (Full Fine-Tuning)&lt;/strong&gt;:
Số tham số cần cập nhật và lưu trạng thái optimizer cho riêng ma trận này là:
\(4096 \times 4096 = 16{,}777{,}216 \text{ tham số } (\approx 16.78\text{ triệu}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tinh chỉnh bằng LoRA với hạng \(r = 8\)&lt;/strong&gt;:
Ta đóng băng \(\mathbf{W}\) và chỉ học hai ma trận mỏng \(\mathbf{B} \in \mathbb{R}^{4096 \times 8}\) và \(\mathbf{A} \in \mathbb{R}^{8 \times 4096}\) sao cho \(\Delta \mathbf{W} = \mathbf{B}\mathbf{A}\):
    &lt;ul&gt;
      &lt;li&gt;Số tham số của \(\mathbf{B}\): \(4096 \times 8 = 32{,}768\).&lt;/li&gt;
      &lt;li&gt;Số tham số của \(\mathbf{A}\): \(8 \times 4096 = 32{,}768\).&lt;/li&gt;
      &lt;li&gt;Tổng số tham số huấn luyện: \(65{,}536\) tham số.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tỷ lệ cắt giảm&lt;/strong&gt;:
\(\frac{65{,}536}{16{,}777{,}216} = \frac{1}{256} \approx 0.39\%!\)
Chỉ từ một ý tưởng đại số tuyến tính cổ điển (phân rã hạng thấp), LoRA giúp bạn tinh chỉnh mô hình hàng tỷ tham số ngay trên một GPU cá nhân.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;tùy-chọn-giải-tích-đại-số-tuyến-tính-và-xác-suất-trong-hệ-sinh-thái-20222026&quot;&gt;Tùy chọn: Giải tích, đại số tuyến tính và xác suất trong hệ sinh thái 2022–2026&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;Bài này là phần &lt;strong&gt;tùy chọn&lt;/strong&gt;, &lt;strong&gt;không&lt;/strong&gt; thay thế các bài học cốt lõi về giải tích, đại số tuyến tính hay xác suất. Mục đích của bài là minh họa các khái niệm toán học đó đang được dùng như thế nào trong phần mềm khoa học và hệ thống thực tế hiện nay.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Ý tưởng xuyên suốt của chương là gradient, ma trận và phân phối xác suất tạo thành ngôn ngữ chung của quá trình học máy. Trong giai đoạn 2022–2026, ngôn ngữ này được thực thi trực tiếp ở cấp trình biên dịch: đồ thị toán học được biên dịch thành kernel GPU, còn mã tính toán khoa học dùng chung cơ chế vi phân tự động (&lt;em&gt;autodiff&lt;/em&gt;) với học sâu.&lt;/p&gt;

&lt;h2 id=&quot;1-vì-sao-kiến-thức-toán-nền-tảng-vẫn-cần-thiết&quot;&gt;1. Vì sao kiến thức toán nền tảng vẫn cần thiết&lt;/h2&gt;

&lt;p&gt;Vi phân tự động (&lt;em&gt;automatic differentiation&lt;/em&gt;) là phiên bản được chuẩn hóa ở quy mô công nghiệp của quy tắc dây chuyền trong giải tích. Nếu \(f = g \circ h\) thì:&lt;/p&gt;

\[Df(\mathbf{x}) = Dg(h(\mathbf{x})) \cdot Dh(\mathbf{x}).\]

&lt;p&gt;Chế độ ngược (&lt;em&gt;reverse-mode&lt;/em&gt;, được dùng trong PyTorch và JAX) nhân chuỗi đạo hàm này từ đầu ra ngược về đầu vào — chính là thuật toán lan truyền ngược cho hàm mất mát vô hướng. Điểm mới của các hệ thống hiện đại không nằm ở công thức đạo hàm, mà ở &lt;em&gt;cách&lt;/em&gt; tích đạo hàm được lập lịch, gộp phép toán (&lt;em&gt;fusion&lt;/em&gt;) và kiểm soát độ ổn định số.&lt;/p&gt;

&lt;h2 id=&quot;2-một-số-ứng-dụng-cụ-thể&quot;&gt;2. Một số ứng dụng cụ thể&lt;/h2&gt;

&lt;h3 id=&quot;học-máy-khoa-học-scientific-ml-và-pinn&quot;&gt;Học máy khoa học (Scientific ML) và PINN&lt;/h3&gt;

&lt;p&gt;Mạng nơ-ron tích hợp vật lý (PINN — &lt;em&gt;Physics-Informed Neural Networks&lt;/em&gt;) cực tiểu hóa hàm mục tiêu gồm sai số khớp dữ liệu và phần dư của phương trình đạo hàm riêng (PDE). Phần dư ứng với toán tử vi phân \(\mathcal{N}\) có dạng:&lt;/p&gt;

\[\mathcal{L}_{\text{PDE}} = \mathbb{E}_{\mathbf{x}}\big\|\mathcal{N}[\hat{u}](\mathbf{x})\big\|^2,\]

&lt;p&gt;trong đó đạo hàm của mạng \(\hat{u}\) được tính bằng vi phân tự động thay vì sai phân hữu hạn. Các thư viện như &lt;a href=&quot;https://docs.nvidia.com/deeplearning/modulus/index.html&quot;&gt;Modulus&lt;/a&gt; của NVIDIA cùng hệ sinh thái JAX (&lt;a href=&quot;https://github.com/google/jax-cfd&quot;&gt;JAX-CFD&lt;/a&gt;, &lt;a href=&quot;https://github.com/jax-md/jax-md&quot;&gt;JAX-MD&lt;/a&gt;) đã đưa cách tiếp cận này trở thành công cụ phổ biến từ sau năm 2022.&lt;/p&gt;

&lt;h3 id=&quot;lập-trình-khả-vi-ngoài-mạng-nơ-ron&quot;&gt;Lập trình khả vi ngoài mạng nơ-ron&lt;/h3&gt;

&lt;p&gt;Các phép biến đổi &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vmap&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt; trong JAX xem mỗi bước mô phỏng như một hàm có thể ghép nối Jacobian. Bản chất của chúng vẫn là đại số tuyến tính (tích Jacobian–vector và vector–Jacobian) kết hợp với khai triển Taylor: một vòng lặp Newton–Schulz hay thuật toán gradient liên hợp (&lt;em&gt;conjugate gradient&lt;/em&gt;) đều có thể trở thành một khối tính toán khả vi.&lt;/p&gt;

&lt;h3 id=&quot;xác-suất-trong-huấn-luyện-mô-hình-nền-tảng&quot;&gt;Xác suất trong huấn luyện mô hình nền tảng&lt;/h3&gt;

&lt;p&gt;Các nghiên cứu về quy luật mở rộng (&lt;em&gt;scaling law&lt;/em&gt;) xem quá trình huấn luyện như một thí nghiệm thống kê, mô tả hàm mất mát \(L\) theo năng lực tính toán, số token và số tham số. Nghiên cứu Chinchilla (&lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Hoffmann et al., 2022&lt;/a&gt;) khớp dữ liệu thực nghiệm bằng mô hình luật lũy thừa:&lt;/p&gt;

\[L(N, D) \approx E + \frac{A}{N^{\alpha}} + \frac{B}{D^{\beta}},\]

&lt;p&gt;vận dụng cùng ngôn ngữ kỳ vọng và hàm hợp lý trong các bài xác suất để phân bổ ngân sách huấn luyện cho mô hình ngôn ngữ lớn (LLM).&lt;/p&gt;

&lt;h2 id=&quot;3-công-cụ-phần-mềm-phổ-biến&quot;&gt;3. Công cụ phần mềm phổ biến&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX&lt;/a&gt; — hỗ trợ kết hợp linh hoạt &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vmap&lt;/code&gt; và &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://pytorch.org/get-started/pytorch-2.0/&quot;&gt;PyTorch 2&lt;/a&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt; — biên dịch đồ thị autograd để tối ưu hiệu năng (&lt;a href=&quot;https://arxiv.org/abs/2404.14294&quot;&gt;Ansel et al., 2024&lt;/a&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/tinygrad/tinygrad&quot;&gt;tinygrad&lt;/a&gt; và &lt;a href=&quot;https://github.com/ml-explore/mlx&quot;&gt;MLX&lt;/a&gt; — các bộ máy vi phân tự động gọn nhẹ, thể hiện rõ bản chất giải tích bên dưới.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-tài-liệu-tham-khảo-20222026&quot;&gt;4. Tài liệu tham khảo (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Training Compute-Optimal Large Language Models (Hoffmann et al., 2022)&lt;/a&gt; — quy luật Chinchilla về việc cân đối đồng thời số lượng token và số tham số.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2404.14294&quot;&gt;PyTorch 2 (Ansel et al., 2024)&lt;/a&gt; — trình biên dịch cho đồ thị autograd.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX&lt;/a&gt; — nền tảng nghiên cứu phổ biến cho vi phân tự động và xử lý song song theo lô (&lt;em&gt;SIMD batching&lt;/em&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-vai-trò-của-bài-này-đối-với-phần-cốt-lõi&quot;&gt;5. Vai trò của bài này đối với phần cốt lõi&lt;/h2&gt;

&lt;p&gt;Bạn vẫn cần dùng các bài giải tích và đại số tuyến tính cốt lõi để tự tay tính \(\nabla f\) và phân tích ma trận. Bài tùy chọn này chỉ bổ sung bức tranh về cách các đối tượng toán học đó vận hành trong trình biên dịch và học máy khoa học, không thay thế phần lý thuyết nền tảng.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Xem trước:&lt;/strong&gt; [Backpropagation calculus&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 4](https://www.youtube.com/watch?v=tIeHLnjs5U8) — 3Blue1Brown, tiếng Anh. Giải thích giải tích đằng sau lan truyền ngược — chính là quy tắc dây chuyền chế độ ngược mà PyTorch và JAX cài đặt.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, tiếng Anh. Tự xây dựng bộ máy vi phân tự động chế độ ngược từ đầu bằng mã nguồn, minh họa trực tiếp kiến thức giải tích của chương.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Visualizing the chain rule and product rule&lt;/td&gt;
          &lt;td&gt;Chapter 4, Essence of calculus](https://www.youtube.com/watch?v=YG15m2VwSjA) — 3Blue1Brown, tiếng Anh. Minh họa quy tắc dây chuyền một biến, cơ sở của đẳng thức \(Df = Dg \cdot Dh\) trong bài.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-07 Modern Decoder Internals and Accounting</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_07_Modern_Internals_and_Accounting/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_07_Modern_Internals_and_Accounting</id>
   <content type="html">&lt;p&gt;Open a 2024–2026 Llama, Qwen, Mistral, or DeepSeek checkpoint and you will notice almost every single sub-layer of the 2017 Vaswani Transformer has been upgraded: LayerNorm became mean-free &lt;strong&gt;RMSNorm&lt;/strong&gt;, sinusoidal positional encodings became relative rotational &lt;strong&gt;RoPE&lt;/strong&gt;, the 2-matrix ReLU MLP became a 3-matrix &lt;strong&gt;SwiGLU&lt;/strong&gt; gate, and Multi-Head Attention became &lt;strong&gt;Grouped-Query Attention (GQA)&lt;/strong&gt; so the KV cache shrinks by $4\times$–$8\times$. Being able to count every parameter and every byte of KV cache in these blocks is the hallmark of a graduate-level LLM engineer.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-modern-decoder-architecture--resource-accounting&quot;&gt;Key ideas: Modern Decoder Architecture &amp;amp; Resource Accounting&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — RMSNorm &amp;amp; Pre-Norm Residual Stability&lt;/strong&gt;: Drops mean-centering to normalize strictly by $\text{RMS}(x) = \sqrt{\frac{1}{d}\sum x_i^2 + \epsilon}$, cutting elementwise memory traffic while stabilizing deep residual streams.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Rotary Positional Embeddings (RoPE)&lt;/strong&gt;: Rotates query and key 2D pairs by position-dependent angles $m\theta_i$ so dot products $q_m^\top k_n$ depend &lt;em&gt;strictly&lt;/em&gt; on relative distance $m - n$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — SwiGLU FFN &amp;amp; Parameter Parity&lt;/strong&gt;: Uses $\big(\text{SiLU}(x W_{\text{gate}}) \odot (x W_{\text{up}})\big) W_{\text{down}}$ with intermediate width $d_{\text{ff}} \approx \frac{8}{3} d_{\text{model}}$ so 3 matrices match the parameter budget of a classic $4 d_{\text{model}}$ 2-matrix MLP.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — GQA KV-Cache &amp;amp; FlashAttention Accounting&lt;/strong&gt;: Shares $n_{\text{kv}} &amp;lt; n_q$ key–value heads across query groups to slash KV-cache VRAM by $n_q / n_{\text{kv}}$, while FlashAttention tiles $Q, K, V$ in fast SRAM to avoid materializing the $O(T^2)$ attention matrix in HBM.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-exact-kv-cache-bytes--rmsnorm-calculation&quot;&gt;Worked example: Exact KV-Cache Bytes &amp;amp; RMSNorm Calculation&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Part A — RMSNorm on a 4D vector&lt;/strong&gt; $x = [1.0,\; -1.0,\; 3.0,\; -3.0]$ with $\epsilon = 0$ and scale $\gamma = [1, 1, 1, 1]$:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Mean square: $\frac{1^2 + (-1)^2 + 3^2 + (-3)^2}{4} = \frac{1 + 1 + 9 + 9}{4} = \frac{20}{4} = 5.0$.&lt;/li&gt;
  &lt;li&gt;$\text{RMS}(x) = \sqrt{5.0} \approx 2.2361$.&lt;/li&gt;
  &lt;li&gt;Normalized output: $x / 2.2361 = [0.4472,\; -0.4472,\; 1.3416,\; -1.3416]$.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Part B — Exact KV-Cache Memory for a Llama-3-8B-Style Decoder&lt;/strong&gt;:
Parameters: $L = 32$ layers, $n_q = 32$ query heads, $n_{\text{kv}} = 8$ KV heads (GQA $4\times$ reduction!), head dim $d_h = 128$, precision BF16 ($2$ bytes), sequence length $T = 8{,}192$ tokens, batch size $B = 1$.&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Bytes per token across all layers (factor $2$ for K and V):
\(2 \times L \times n_{\text{kv}} \times d_h \times 2\text{ bytes} = 2 \times 32 \times 8 \times 128 \times 2 = 131{,}072\text{ bytes} = 128\text{ KB/token}.\)&lt;/li&gt;
  &lt;li&gt;Total KV cache for $8{,}192$ tokens:
\(8{,}192 \times 128\text{ KB} = 1{,}048{,}576\text{ KB} = 1.00\text{ GB}.\)
(Without GQA—using $n_{\text{kv}} = 32$—that exact same context would consume &lt;strong&gt;$4.00\text{ GB}$&lt;/strong&gt;, cutting max concurrent batch size by $4\times$!)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Every architectural tweak in a modern decoder directly translates into verifiable memory and throughput math.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;modern-decoder-internals-and-accounting&quot;&gt;Modern Decoder Internals and Accounting&lt;/h1&gt;

&lt;p&gt;Chapter 08 derives the 2017 Transformer. This lesson is the &lt;strong&gt;LLM-era block&lt;/strong&gt; you will actually open in a 2024–2026 checkpoint: pre-norm RMSNorm, causal attention with RoPE, a SwiGLU feed-forward, and a KV cache at decode time. It also gives the &lt;strong&gt;back-of-the-envelope arithmetic&lt;/strong&gt; students are expected to do in interviews: parameter count, an activation sketch, training FLOPs, and inference memory.&lt;/p&gt;

&lt;p&gt;The 2017 algebra still holds. What changed is packaging and cost. For the neuron-level SwiGLU / RMSNorm note see &lt;strong&gt;02-99&lt;/strong&gt;; for the original encoder–decoder walk see &lt;strong&gt;08-01&lt;/strong&gt;; for the attention kernel story see &lt;strong&gt;07-99&lt;/strong&gt;. This page is the hub that puts those pieces on one decoder stack.&lt;/p&gt;

&lt;h2 id=&quot;1-the-modern-decoder-block&quot;&gt;1. The modern decoder block&lt;/h2&gt;

&lt;p&gt;A Llama-family layer is still “communicate, then compute,” with residuals around each sublayer. The default packaging is &lt;strong&gt;pre-norm&lt;/strong&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart TD
  x[&quot;Residual stream x&quot;] --&amp;gt; n1[&quot;RMSNorm&quot;]
  n1 --&amp;gt; attn[&quot;Causal attention + RoPE&quot;]
  attn --&amp;gt; a1[&quot;Add residual&quot;]
  a1 --&amp;gt; n2[&quot;RMSNorm&quot;]
  n2 --&amp;gt; ffn[&quot;SwiGLU FFN&quot;]
  ffn --&amp;gt; a2[&quot;Add residual&quot;]
  a2 --&amp;gt; y[&quot;Block output&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id=&quot;rmsnorm&quot;&gt;RMSNorm&lt;/h3&gt;

&lt;p&gt;LayerNorm subtracts a mean and divides by a standard deviation. &lt;strong&gt;RMSNorm&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/1910.07467&quot;&gt;Zhang &amp;amp; Sennrich, 2019&lt;/a&gt;) drops the mean and keeps only a root-mean-square scale plus a learned gain \(\gamma\) (no bias in the usual LLM recipe):&lt;/p&gt;

\[\mathrm{RMSNorm}(x) = \frac{x}{\sqrt{\frac{1}{d}\sum_{i=1}^{d} x_i^2 + \varepsilon}} \odot \gamma.\]

&lt;p&gt;Why LMs switched: it is cheaper, it does not fight the residual mean, and it is what the widely copied Llama / Gemma / Qwen stacks ship. The &lt;em&gt;idea&lt;/em&gt; is still “stabilize the scale of the residual stream before the next matmul” (Chapter 09).&lt;/p&gt;

&lt;h3 id=&quot;swiglu-feed-forward&quot;&gt;SwiGLU feed-forward&lt;/h3&gt;

&lt;p&gt;A 2017 FFN is \(\mathrm{ReLU}(x W_1) W_2\). A modern gated FFN (&lt;a href=&quot;https://arxiv.org/abs/2002.05202&quot;&gt;Shazeer, 2020&lt;/a&gt;) is&lt;/p&gt;

\[\mathrm{SwiGLU}(x) = \big(\mathrm{SiLU}(x W_{\mathrm{gate}}) \odot (x W_{\mathrm{up}})\big) W_{\mathrm{down}},\]

&lt;p&gt;with \(\mathrm{SiLU}(z) = z\,\sigma(z)\) (also called Swish). Three matrices instead of two; the extra gate is the Hadamard product. Width is usually chosen so the &lt;strong&gt;parameter count&lt;/strong&gt; stays comparable to a ReLU FFN that was \(4d\) wide (you shrink \(d_{\mathrm{ff}}\) when you add the third matrix). That is an accounting choice, not a new theorem.&lt;/p&gt;

&lt;p&gt;ReLU / SiLU themselves are in &lt;strong&gt;02-03&lt;/strong&gt; and &lt;strong&gt;26-01&lt;/strong&gt;. Here you only need: the FFN is the block’s &lt;em&gt;position-wise&lt;/em&gt; compute, and SwiGLU is the default nonlinearity packaging.&lt;/p&gt;

&lt;h3 id=&quot;rope-as-a-relative-rotation&quot;&gt;RoPE, as a relative rotation&lt;/h3&gt;

&lt;p&gt;Absolute sin–cos positional encodings add a vector to the token embedding. &lt;strong&gt;RoPE&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2104.09864&quot;&gt;Su et al., 2021/2023&lt;/a&gt;) instead &lt;em&gt;rotates&lt;/em&gt; query and key pairs in 2-D planes by an angle that depends on position \(t\):&lt;/p&gt;

\[\begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}
\leftarrow
\begin{pmatrix} \cos(t\theta_i) &amp;amp; -\sin(t\theta_i) \\ \sin(t\theta_i) &amp;amp; \cos(t\theta_i) \end{pmatrix}
\begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix},\]

&lt;p&gt;and the same for \(k\), with fixed frequencies \(\theta_i = \mathrm{base}^{-2i/d}\). The inner product \(q_t^\top k_s\) then depends on \(t-s\), not on absolute \(t\) and \(s\) separately. That is the whole idea: &lt;strong&gt;relative position lives in the attention score&lt;/strong&gt;, not as an extra added embedding. Lesson &lt;strong&gt;08-99&lt;/strong&gt; has the same display; Chapter 08’s sin–cos PE remains the right first model.&lt;/p&gt;

&lt;h3 id=&quot;gqa--mqa-shrinking-the-cache-not-the-scores&quot;&gt;GQA / MQA: shrinking the cache, not the scores&lt;/h3&gt;

&lt;p&gt;Multi-head attention stores one \(K,V\) per query head. &lt;strong&gt;Multi-query&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/1911.02150&quot;&gt;Shazeer, 2019&lt;/a&gt;) shares a single \(K,V\) across heads. &lt;strong&gt;Grouped-query&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2305.13245&quot;&gt;Ainslie et al., 2023&lt;/a&gt;) sits in between: \(n_{\mathrm{q}}\) query heads share \(n_{\mathrm{kv}} \ll n_{\mathrm{q}}\) key/value heads. The attention &lt;em&gt;formula&lt;/em&gt; is unchanged; the &lt;strong&gt;KV-cache&lt;/strong&gt; shrinks by about \(n_{\mathrm{kv}} / n_{\mathrm{q}}\). That is why GQA is a serving feature as much as a training feature (lesson &lt;strong&gt;26-04&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;2-flashattention-as-a-story-not-a-cuda-dump&quot;&gt;2. FlashAttention as a story, not a CUDA dump&lt;/h2&gt;

&lt;p&gt;Exact attention is still \(\mathrm{softmax}(QK^\top / \sqrt{d})\,V\). The naive implementation materializes the \(L\times L\) score matrix in GPU HBM. &lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;Dao et al., 2022&lt;/a&gt; (&lt;strong&gt;FlashAttention&lt;/strong&gt;) never stores that full matrix: they &lt;strong&gt;tile&lt;/strong&gt; \(Q,K,V\) into SRAM-sized blocks and fuse the softmax with the value multiply.&lt;/p&gt;

&lt;p&gt;Softmax over a long row is not a local operation — you need the sum of exponentials. The trick is the same &lt;strong&gt;online / streaming softmax&lt;/strong&gt; already named in &lt;strong&gt;26-01&lt;/strong&gt;: keep a running max \(m\) and a running sum \(s\) of \(e^{z-m}\) as tiles arrive, and &lt;em&gt;rescale&lt;/em&gt; the partial weighted sum of \(V\) whenever \(m\) grows. The output is algebraically the same softmax; the IO is much smaller.&lt;/p&gt;

&lt;p&gt;You do &lt;strong&gt;not&lt;/strong&gt; need the kernel schedule to use the idea. Remember three sentences: (1) attention is IO-bound at LLM sizes; (2) tiling plus online softmax removes the \(L\times L\) write; (3) the numerics are the stable log-sum-exp story, not a new score function. FlashAttention-2/3 improve parallelism and hardware mapping (&lt;a href=&quot;https://arxiv.org/abs/2307.08691&quot;&gt;Dao, 2023&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2407.08608&quot;&gt;Shah et al., 2024&lt;/a&gt;). Pointer back to &lt;strong&gt;07-99&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;3-accounting-students-can-actually-compute&quot;&gt;3. Accounting students can actually compute&lt;/h2&gt;

&lt;p&gt;No invented model cards here — only the &lt;strong&gt;order-of-magnitude&lt;/strong&gt; identities used in Kaplan-style notes and in interviews. Plug in &lt;em&gt;your&lt;/em&gt; \(n_{\mathrm{layers}}\), \(d\), \(V\), \(L\).&lt;/p&gt;

&lt;h3 id=&quot;parameter-count-dense-decoder&quot;&gt;Parameter count (dense decoder)&lt;/h3&gt;

&lt;p&gt;A first sketch, ignoring biases and MoE:&lt;/p&gt;

\[\begin{aligned}
N_{\mathrm{embed}} &amp;amp;\approx 2\, V d
\quad \text{(token table + untied LM head; drop a } Vd \text{ if weights are tied)}, \\
N_{\mathrm{attn}} &amp;amp;\approx n_{\mathrm{layers}}\big( d\cdot d_{\mathrm{q}} + 2\, d\cdot d_{\mathrm{kv}} + d_{\mathrm{q}}\cdot d \big), \\
N_{\mathrm{ffn}} &amp;amp;\approx n_{\mathrm{layers}}\cdot 3\, d\, d_{\mathrm{ff}}
\quad \text{(SwiGLU: gate, up, down)}.
\end{aligned}\]

&lt;p&gt;For multi-head, \(d_{\mathrm{q}} = n_{\mathrm{q}} d_{\mathrm{head}}\) and \(d_{\mathrm{kv}} = n_{\mathrm{kv}} d_{\mathrm{head}}\). Full MHA means \(n_{\mathrm{kv}} = n_{\mathrm{q}}\) and the attention term is about \(4 n_{\mathrm{layers}} d^2\). GQA replaces two of those \(d^2\) blocks by \(d\cdot d_{\mathrm{kv}}\). Embeddings dominate only at small \(d\) or huge \(V\); at typical LLM width the &lt;strong&gt;layers&lt;/strong&gt; dominate.&lt;/p&gt;

&lt;h3 id=&quot;activation-sketch-training&quot;&gt;Activation sketch (training)&lt;/h3&gt;

&lt;p&gt;Forward activations you must keep for the backward pass scale as&lt;/p&gt;

\[n_{\mathrm{layers}} \times B \times L \times d\]

&lt;p&gt;plus attention maps if they are not recomputed. Checkpointing (rematerialization) trades extra FLOPs for a smaller activation footprint. This is why &lt;strong&gt;micro-batch size&lt;/strong&gt; and &lt;strong&gt;sequence length&lt;/strong&gt; hit memory before the weight tensors do.&lt;/p&gt;

&lt;h3 id=&quot;flops-order-of-magnitude&quot;&gt;FLOPs, order of magnitude&lt;/h3&gt;

&lt;p&gt;A dense matmul of an \(n\times m\) weight with a length-\(L\) batch of tokens costs about \(2 n m L\) FLOPs (multiply-add). Summing over the whole network, the usual first-order statement (&lt;a href=&quot;https://arxiv.org/abs/2001.08361&quot;&gt;Kaplan et al., 2020&lt;/a&gt;) is:&lt;/p&gt;

\[\begin{aligned}
C_{\mathrm{fwd}} &amp;amp;\approx 2\, N_{\mathrm{params}}\, T, \\
C_{\mathrm{bwd}} &amp;amp;\approx 2\, C_{\mathrm{fwd}} \approx 4\, N_{\mathrm{params}}\, T, \\
C_{\mathrm{train}} &amp;amp;\approx 6\, N_{\mathrm{params}}\, T,
\end{aligned}\]

&lt;p&gt;where \(T\) is the number of &lt;strong&gt;tokens&lt;/strong&gt; (batch \(\times\) sequence, summed over steps). Attention’s \(O(L^2 d)\) term is ignored in this sketch; it matters at very long \(L\), not in the first interview answer. Backward \(\approx 2\times\) forward is the same “one extra matmul per weight for the input gradient, one for the weight gradient” picture from Chapter 03.&lt;/p&gt;

&lt;h3 id=&quot;inference-memory&quot;&gt;Inference memory&lt;/h3&gt;

&lt;p&gt;At decode time you are not storing a training graph. The resident set is essentially&lt;/p&gt;

\[\mathrm{mem} \approx \underbrace{N_{\mathrm{params}} \cdot b_{\mathrm{w}}}_{\text{weights}} + \underbrace{2 \cdot L \cdot n_{\mathrm{layers}} \cdot n_{\mathrm{kv}} \cdot d_{\mathrm{head}} \cdot b_{\mathrm{kv}}}_{\text{KV cache}},\]

&lt;p&gt;with \(b_{\mathrm{w}}\) and \(b_{\mathrm{kv}}\) the bytes per element (2 for fp16, 1 for int8, …). The factor 2 is keys and values. &lt;strong&gt;This grows linearly in the cached length \(L\)&lt;/strong&gt; — that is the picture in &lt;strong&gt;26-04&lt;/strong&gt;. Quantization shrinks the first term; GQA shrinks the second.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  prefill[&quot;Prefill: write K,V for the prompt&quot;] --&amp;gt; step[&quot;Decode one token&quot;]
  step --&amp;gt; append[&quot;Append one new K,V pair per layer&quot;]
  append --&amp;gt; grow[&quot;Cache length n, memory Theta of n&quot;]
  grow --&amp;gt; step
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;4-scaling-laws-qualitatively-chinchilla-style&quot;&gt;4. Scaling laws, qualitatively (Chinchilla-style)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2001.08361&quot;&gt;Kaplan et al., 2020&lt;/a&gt; showed that, over a wide range, pretraining loss falls as a power law in model size, dataset size, and compute, and that &lt;strong&gt;under a fixed compute budget&lt;/strong&gt; it paid to grow parameters faster than tokens. &lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Hoffmann et al., 2022&lt;/a&gt; (&lt;em&gt;Training Compute-Optimal Large Language Models&lt;/em&gt;, the &lt;strong&gt;Chinchilla&lt;/strong&gt; paper) re-fit the same kind of isoFLOP curves with a different protocol and concluded the opposite allocation: &lt;strong&gt;for a given training-FLOP budget, scale parameters and tokens together&lt;/strong&gt; — many then-popular models were &lt;em&gt;undertrained&lt;/em&gt; (too big for the number of tokens they saw).&lt;/p&gt;

&lt;p&gt;What you should take, without treating any one fitted exponent as a law of nature:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Compute \(C \approx 6 N T\) is the budget you are splitting between \(N\) and \(T\).&lt;/li&gt;
  &lt;li&gt;“Compute-optimal” means: choose \((N, T)\) on that isoFLOP curve so that the &lt;em&gt;loss&lt;/em&gt; is smallest, not so that the &lt;em&gt;model&lt;/em&gt; is largest.&lt;/li&gt;
  &lt;li&gt;Hoffmann et al. found that compute-optimal training in their setup used &lt;strong&gt;on the order of tens of tokens per parameter&lt;/strong&gt;. That is a published fit, not a universal constant; later LMs often train &lt;em&gt;past&lt;/em&gt; that point because inference cost favors a smaller \(N\) that read more tokens.&lt;/li&gt;
  &lt;li&gt;Chapter 25 surveys the research landscape; this lesson only states the &lt;strong&gt;train-time&lt;/strong&gt; trade. Test-time compute (25-99) is a different axis.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Do not quote a loss number or a parameter count you did not measure or read off a paper table.&lt;/p&gt;

&lt;h2 id=&quot;5-rnn--lstm-vs-transformer-and-one-paragraph-on-ssms&quot;&gt;5. RNN / LSTM vs Transformer (and one paragraph on SSMs)&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;RNN / LSTM (Ch. 05–06)&lt;/th&gt;
      &lt;th&gt;Transformer decoder (Ch. 08, this lesson)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;State&lt;/td&gt;
      &lt;td&gt;A hidden vector \(h_t\) updated from \(h_{t-1}\)&lt;/td&gt;
      &lt;td&gt;The whole prefix, mixed by attention&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Parallelism in \(t\)&lt;/td&gt;
      &lt;td&gt;Sequential: step \(t\) needs \(t-1\)&lt;/td&gt;
      &lt;td&gt;Training: all positions in the window at once&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Path length&lt;/td&gt;
      &lt;td&gt;\(O(L)\) steps between distant tokens&lt;/td&gt;
      &lt;td&gt;\(O(1)\) attention hop (inside the window)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Decode cost&lt;/td&gt;
      &lt;td&gt;\(O(1)\) state update per new token&lt;/td&gt;
      &lt;td&gt;\(O(L)\) attend-to-cache per new token&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Long range&lt;/td&gt;
      &lt;td&gt;LSTMs help vanishing gradients; they do not give global mixing&lt;/td&gt;
      &lt;td&gt;Global inside \(L\); cost is the KV cache and \(L^2\) prefill&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;An LSTM gate is a &lt;em&gt;learned&lt;/em&gt; write/forget of a fixed-size cell. Attention is a &lt;em&gt;content-addressed&lt;/em&gt; read of every cached key. That is the interview contrast. Transformers won pretraining throughput (parallel \(t\)) and in-context mixing; RNNs stay cheap per generated token because the state does not grow.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;State-space models (SSMs), one paragraph.&lt;/strong&gt; Linear recurrences such as S4 and Mamba (&lt;a href=&quot;https://arxiv.org/abs/2312.00752&quot;&gt;Gu &amp;amp; Dao, 2023&lt;/a&gt;) replace the attention mixer by a structured state that &lt;em&gt;can&lt;/em&gt; be computed as a convolution in training and as an \(O(1)\)-state step in decode — RNN-like inference cost with Transformer-like training parallelism. They are a real alternative sequence mixer, not “a small LSTM.” This course does not derive the HiPPO / selective-scan algebra; if you meet an SSM paper, ask: &lt;em&gt;what is the state, and is the train path a convolution or a scan?&lt;/em&gt; Then come back to the decoder block above, which is still the default LLM.&lt;/p&gt;

&lt;h2 id=&quot;6-appendix-three-parallelism-pictures&quot;&gt;6. Appendix: three parallelism pictures&lt;/h2&gt;

&lt;p&gt;These diagrams are the vocabulary of a training cluster, not a Megatron tutorial. Each shard is one idea.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data parallelism&lt;/strong&gt; — replicate the whole model; split the batch.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  batch[&quot;Training batch&quot;] --&amp;gt; g1[&quot;Replica GPU 1&quot;]
  batch --&amp;gt; g2[&quot;Replica GPU 2&quot;]
  batch --&amp;gt; g3[&quot;Replica GPU 3&quot;]
  g1 --&amp;gt; avg[&quot;All-reduce gradients&quot;]
  g2 --&amp;gt; avg
  g3 --&amp;gt; avg
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Pipeline parallelism&lt;/strong&gt; — split &lt;em&gt;layers&lt;/em&gt; across devices; a micro-batch walks the pipeline.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  mb[&quot;Micro-batch&quot;] --&amp;gt; p1[&quot;Device A: layers 1 to k&quot;]
  p1 --&amp;gt; p2[&quot;Device B: layers k+1 to 2k&quot;]
  p2 --&amp;gt; p3[&quot;Device C: remaining layers&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Tensor parallelism&lt;/strong&gt; — split &lt;em&gt;one&lt;/em&gt; matmul (or one attention head group) across devices.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  x[&quot;Hidden state x&quot;] --&amp;gt; col1[&quot;Device A: part of W&quot;]
  x --&amp;gt; col2[&quot;Device B: rest of W&quot;]
  col1 --&amp;gt; cat[&quot;All-gather or reduce-scatter&quot;]
  col2 --&amp;gt; cat
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Real stacks mix all three (and ZeRO / FSDP, which shard &lt;em&gt;optimizer state&lt;/em&gt; as well). You only need to name which axis is being split: batch, depth, or width. Chapter 23’s efficiency tools (quantization, distillation) are complementary: they change \(N\) or bits, not how a cluster cuts a step.&lt;/p&gt;

&lt;h2 id=&quot;7-where-this-sits-in-the-hub&quot;&gt;7. Where this sits in the hub&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;26-01&lt;/strong&gt; — CE / softmax / Adam refresh that this block’s last layer uses.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;26-04&lt;/strong&gt; — KV-cache bytes, batching, speculative decoding, sampling.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;08-01 / 08-99&lt;/strong&gt; — full 2017 derivation and the first RoPE display.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;07-99&lt;/strong&gt; — FlashAttention citations and PagedAttention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;25 / 25-99&lt;/strong&gt; — broader scaling and test-time compute.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;further-reading&quot;&gt;Further reading&lt;/h2&gt;

&lt;p&gt;Inspiration and topic map only — &lt;strong&gt;not&lt;/strong&gt; a source to quote. Rewrite was done in this course’s voice; diagrams above are original Mermaid.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Alisa Liu, &lt;em&gt;&lt;a href=&quot;https://alisawuffles.notion.site/alisa-s-book-of-llms&quot;&gt;Alisa’s Book of LLMs&lt;/a&gt;&lt;/em&gt; (public study notes).&lt;/li&gt;
  &lt;li&gt;Alisa Liu, &lt;em&gt;&lt;a href=&quot;https://alisawuffles.notion.site/math-notes&quot;&gt;Math notes&lt;/a&gt;&lt;/em&gt; (same author; fetch is often empty as a Notion SPA — use the URL as a pointer).&lt;/li&gt;
  &lt;li&gt;Kaplan et al., 2020. &lt;a href=&quot;https://arxiv.org/abs/2001.08361&quot;&gt;Scaling Laws for Neural Language Models&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Hoffmann et al., 2022. &lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Training Compute-Optimal Large Language Models&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Vaswani et al., 2017. &lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Su et al., 2023. &lt;a href=&quot;https://arxiv.org/abs/2104.09864&quot;&gt;RoFormer / RoPE&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Zhang &amp;amp; Sennrich, 2019. &lt;a href=&quot;https://arxiv.org/abs/1910.07467&quot;&gt;RMSNorm&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Shazeer, 2020. &lt;a href=&quot;https://arxiv.org/abs/2002.05202&quot;&gt;GLU Variants Improve Transformer&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Dao et al., 2022. &lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;FlashAttention&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Ainslie et al., 2023. &lt;a href=&quot;https://arxiv.org/abs/2305.13245&quot;&gt;GQA&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Gu &amp;amp; Dao, 2023. &lt;a href=&quot;https://arxiv.org/abs/2312.00752&quot;&gt;Mamba&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key takeaways&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Modern decoder layer = RMSNorm → causal attention + RoPE → residual → RMSNorm → SwiGLU → residual.&lt;/li&gt;
  &lt;li&gt;GQA / MQA cut &lt;strong&gt;cache heads&lt;/strong&gt;, not the softmax formula. FlashAttention cuts &lt;strong&gt;IO&lt;/strong&gt;, not the math.&lt;/li&gt;
  &lt;li&gt;Forward FLOPs \(\sim 2 N T\); backward \(\sim 2\times\) that; train \(\sim 6 N T\). Inference memory \(\approx\) weights + KV.&lt;/li&gt;
  &lt;li&gt;Chinchilla-style optimality: split a FLOP budget across &lt;strong&gt;both&lt;/strong&gt; \(N\) and \(T\). Cite Kaplan and Hoffmann; do not invent a loss curve.&lt;/li&gt;
  &lt;li&gt;RNNs compress the past into \(h_t\); Transformers reread a cache of size \(O(L)\). SSMs try to get both.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. The decoder block this lesson asks you to draw (attention, then MLP).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=gBMO1JZav44&quot;&gt;How FlashAttention Accelerates Generative AI Revolution&lt;/a&gt; — Jia-Bin Huang, English. FlashAttention as a memory-traffic story, which is how the lesson wants it told.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PZXN7jm9IC0&quot;&gt;Chinchilla Explained: Compute-Optimal Massive Language Models&lt;/a&gt; — Edan Meyer, English. Chinchilla-style scaling, the qualitative accounting section.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-06 Interviews Practice</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_06_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_06_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Senior LLM engineering interviews test whether you can reason across the full stack on a whiteboard without hand-waving: when to prompt vs. RAG vs. fine-tune, why you should check quantization and speculative decoding &lt;em&gt;before&lt;/em&gt; launching a costly distillation run, how to derive the softmax head gradient in two lines, and how to count every parameter and KV-cache byte of a modern decoder block from scratch.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-full-stack-llm-interview-readiness&quot;&gt;Key ideas: Full-Stack LLM Interview Readiness&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Build-vs-Retrieve-vs-Adapt Decision Tree&lt;/strong&gt;: Separates knowledge injection (RAG), style/format adaptation (prompting / LoRA SFT), and preference/reasoning shaping (DPO / GRPO).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Serving &amp;amp; Compression Triage&lt;/strong&gt;: Evaluates latency and VRAM bottlenecks quantitatively—choosing quantization, prefix caching, or speculative decoding before retraining a student model.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Core Math Derivations on Demand&lt;/strong&gt;: Fluently derives $\partial\mathcal{L}/\partial z = p - t$, temperature-scaled KD gradients, and attention FLOP / KV-cache scaling formulas.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Architecture Accounting&lt;/strong&gt;: Identifies RMSNorm, RoPE, SwiGLU, and GQA in modern checkpoints and verifies parameter counts and memory budgets on the spot.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-solving-an-interview-triage-prompt--rag-vs-fine-tune-latency--cost&quot;&gt;Worked example: Solving an Interview Triage Prompt — RAG vs. Fine-Tune Latency &amp;amp; Cost&lt;/h3&gt;

&lt;p&gt;An interviewer asks: &lt;em&gt;“Our 10,000-document internal policy corpus changes every week. Should we LoRA fine-tune our 8B model weekly or use RAG with a 500-token retrieved context?”&lt;/em&gt; Let us quantify both sides:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Knowledge freshness &amp;amp; hallucination&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Fine-tuning bakes facts loosely into weights, requires weekly retraining/eval pipelines, and still cannot cite exact clause numbers reliably.&lt;/li&gt;
      &lt;li&gt;RAG updates the vector index in seconds whenever a policy PDF changes and grounds answers with verbatim citations.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Incremental inference cost of RAG&lt;/strong&gt; (adding $500$ retrieved tokens to prefill on an 8B model):
    &lt;ul&gt;
      &lt;li&gt;Extra prefill FLOPs: $2 \times 8 \times 10^9 \times 500 = 8 \times 10^{12}$ FLOPs.&lt;/li&gt;
      &lt;li&gt;On an H100 running at $500\text{ TFLOP/s}$ effective BF16 throughput, $8\text{ TFLOPs} / 500\text{ TFLOP/s} = 16\text{ ms}$ extra TTFT!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Clean interview verdict&lt;/strong&gt;: &lt;strong&gt;Use RAG for fast-changing factual knowledge&lt;/strong&gt; (only $16\text{ ms}$ prefill overhead, instant updates, auditable citations), and reserve &lt;strong&gt;SFT/LoRA strictly for domain tone, tool-use formatting, or reasoning style&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Backing architectural choices with concrete latency and FLOP numbers turns a subjective interview question into a decisive engineering answer.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-llm-interview-prompts&quot;&gt;Optional: LLM interview prompts&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace 26-01–26-05 or &lt;strong&gt;26-07&lt;/strong&gt;. The prompts are course-written. They are &lt;strong&gt;not&lt;/strong&gt; taken from Kashani &amp;amp; Ivry, &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, Alisa’s notes, or any blog.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Use them closed-book after you can sketch next-token loss, ICL vs SFT, the SFT → preference pipeline, KV-cache, the three distillation families, and the modern-block / FLOP sketch in &lt;strong&gt;26-07&lt;/strong&gt;. For the course-wide practice map, stay on &lt;strong&gt;01-98&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;p1-what-is-actually-being-trained&quot;&gt;P1. What is actually being trained?&lt;/h2&gt;

&lt;p&gt;You have two minutes. Define an LLM as used in this chapter in one sentence, then name the loss of pretraining and the thing that loss does &lt;em&gt;not&lt;/em&gt; guarantee.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Decoder-only, next-token, not truth.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; A causal Transformer LM trained with token-level cross-entropy on a corpus. The loss rewards corpus likelihood, not factuality, not instruction-following, and not a small memory footprint. Those come from later adaptations (26-02–26-04).&lt;/p&gt;

&lt;h2 id=&quot;p2-prompt-vs-fine-tune-vs-retrieve&quot;&gt;P2. Prompt vs fine-tune vs retrieve&lt;/h2&gt;

&lt;p&gt;A teammate wants “the model to always answer in the company’s invoice JSON schema.” Give one prompting solution, one weight-update solution, and one reason retrieval might still be required.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Template / ICL; SFT or LoRA; facts vs format.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; A fixed schema belongs in the prompt or in SFT/LoRA so the format is stable. Retrieval (18-99) is for &lt;em&gt;which&lt;/em&gt; invoice terms or SKUs exist this week — alignment and prompting will not invent a product catalog.&lt;/p&gt;

&lt;h2 id=&quot;p3-why-not-always-distill-logits&quot;&gt;P3. Why not always distill logits?&lt;/h2&gt;

&lt;p&gt;Explain two reasons a team that only has a hosted chat API would choose &lt;strong&gt;response distillation&lt;/strong&gt; over full token-distribution KD, even if they like the 2015 loss on paper.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Access and \(V\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; The API typically does not expose a \(V\)-way distribution each step. Even if it did, storing or matching that vector on long sequences is expensive; sampled text is what you can legally &lt;em&gt;and&lt;/em&gt; mechanically collect (and only if the terms allow training on it).&lt;/p&gt;

&lt;h2 id=&quot;p4-temperature-as-a-teaching-device&quot;&gt;P4. Temperature as a teaching device&lt;/h2&gt;

&lt;p&gt;A teacher is 99.9% on the correct ImageNet class. Why raise \(T\) before the KL, and what goes wrong if you set \(T\) huge and drop the hard-label term entirely?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Dark knowledge vs uniform soup.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; High \(T\) lifts the interesting off-diagonal mass (dark knowledge). If \(T\to\infty\), the target approaches uniform and the student learns “every class is equally fine,” which is not a useful teacher. The hard CE term (or a moderate \(T\)) keeps the mode anchored. Same intuition applies to a peaked token distribution, which is why LM logit KD often uses top-\(k\) instead of a huge \(T\) alone.&lt;/p&gt;

&lt;h2 id=&quot;p5-serving-before-students&quot;&gt;P5. Serving before students&lt;/h2&gt;

&lt;p&gt;Name two changes you would try &lt;strong&gt;before&lt;/strong&gt; training an 8B student from a 70B teacher you own, and one situation where you would skip those and distill anyway.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; 26-04 then 26-05.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Quantize (4-bit / GGUF), cut unused context, batch, or speculate. Distill anyway when the &lt;em&gt;architecture&lt;/em&gt; must shrink (edge memory, a cheaper SKU, many LoRA specialists on a small base) or when you explicitly want a new \(\theta\) that imitates behavior rather than the same checkpoint with fewer bits.&lt;/p&gt;

&lt;h2 id=&quot;p6-rights-not-headlines&quot;&gt;P6. Rights, not headlines&lt;/h2&gt;

&lt;p&gt;In four sentences, contrast legitimate distillation with unauthorized harvesting &lt;strong&gt;without&lt;/strong&gt; naming a lawsuit or a 2026 news item.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Who owns the teacher; what the API is for.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; If you own the teacher or its license invites synthetic-data / in-family students, distillation is a compression and product-tier tool. If you only have a customer API, the text is a service output; many terms forbid using it as a training corpus for a competing model. The tension is structural: useful APIs leak capability through the same tokens they sell. Evaluation of any public allegation belongs outside this course.&lt;/p&gt;

&lt;h2 id=&quot;p7-softmax-gradient-on-a-language-model-head&quot;&gt;P7. Softmax gradient on a language-model head&lt;/h2&gt;

&lt;p&gt;Write \(\partial\mathcal{L}/\partial z\) for token-level CE after softmax. Then say in one sentence what log-sum-exp buys you, and what “online softmax” adds for FlashAttention.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; \(p-t\); running max.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; \(\partial\mathcal{L}/\partial z = p - t\) with \(t\) one-hot. Log-sum-exp subtracts the row max so \(e^{z}\) does not overflow. Online softmax keeps a running max and a running sum (and a running weighted \(V\)) so you can stream tiles without materializing \(L\times L\) (&lt;strong&gt;26-01&lt;/strong&gt;, &lt;strong&gt;26-07&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;p8-name-the-modern-block-then-count&quot;&gt;P8. Name the modern block, then count&lt;/h2&gt;

&lt;p&gt;Draw RMSNorm → causal attention + RoPE → residual → RMSNorm → SwiGLU → residual. Then give the order-of-magnitude forward FLOPs per token and the two terms in inference memory.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; \(2N\); weights + KV.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Forward \(\approx 2 N_{\mathrm{params}}\) FLOPs per token; backward \(\approx 2\times\) that; train \(\approx 6NT\). Inference memory \(\approx\) bytes of weights plus the KV cache, which is linear in cached length and in \(n_{\mathrm{kv}}\) (GQA). Do not invent a parameter count you did not compute from \(d\), \(n_{\mathrm{layers}}\), \(V\).&lt;/p&gt;

&lt;h2 id=&quot;p9-draft-and-verify-vs-distill&quot;&gt;P9. Draft and verify vs distill&lt;/h2&gt;

&lt;p&gt;A teammate says “speculative decoding is how we train the 8B student.” Correct them in four sentences, and write the temperature / top-\(p\) formulas they will still need at decode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Same target law; different \(\theta\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Speculative decoding is a &lt;em&gt;serving&lt;/em&gt; loop: a draft proposes, the target verifies in parallel, accepted tokens follow the target distribution (&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Leviathan et al., 2023&lt;/a&gt;). Distillation trains a new \(\theta\). Sampling: \(p_i^{(T)}\propto e^{z_i/T}\); top-\(p\) keeps the smallest set with cumulative mass \(\ge p\) then renormalizes (&lt;strong&gt;26-04&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;p10-compute-optimal-in-words&quot;&gt;P10. Compute-optimal in words&lt;/h2&gt;

&lt;p&gt;Under a fixed training-FLOP budget \(C \approx 6NT\), what did Kaplan-style advice originally emphasize, and what did Hoffmann et al. (Chinchilla) change? No fitted exponents.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Tokens vs parameters.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Kaplan et al. (2020) found that, on their curves, growing \(N\) faster than \(T\) looked compute-optimal. Hoffmann et al. (2022) re-ran isoFLOP studies and argued many models were undertrained: you should scale &lt;strong&gt;\(N\) and \(T\) together&lt;/strong&gt;. Later products often train &lt;em&gt;past&lt;/em&gt; that point because a smaller \(N\) that read more tokens is cheaper to serve. Cite the papers; do not quote a loss you did not read off a table (&lt;strong&gt;26-07&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;how-to-use-these&quot;&gt;How to use these&lt;/h2&gt;

&lt;p&gt;Speak the answer out loud in 90 seconds, then check the discussion. If you need RL math, open &lt;strong&gt;21-99&lt;/strong&gt;, not this page. If you need classical KD formulas, open &lt;strong&gt;23-01&lt;/strong&gt; and &lt;strong&gt;26-05&lt;/strong&gt;. If you need the decoder diagram or FLOPs, open &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=7xTGNNLPyMI&quot;&gt;Deep Dive into LLMs like ChatGPT&lt;/a&gt; — Andrej Karpathy, English. Before the hub’s interview prompts on what is actually trained and how it is served.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is cross-entropy?&lt;/td&gt;
          &lt;td&gt;Compression is Intelligence Part 2](https://www.youtube.com/watch?v=GlYgs6v2YfU) — 3Blue1Brown, English. Cross-entropy and the softmax gradient, which one prompt asks you to derive.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. The modern block another prompt asks you to name and then count.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-05 Model Distillation for LLMs</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_05_Model_Distillation_for_LLMs/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_05_Model_Distillation_for_LLMs</id>
   <content type="html">&lt;p&gt;Classical knowledge distillation matches a student’s full probability vector to a teacher’s softmax—easy when you have 10 CIFAR classes, painful when your LLM vocabulary has 128,256 tokens and storing full teacher logits for a billion tokens would take half a petabyte of disk! Modern LLM distillation therefore split into three practical regimes: black-box synthetic data (text-in, text-out), white-box top-$k$ / reverse-KL logit distillation, and hidden-state feature alignment—each carrying sharp engineering and legal/licensing boundaries.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-knowledge-distillation-for-large-language-models&quot;&gt;Key ideas: Knowledge Distillation for Large Language Models&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Temperature-Scaled Logit KD &amp;amp; Dark Knowledge&lt;/strong&gt;: Softens teacher probabilities $p_T = \operatorname{softmax}(z_T / \tau)$ so non-target tokens transmit rich semantic similarity signals, scaled by $\tau^2$ to preserve gradient norms.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Forward KL vs. Reverse KL for Generation&lt;/strong&gt;: Contrasts mode-covering forward KL $D_{\text{KL}}(p_T | p_S)$ (which can cause small students to smear mass across low-probability phrases) with mode-seeking reverse KL $D_{\text{KL}}(p_S | p_T)$ (sharp, fluent generations).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Three Modern LLM Distillation Families&lt;/strong&gt;: Organizes synthetic-response SFT (black-box, cheapest, works across mismatched tokenizers), sparse top-$k$ logit KD (white-box, same tokenizer), and intermediate hidden-state matching.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Governance &amp;amp; Terms-of-Service Hygiene&lt;/strong&gt;: Distinguishes legitimate in-house distillation (from your own or permissively licensed open-weight teachers) from unauthorized harvesting of proprietary APIs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-tau2-scaling-is-mandatory-in-temperature-scaled-kd&quot;&gt;Worked example: Why $\tau^2$ Scaling Is Mandatory in Temperature-Scaled KD&lt;/h3&gt;

&lt;p&gt;Consider a 2-class teacher logit vector $z_T = [4.0, 2.0]$ and student logits $z_S = [3.0, 3.0]$ at temperature $\tau = 2.0$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute softened probabilities at $\tau = 2.0$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Teacher $z_T / 2 = [2.0, 1.0] \implies p_T^{(2)} = [\sigma(1.0),\; 1 - \sigma(1.0)] = [0.7311,\; 0.2689]$.&lt;/li&gt;
      &lt;li&gt;Student $z_S / 2 = [1.5, 1.5] \implies p_S^{(2)} = [0.5000,\; 0.5000]$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute KL divergence $D_{\text{KL}}(p_T^{(2)} | p_S^{(2)})$&lt;/strong&gt;:
\(D_{\text{KL}} = 0.7311\ln\frac{0.7311}{0.5} + 0.2689\ln\frac{0.2689}{0.5} = 0.2778 - 0.1668 = 0.1110\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check the gradient on student logit $z_{S,1}$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Unscaled $\frac{\partial D_{\text{KL}}}{\partial z_{S,1}} = \frac{1}{\tau}(p_{S,1}^{(2)} - p_{T,1}^{(2)}) = \frac{1}{2}(0.5000 - 0.7311) = -0.1156$.&lt;/li&gt;
      &lt;li&gt;Notice that because $\frac{\partial (z_S/\tau)}{\partial z_S} = \frac{1}{\tau}$ &lt;em&gt;and&lt;/em&gt; softmax sensitivity shrinks by another factor of $\frac{1}{\tau}$ at high $\tau$, the raw gradient shrinks as $O(1/\tau^2)$!&lt;/li&gt;
      &lt;li&gt;Multiplying the KL loss by $\tau^2 = 4$ restores $\tau^2 \cdot \frac{\partial D_{\text{KL}}}{\partial z_{S,1}} = -0.4622$, keeping KD balanced with the $\tau=1$ hard-label cross-entropy term.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Forgetting the $\tau^2$ multiplier silently weakens distillation by $4\times$ at $\tau=2$ and $16\times$ at $\tau=4$.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;model-distillation-for-llms&quot;&gt;Model Distillation for LLMs&lt;/h1&gt;

&lt;p&gt;Chapter 23 introduced &lt;strong&gt;knowledge distillation (KD)&lt;/strong&gt; as a compression tool: a small student matches a large teacher. That picture still holds. What changes for LLMs is the &lt;em&gt;output space&lt;/em&gt; (a huge token vocabulary, one step at a time) and the &lt;em&gt;interface&lt;/em&gt; you have to the teacher (full weights vs text only).&lt;/p&gt;

&lt;p&gt;This lesson refreshes classical KD, explains why the 2015 recipe is awkward for autoregressive LMs, then presents three modern families in original teaching language. It is &lt;strong&gt;not&lt;/strong&gt; a reprint of any blog or paper.&lt;/p&gt;

&lt;h2 id=&quot;1-classical-kd-refresh-the-chapter-23-core&quot;&gt;1. Classical KD refresh (the Chapter 23 core)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/1503.02531&quot;&gt;Hinton, Vinyals, and Dean, 2015&lt;/a&gt;, &lt;em&gt;Distilling the Knowledge in a Neural Network&lt;/em&gt;, trained a student on the teacher’s &lt;strong&gt;soft&lt;/strong&gt; class distribution, not only on one-hot labels.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why soft targets help.&lt;/strong&gt; A hard label says “this image is class 7.” A trained teacher might say “7 with 0.80, 3 with 0.15, 8 with 0.04, …” Those off-diagonal masses encode &lt;em&gt;which mistakes are reasonable&lt;/em&gt; — similarity structure Hinton et al. called &lt;strong&gt;dark knowledge&lt;/strong&gt;. The student sees a richer gradient than “right vs wrong.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Temperature.&lt;/strong&gt; At \(T = 1\) a confident teacher is nearly one-hot, so the extra signal vanishes. Softmax with temperature&lt;/p&gt;

\[p_i^{(T)} = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}\]

&lt;p&gt;flattens the distribution as \(T &amp;gt; 1\) grows. The student matches \(p_{\mathrm{teacher}}^{(T)}\) (typically with a KL divergence) and often still matches the hard label. A common blend is&lt;/p&gt;

\[\mathcal{L} = \alpha\, T^{2}\, \mathrm{KL}\big(p_{\mathrm{teacher}}^{(T)} \,\|\, p_{\mathrm{student}}^{(T)}\big) + (1-\alpha)\,\mathrm{CE}(y, z_{\mathrm{student}}).\]

&lt;p&gt;The \(T^{2}\) factor keeps gradient scale from collapsing as you raise \(T\) (see the 2015 note and the Chapter 23 snippet). \(\alpha\) trades “imitate the teacher” against “hit the dataset label.”&lt;/p&gt;

&lt;p&gt;That is the right first model for &lt;strong&gt;fixed-\(K\) classification&lt;/strong&gt; (ImageNet, speech senones, a 10-way head). Review &lt;strong&gt;23-01&lt;/strong&gt; if this paragraph is new.&lt;/p&gt;

&lt;h2 id=&quot;2-why-classical-logit-kd-is-awkward-for-huge-vocabulary-lms&quot;&gt;2. Why classical logit KD is awkward for huge-vocabulary LMs&lt;/h2&gt;

&lt;p&gt;A decoder LM is a classifier &lt;em&gt;at every position&lt;/em&gt;, with \(K = V\) in the tens or hundreds of thousands, and the “example” is a &lt;em&gt;sequence&lt;/em&gt; of such decisions.&lt;/p&gt;

&lt;p&gt;Practical friction:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cost.&lt;/strong&gt; Storing or streaming a full teacher distribution per token is \(O(V)\) extra memory and I/O. For long sequences that dominates the student’s own logits.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sparsity.&lt;/strong&gt; After a small \(T\), almost all of the \(V\) mass sits on a handful of tokens. You are paying to match near-zeros unless you truncate to a top-\(k\) or a sample.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exposure.&lt;/strong&gt; Training on teacher logits usually needs a &lt;strong&gt;white-box&lt;/strong&gt; (or at least logit-exposing) teacher. Public chat APIs typically return &lt;em&gt;text&lt;/em&gt;, maybe a few logprobs, not a \(V\)-vector per step.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sequence, not i.i.d. images.&lt;/strong&gt; Error compounds along the rollout. Matching a teacher &lt;em&gt;token distribution given the teacher’s prefix&lt;/em&gt; is not the same as matching the teacher’s &lt;em&gt;completed answers&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;So teams still use logit KD &lt;strong&gt;in house&lt;/strong&gt; when they own both models (and often restrict it to top-\(k\) or selected positions). They do not treat the 2015 formula as a drop-in for “make a cheap clone of a closed API model.”&lt;/p&gt;

&lt;h2 id=&quot;3-three-modern-families-original-grouping&quot;&gt;3. Three modern families (original grouping)&lt;/h2&gt;

&lt;p&gt;Names vary across papers. Group by &lt;strong&gt;what the student is asked to match&lt;/strong&gt; and &lt;strong&gt;what access you need&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;31-synthetic-data--response-distillation-text-in-text-out&quot;&gt;3.1 Synthetic-data / response distillation (text in, text out)&lt;/h3&gt;

&lt;p&gt;The teacher generates completions — answers, step-by-step rationales, code, rewritten documents. You store &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(prompt, teacher_text)&lt;/code&gt; and train the student with ordinary next-token SFT on that text (sometimes mixed with human data).&lt;/p&gt;

&lt;p&gt;This is the dominant &lt;strong&gt;black-box&lt;/strong&gt; pattern: you only need samples from the teacher, not \(z\) or hidden states. Instruction-following clones of the early 2020s (research projects that fine-tuned small LMs on outputs of a stronger chat model) are this family. Later work asks the teacher for &lt;em&gt;rationales&lt;/em&gt; and trains the student to produce the reasoning tokens as well as the answer, so the student gets a longer, more structured target than a short final string.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What transfers.&lt;/strong&gt; Surface behavior and, if the prompts cover the task, some of the teacher’s &lt;em&gt;decisions&lt;/em&gt;. &lt;strong&gt;What does not automatically transfer.&lt;/strong&gt; Calibration of the full \(p(\cdot\mid x_{&amp;lt;t})\), internal features, or capabilities the prompt set never elicited.&lt;/p&gt;

&lt;p&gt;Because the student only sees sampled strings, two teacher samples for the same prompt can disagree. Dataset design (temperature, filtering, mixing real labels) matters as much as the loss.&lt;/p&gt;

&lt;h3 id=&quot;32-feature--hidden-state-distillation-white-box&quot;&gt;3.2 Feature / hidden-state distillation (white-box)&lt;/h3&gt;

&lt;p&gt;The student matches intermediate activations: hidden states, attention maps, or a projection of the teacher’s residual stream. This needs &lt;strong&gt;aligned depths or learned adapters&lt;/strong&gt; and access to teacher internals. It is the LM analogue of hint losses used in vision KD.&lt;/p&gt;

&lt;p&gt;Use it when you control the teacher checkpoint and want the student to share &lt;em&gt;representational geometry&lt;/em&gt;, not only final strings. It is a poor fit for an API you cannot instrument.&lt;/p&gt;

&lt;h3 id=&quot;33-logit--token-distribution-distillation-white-box&quot;&gt;3.3 Logit / token-distribution distillation (white-box)&lt;/h3&gt;

&lt;p&gt;Apply the 2015 idea at each position: match \(p_{\mathrm{teacher}}(\cdot \mid x_{&amp;lt;t})\) and \(p_{\mathrm{student}}(\cdot \mid x_{&amp;lt;t})\), usually with temperature and often with a reverse-KL or top-\(k\) variant so the student does not waste capacity on the tail. &lt;a href=&quot;https://arxiv.org/abs/1910.01108&quot;&gt;Sanh et al., 2019&lt;/a&gt; (DistilBERT) is the classic &lt;em&gt;encoder&lt;/em&gt; example; generative LM papers explore related losses under names such as MiniLLM (&lt;a href=&quot;https://arxiv.org/abs/2306.08543&quot;&gt;Gu et al., 2024&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;This is the most faithful &lt;em&gt;distributional&lt;/em&gt; copy, and the most demanding: same (or mapped) tokenizer, stored or on-the-fly teacher logits, and usually the same prefixing policy.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Family&lt;/th&gt;
      &lt;th&gt;Student target&lt;/th&gt;
      &lt;th&gt;Teacher access&lt;/th&gt;
      &lt;th&gt;Typical use&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Response / synthetic data&lt;/td&gt;
      &lt;td&gt;Teacher &lt;em&gt;text&lt;/em&gt; (and optional rationales)&lt;/td&gt;
      &lt;td&gt;Samples only&lt;/td&gt;
      &lt;td&gt;Open teachers, product SFT sets, most public recipes&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Feature / hidden state&lt;/td&gt;
      &lt;td&gt;Layer activations&lt;/td&gt;
      &lt;td&gt;White-box&lt;/td&gt;
      &lt;td&gt;In-house, related architectures&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Logit / token distribution&lt;/td&gt;
      &lt;td&gt;Softmax over \(V\)&lt;/td&gt;
      &lt;td&gt;White-box (or full logprobs)&lt;/td&gt;
      &lt;td&gt;In-house, same tokenizer&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Many production pipelines &lt;strong&gt;mix&lt;/strong&gt; them: generate a synthetic SFT set, then add a cheap logit term on a subset of tokens if both models run locally.&lt;/p&gt;

&lt;h2 id=&quot;4-legitimate-in-house-use-vs-unauthorized-harvesting&quot;&gt;4. Legitimate in-house use vs unauthorized harvesting&lt;/h2&gt;

&lt;p&gt;Distillation is ordinary engineering when you &lt;strong&gt;have the right to train on the teacher’s outputs or weights&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;shrinking your own frontier model into a faster tier (mobile, batch, on-prem),&lt;/li&gt;
  &lt;li&gt;following an &lt;strong&gt;open license&lt;/strong&gt; that lists distillation or synthetic data as an intended use (several large open checkpoints have been released with that story),&lt;/li&gt;
  &lt;li&gt;research on public models whose terms allow it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The structural tension is not a mystery about any one company. &lt;strong&gt;A model that is useful through an API emits text that is also a training signal.&lt;/strong&gt; Providers therefore put &lt;strong&gt;terms of service&lt;/strong&gt; and technical controls (rate limits, abuse detection) around using outputs to build a competing model. That is a contract and product-integrity issue: capability leaks through the same channel you opened for customers.&lt;/p&gt;

&lt;p&gt;This course does &lt;strong&gt;not&lt;/strong&gt; recap news-cycle allegations, lawsuit claims, or unverified incident counts. Those change quickly and are easy to get wrong. If you need the industry debate as extra reading, use a tutorial that frames the &lt;em&gt;engineering&lt;/em&gt; first — for example Machine Learning Mastery’s &lt;a href=&quot;https://machinelearningmastery.com/a-gentle-introduction-to-model-distillation/&quot;&gt;A Gentle Introduction to Model Distillation&lt;/a&gt; (Chugani, 2026) — and treat any controversy section as &lt;strong&gt;reporting to verify&lt;/strong&gt;, not as a primary source.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Self-study rule.&lt;/strong&gt; If you do not own the teacher and the terms forbid training on outputs, do not build a distillation set from that API. Use an openly licensed teacher, your own model, or public datasets.&lt;/p&gt;

&lt;h2 id=&quot;5-tiny-code-sketches&quot;&gt;5. Tiny code sketches&lt;/h2&gt;

&lt;h3 id=&quot;51-temperature-scaled-kd-for-a-fixed-classifier&quot;&gt;5.1 Temperature-scaled KD for a &lt;em&gt;fixed&lt;/em&gt; classifier&lt;/h3&gt;

&lt;p&gt;This is the Chapter 23 setting, written so the \(T^{2}\) and KL direction are explicit. It is &lt;strong&gt;not&lt;/strong&gt; a full LM trainer.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;classification_kd_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;teacher_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                           &lt;span class=&quot;n&quot;&gt;temperature&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;4.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Soft-target KD for a shared, small class set.

    student_logits, teacher_logits: (batch, num_classes)
    labels: (batch,) integer class ids
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temperature&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;hard&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;log_p_s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;p_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;teacher_logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# KL(teacher || student); T^2 restores gradient scale as T grows
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;soft&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;kl_div&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_p_s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reduction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;batchmean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;soft&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hard&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;To imagine the LM analogue, think of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;num_classes = vocab_size&lt;/code&gt; and a loop over time, with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ignore_index&lt;/code&gt; on padding — and then remember why people switch to top-\(k\) or to text SFT instead.&lt;/p&gt;

&lt;h3 id=&quot;52-response-distillation-is-a-fine-tune-dataset&quot;&gt;5.2 Response distillation &lt;em&gt;is&lt;/em&gt; a fine-tune dataset&lt;/h3&gt;

&lt;p&gt;No new loss is required. You build rows the student will see as ordinary instruction data:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Each row is teacher-generated text the student should assign high likelihood to.
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sft_rows&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;prompt&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Give a one-paragraph intuition for dropout.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;completion&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dropout randomly masks units at train time so ...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;prompt&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Now show a tiny numeric example.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;completion&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Suppose a hidden layer has four units and p=0.5 ...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Train with next-token CE on `completion` (and the chat template), same as 26-01 / 26-02.
# Optional: keep a human-written subset so the student does not only copy teacher quirks.
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If the teacher also wrote a rationale, store it &lt;em&gt;inside&lt;/em&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;completion&lt;/code&gt; (or as a second field you concatenate). The student is still doing SFT; the novelty is &lt;strong&gt;who wrote the targets&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;6-further-reading&quot;&gt;6. Further reading&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Hinton, G., Vinyals, O., and Dean, J. (2015). &lt;a href=&quot;https://arxiv.org/abs/1503.02531&quot;&gt;Distilling the Knowledge in a Neural Network&lt;/a&gt;. Historical source for soft targets, temperature, and dark knowledge.&lt;/li&gt;
  &lt;li&gt;Machine Learning Mastery — &lt;a href=&quot;https://machinelearningmastery.com/a-gentle-introduction-to-model-distillation/&quot;&gt;A Gentle Introduction to Model Distillation&lt;/a&gt; (Chugani, 2026). Extra tutorial framing of classical vs LLM-era families; &lt;strong&gt;cited as further reading, not copied here&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;This course: &lt;strong&gt;23-01 Model Compression&lt;/strong&gt; (pruning, quantization, classical KD) and &lt;strong&gt;23-99&lt;/strong&gt; (GPTQ / AWQ / speculative decoding — complementary, not a substitute for a student). Serving-time draft-and-verify is also in &lt;strong&gt;26-04&lt;/strong&gt;; FLOP / memory accounting before you pick a student size is in &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Optional technical pointers (not assigned): DistilBERT (&lt;a href=&quot;https://arxiv.org/abs/1910.01108&quot;&gt;Sanh et al., 2019&lt;/a&gt;); rationale-style distillation such as Distilling Step-by-Step (&lt;a href=&quot;https://arxiv.org/abs/2305.02301&quot;&gt;Hsieh et al., 2023&lt;/a&gt;); MiniLLM (&lt;a href=&quot;https://arxiv.org/abs/2306.08543&quot;&gt;Gu et al., 2024&lt;/a&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key takeaways&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Classical KD = match a teacher’s &lt;em&gt;soft class distribution&lt;/em&gt;; temperature reveals dark knowledge.&lt;/li&gt;
  &lt;li&gt;Autoregressive LMs make full-logit matching expensive and often inaccessible.&lt;/li&gt;
  &lt;li&gt;Modern practice clusters into &lt;strong&gt;response (synthetic)&lt;/strong&gt;, &lt;strong&gt;feature&lt;/strong&gt;, and &lt;strong&gt;logit&lt;/strong&gt; distillation.&lt;/li&gt;
  &lt;li&gt;In-house / licensed distillation is standard efficiency work; training on a forbidden API is a terms-and-leakage problem, not a new algorithm.&lt;/li&gt;
  &lt;li&gt;A temperature-scaled KL is the right &lt;em&gt;picture&lt;/em&gt;; a teacher-written SFT file is what most LLM students actually train on.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=jrJKRYAdh7I&quot;&gt;Knowledge Distillation: How LLMs train each other&lt;/a&gt; — Julia Turc, English. How a large language model teaches a smaller one, which is this lesson’s modern half.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[2.3 Knowledge Distillation&lt;/td&gt;
          &lt;td&gt;Geoffery Hinton&lt;/td&gt;
          &lt;td&gt;Soft Labels&lt;/td&gt;
          &lt;td&gt;Softmax with Temperature](https://www.youtube.com/watch?v=g1r4Esohw-g) — AI_Snippets, English. Classical soft-label distillation and the temperature, the Chapter 23 refresh.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, English. Why matching a full vocabulary distribution is expensive, the lesson’s objection to naive logit KD.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-04 Serving and Efficiency for LLMs</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_04_Serving_and_Efficiency/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_04_Serving_and_Efficiency</id>
   <content type="html">&lt;p&gt;You can pay $2 million once to train an LLM, and then pay $20 million every year to serve it to users. Serving efficiency is governed by a stark hardware split: &lt;strong&gt;prefill&lt;/strong&gt; processes your entire prompt in one giant parallel matrix–matrix multiplication (compute-bound, sets Time-To-First-Token), while &lt;strong&gt;decode&lt;/strong&gt; generates one token at a time using matrix–vector multiplications that haul the entire model + KV cache across GPU HBM every step (memory-bandwidth-bound, sets tokens/second). Every serving knob—continuous batching, PagedAttention, quantization, and speculative decoding—directly attacks one side of that roofline.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-systems-engineering-of-llm-serving&quot;&gt;Key ideas: Systems Engineering of LLM Serving&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Prefill vs. Decode Roofline Physics&lt;/strong&gt;: Computes arithmetic intensity (FLOPs / Byte) to explain why batch-size-1 decode leaves $&amp;gt;95\%$ of GPU Tensor Cores idle waiting on HBM memory bandwidth.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Continuous Batching &amp;amp; PagedAttention&lt;/strong&gt;: Eliminates padding waste by inserting new requests at iteration boundaries and allocating KV cache in non-contiguous memory pages (like OS virtual memory) to boost throughput $3\times$–$10\times$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Sampling Controls (Temperature, Top-$k$, Top-$p$)&lt;/strong&gt;: Reshapes the output softmax distribution at decode time to trade deterministic precision against creative diversity.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Optimization Hierarchy (Before Distilling)&lt;/strong&gt;: Prioritizes cheap, lossless or near-lossless serving wins (prefix caching, FP8/INT4 quantization, speculative decoding) before investing in full model distillation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-applying-temperature-top-k-and-nucleus-top-p-sampling&quot;&gt;Worked example: Applying Temperature, Top-$k$, and Nucleus (Top-$p$) Sampling&lt;/h3&gt;

&lt;p&gt;Suppose the LM head emits logits $z = [3.0,\; 2.0,\; 1.0,\; -1.0]$ for four candidate tokens &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[A, B, C, D]&lt;/code&gt;.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standard softmax at $T = 1.0$&lt;/strong&gt;:
\(e^3 = 20.09,\quad e^2 = 7.39,\quad e^1 = 2.72,\quad e^{-1} = 0.37 \implies Z = 30.57.\)
\(p = [65.7\%,\; 24.2\%,\; 8.9\%,\; 1.2\%].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply Nucleus (Top-$p$) with $p_{\text{thresh}} = 0.85$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Cumulative mass: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt; ($65.7\% &amp;lt; 85\%$), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A + B&lt;/code&gt; ($65.7\% + 24.2\% = 89.9\% \ge 85\%$).&lt;/li&gt;
      &lt;li&gt;Keep only &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{A, B}&lt;/code&gt; and drop &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{C, D}&lt;/code&gt;!&lt;/li&gt;
      &lt;li&gt;Renormalized probabilities: $p’(A) = \frac{65.7}{89.9} = 73.1\%$, $\; p’(B) = \frac{24.2}{89.9} = 26.9\%$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare with low temperature $T = 0.5$&lt;/strong&gt; (scaled logits $[6.0, 4.0, 2.0, -2.0]$):
$e^6 / (e^6 + e^4 + e^2 + e^{-2}) = 403.4 / 465.4 = 86.7\%$ on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;A&lt;/code&gt;—sharpening the distribution dramatically.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Top-$p$ dynamically adapts candidate count (keeping 1 token when the model is confident, 10+ when genuinely open-ended), whereas temperature globally sharpens or flattens every step.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;serving-and-efficiency-for-llms&quot;&gt;Serving and Efficiency for LLMs&lt;/h1&gt;

&lt;p&gt;A pretrained, instructed, aligned decoder is still expensive &lt;strong&gt;per generated token&lt;/strong&gt;. Training is a one-off (or rare) bill; serving is the bill that scales with users. This lesson lists the knobs you should name before you reach for distillation.&lt;/p&gt;

&lt;p&gt;The compression math — quantization grids, pruning scores, classical KD — stays in &lt;strong&gt;Chapter 23&lt;/strong&gt;. The LLM-specific recipes (GPTQ, AWQ, GGUF, speculative decoding) are in &lt;strong&gt;23-99&lt;/strong&gt;. Here we only answer: &lt;em&gt;what is expensive at decode time, and when is a smaller student the right next step?&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-prefill-vs-decode&quot;&gt;1. Prefill vs decode&lt;/h2&gt;

&lt;p&gt;Autoregressive generation has two phases:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prefill.&lt;/strong&gt; The full prompt (system + history + user + retrieved text) is consumed in parallel. You pay attention over the prompt length once and write a &lt;strong&gt;KV-cache&lt;/strong&gt;: for each layer and each prompt token, store the key and value vectors.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Decode.&lt;/strong&gt; You emit one new token at a time. Without a cache you would recompute attention from scratch on the growing prefix (roughly \(O(t^2)\) work by step \(t\)). With a cache you append one new \(k,v\) and attend against the stored prefix — about \(O(t)\) attention work per new token, plus the MLP.&lt;/p&gt;

&lt;p&gt;That is the same KV-cache already named in &lt;strong&gt;08-99&lt;/strong&gt;. Serving systems (vLLM, SGLang, llama.cpp) are mostly: &lt;em&gt;manage many caches, batch the matrix multiplies, and overlap I/O&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Memory, not just FLOPs, often dominates. The cache for a long conversation is&lt;/p&gt;

\[\mathrm{bytes} \approx 2 \cdot L \cdot n_{\mathrm{layers}} \cdot n_{\mathrm{kv\_heads}} \cdot d_{\mathrm{head}} \cdot b\]

&lt;p&gt;(the factor 2 is keys and values; \(b\) is bytes per element; grouped-query attention shrinks \(n_{\mathrm{kv\_heads}}\)). This is why long context is a &lt;strong&gt;product&lt;/strong&gt; decision, not only a quality decision.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  prefill[&quot;Prefill prompt&quot;] --&amp;gt; kv[&quot;Write K,V for every prompt token&quot;]
  kv --&amp;gt; d1[&quot;Decode token t&quot;]
  d1 --&amp;gt; app[&quot;Append one new K,V&quot;]
  app --&amp;gt; d2[&quot;Decode token t+1&quot;]
  d2 --&amp;gt; lin[&quot;Cache length grows as O of n&quot;]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;GQA / MQA (&lt;strong&gt;26-07&lt;/strong&gt;, &lt;strong&gt;07-99&lt;/strong&gt;) shrink \(n_{\mathrm{kv\_heads}}\). FlashAttention does &lt;strong&gt;not&lt;/strong&gt; shrink the cache; it shrinks the IO of computing attention against that cache (tiling + online softmax, &lt;strong&gt;26-01&lt;/strong&gt; / &lt;strong&gt;26-07&lt;/strong&gt;). Order-of-magnitude training FLOPs and the “weights + KV” memory identity are in &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;2-batching-and-packing&quot;&gt;2. Batching and packing&lt;/h2&gt;

&lt;p&gt;A single decode step is a skinny matmul: batch 1, sequence 1, huge weights. GPUs want fat matmuls. &lt;strong&gt;Continuous batching&lt;/strong&gt; (iteration-level scheduling; the vLLM picture) keeps the device busy by admitting a new request when another request finishes a sequence, instead of waiting for a static batch to complete. &lt;strong&gt;Sequence packing&lt;/strong&gt; is the training-time cousin: concatenate short documents inside one window and mask so tokens do not attend across a document boundary. Same idea — do not pay for padding you will ignore.&lt;/p&gt;

&lt;p&gt;Prefill of a shared system prompt can be computed once and &lt;strong&gt;prefix-cached&lt;/strong&gt;. That is batching in time rather than across users.&lt;/p&gt;

&lt;h2 id=&quot;3-sampling-temperature-top-k-top-p&quot;&gt;3. Sampling: temperature, top-\(k\), top-\(p\)&lt;/h2&gt;

&lt;p&gt;Decode is not always \(\arg\max\). Given logits \(z\),&lt;/p&gt;

\[p_i^{(T)} = \frac{\exp(z_i / T)}{\sum_j \exp(z_j / T)}.\]

&lt;p&gt;\(T \to 0\) is greedy; \(T = 1\) is the trained distribution; \(T &amp;gt; 1\) flattens (more surprise, more breakage). &lt;strong&gt;Top-\(k\)&lt;/strong&gt; zeroes every logit outside the \(k\) largest, then renormalizes. &lt;strong&gt;Nucleus / top-\(p\)&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/1904.09751&quot;&gt;Holtzman et al., 2020&lt;/a&gt;) keeps the &lt;em&gt;smallest&lt;/em&gt; set of tokens whose cumulative probability is at least \(p\), then renormalizes. Temperature changes &lt;em&gt;shape&lt;/em&gt;; top-\(k\) / top-\(p\) change &lt;em&gt;support&lt;/em&gt;. They compose: scale by \(T\), truncate, then sample.&lt;/p&gt;

&lt;p&gt;Do not confuse this \(T\) with the distillation temperature in &lt;strong&gt;26-05&lt;/strong&gt;. Same algebra; different job (decode diversity vs soft teacher).&lt;/p&gt;

&lt;h2 id=&quot;4-speculative-decoding-draft--verify&quot;&gt;4. Speculative decoding (draft + verify)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Leviathan et al., 2023&lt;/a&gt; (and parallel work) use a cheap &lt;strong&gt;draft&lt;/strong&gt; model to propose several tokens; the large &lt;strong&gt;target&lt;/strong&gt; verifies that prefix in one parallel forward. Tokens the target would have sampled are accepted; at the first disagreement you resample from the &lt;em&gt;adjusted&lt;/em&gt; target distribution and drop the rest of the draft. Implemented correctly, the output law is the target’s, not the draft’s. You spend extra draft FLOPs to buy target forwards.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;sequenceDiagram
  participant Draft as Draft model
  participant Target as Target model
  Draft-&amp;gt;&amp;gt;Draft: Propose k tokens
  Draft-&amp;gt;&amp;gt;Target: Hand over the draft prefix
  Target-&amp;gt;&amp;gt;Target: Parallel verify of the prefix
  Target-&amp;gt;&amp;gt;Draft: Accept a prefix plus one resample
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is a &lt;em&gt;serving&lt;/em&gt; trick, not a new trained student. If you need a smaller architecture, that is distillation (&lt;strong&gt;26-05&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;5-quantization-is-the-first-cheap-win&quot;&gt;5. Quantization is the first cheap win&lt;/h2&gt;

&lt;p&gt;Storing weights in 16-bit instead of 32-bit, then 8-bit or 4-bit, cuts memory and can cut bandwidth-bound decode time. Chapter 23 gives the rounding picture; &lt;strong&gt;23-99&lt;/strong&gt; names GPTQ / AWQ / GGUF as the recipes people actually run on 7B–70B decoders.&lt;/p&gt;

&lt;p&gt;Quantization &lt;strong&gt;does not&lt;/strong&gt; train a new model. It approximates the same \(\theta\) with fewer bits. Use it when:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;you own or may redistribute that checkpoint,&lt;/li&gt;
  &lt;li&gt;quality drop is acceptable after a quick eval,&lt;/li&gt;
  &lt;li&gt;you need the &lt;em&gt;same&lt;/em&gt; behavior at lower RAM (laptops, a single GPU, edge).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If 4-bit still misses a latency or cost target, you need fewer layers/width or fewer active parameters (MoE routing — also in 23-99) — or a &lt;strong&gt;student&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;6-other-serving-levers-so-you-do-not-overfit-on-distillation&quot;&gt;6. Other serving levers (so you do not overfit on distillation)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Prompt caching / prefix sharing.&lt;/strong&gt; Many requests share a system prompt; reuse that prefill (section 2).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Retrieval vs long context.&lt;/strong&gt; Stuffing a book into \(L\) is often slower and worse than retrieving (18-99).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adapters (LoRA / QLoRA).&lt;/strong&gt; Specialize without serving a full extra copy of every expert (Chapter 15 optional).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Accounting.&lt;/strong&gt; If you need \(N\), activation size, or \(C \approx 6NT\), open &lt;strong&gt;26-07&lt;/strong&gt; rather than guessing.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;None of these &lt;em&gt;transfer knowledge into a smaller architecture&lt;/em&gt;. They make the teacher cheaper to run.&lt;/p&gt;

&lt;h2 id=&quot;7-when-to-distill&quot;&gt;7. When to distill&lt;/h2&gt;

&lt;p&gt;Reach for distillation (&lt;strong&gt;26-05&lt;/strong&gt;) when at least one of these is true:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Architecture must shrink.&lt;/strong&gt; Quantization cannot delete layers. A 70B teacher that must become a 7–8B (or a mobile) student needs a new \(\theta\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;You want a cheaper product tier&lt;/strong&gt; with similar &lt;em&gt;behavior&lt;/em&gt;, not a bit-exact clone — in-house, on a teacher you are allowed to train from.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;You will fine-tune many specialists.&lt;/strong&gt; Distill a general student once, then LoRA each specialist.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;White-box internals are available&lt;/strong&gt; and you care about matching hidden states or token distributions, not only text.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Do &lt;strong&gt;not&lt;/strong&gt; distill first if you have not tried 4-bit weights, a sane context limit, and batching. Distillation is a training project; quantization is often a conversion flag.&lt;/p&gt;

&lt;p&gt;Also do not distill a teacher you are not licensed or contracted to train from. The next lesson separates ordinary in-house / open-license distillation from harvesting an API you do not control.&lt;/p&gt;

&lt;h2 id=&quot;further-reading&quot;&gt;Further reading&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Leviathan et al., 2023. &lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Fast Inference from Transformers via Speculative Decoding&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Holtzman et al., 2020. &lt;a href=&quot;https://arxiv.org/abs/1904.09751&quot;&gt;The Curious Case of Neural Text Degeneration&lt;/a&gt; (nucleus sampling).&lt;/li&gt;
  &lt;li&gt;Kwon et al., 2023. &lt;a href=&quot;https://arxiv.org/abs/2309.06180&quot;&gt;Efficient Memory Management for Large Language Model Serving with PagedAttention&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Topic-map inspiration (not quoted): &lt;a href=&quot;https://alisawuffles.notion.site/alisa-s-book-of-llms&quot;&gt;Alisa’s Book of LLMs&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key takeaways&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Decode cost = MLP + attending over a growing &lt;strong&gt;KV-cache&lt;/strong&gt; (\(O(n)\) memory in the cached length).&lt;/li&gt;
  &lt;li&gt;Continuous batching / packing fill the GPU; speculative decoding is draft + parallel verify.&lt;/li&gt;
  &lt;li&gt;Temperature reshapes \(p\); top-\(k\) / top-\(p\) cut support. Same \(T\) algebra as KD, different job.&lt;/li&gt;
  &lt;li&gt;Quantization and batching are the default efficiency tools (Chapter 23 / 23-99).&lt;/li&gt;
  &lt;li&gt;Distillation is the tool for a &lt;em&gt;new, smaller&lt;/em&gt; network that &lt;em&gt;imitates&lt;/em&gt; a teacher.&lt;/li&gt;
  &lt;li&gt;Decide “cache / quantize / retrieve” before “train a student.”&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=VkWlLSTdHs8&quot;&gt;Faster LLMs: Accelerate Inference with Speculative Decoding&lt;/a&gt; — IBM Technology, English. Speculative decoding is the draft-and-verify speedup this lesson explains.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, English. Quantization, the lesson’s first cheap serving win.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, English. Temperature sampling is implemented in this build; the lesson contrasts it with top-k and top-p. The video is long; the sampling section is the relevant part.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-03 Alignment: SFT to Preference Optimization</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_03_Alignment_SFT_to_Preference/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_03_Alignment_SFT_to_Preference</id>
   <content type="html">&lt;p&gt;Pretraining on the open internet teaches an LLM to imitate everything humanity has ever written—textbooks and conspiracy forums alike. Supervised Fine-Tuning (SFT) teaches it the &lt;em&gt;format&lt;/em&gt; of a helpful assistant, yet SFT alone still struggles to distinguish a subtly hallucinated answer from a careful, honest one because both look fluent under cross-entropy. Preference alignment (RLHF, DPO, GRPO) adds the crucial comparative signal: given two fluent responses to the exact same prompt, push up the probability of the better one while anchoring to the reference model with a KL leash.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-three-stage-llm-post-training-pipeline&quot;&gt;Key ideas: The Three-Stage LLM Post-Training Pipeline&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Supervised Fine-Tuning (SFT) &amp;amp; Loss Masking&lt;/strong&gt;: Fine-tunes on high-quality &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(prompt, response)&lt;/code&gt; dialogues while masking loss on prompt tokens (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;label = -100&lt;/code&gt;) so gradients train only assistant completions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Bradley–Terry Reward Modeling&lt;/strong&gt;: Converts pairwise human rankings $(y_w \succ y_l \mid x)$ into a scalar reward function via $\mathcal{L}&lt;em&gt;{\text{RM}} = -\mathbb{E}[\log\sigma(r&lt;/em&gt;\phi(x, y_w) - r_\phi(x, y_l))]$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — KL-Regularized Preference Optimization (PPO vs. DPO)&lt;/strong&gt;: Optimizes expected preference while penalizing $\beta D_{\text{KL}}(\pi_\theta | \pi_{\text{ref}})$ to prevent reward hacking, verbosity inflation, and mode collapse.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Scope &amp;amp; Limits of Alignment&lt;/strong&gt;: Distinguishes behavioral shaping (tone, refusal, helpfulness) from factual grounding—alignment cannot invent knowledge absent from pretraining or retrieval.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-bradleyterry-reward-loss--kl-penalized-objective&quot;&gt;Worked example: Bradley–Terry Reward Loss &amp;amp; KL-Penalized Objective&lt;/h3&gt;

&lt;p&gt;Suppose for prompt $x$, a reward model scores the preferred answer $r(x, y_w) = 2.5$ and the rejected answer $r(x, y_l) = 1.5$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Reward margin &amp;amp; Bradley–Terry probability&lt;/strong&gt;:
\(\Delta r = 2.5 - 1.5 = +1.0 \implies P(y_w \succ y_l) = \sigma(1.0) = \frac{1}{1 + e^{-1}} \approx 0.7311.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Reward Model training loss&lt;/strong&gt;:
\(\mathcal{L}_{\text{RM}} = -\ln(0.7311) \approx 0.3133\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;KL-penalized RLHF net reward&lt;/strong&gt; with $\beta = 0.05$:
Suppose our updated policy $\pi_\theta$ generates a response with reward $r = 3.2$, summed log-prob $\log \pi_\theta(y \mid x) = -12.0$, and reference log-prob $\log \pi_{\text{ref}}(y \mid x) = -22.0$ (so token-level KL proxy $\log\frac{\pi_\theta}{\pi_{\text{ref}}} = +10.0$).
\(R_{\text{total}} = r - \beta\log\frac{\pi_\theta(y \mid x)}{\pi_{\text{ref}}(y \mid x)} = 3.2 - 0.05(10.0) = 3.2 - 0.5 = 2.7.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Even if the policy finds a strange phrasing that bumps raw reward from $2.5$ to $3.2$, drifting too far from $\pi_{\text{ref}}$ triggers a KL tax that keeps language natural and grounded.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;alignment-sft-to-preference-optimization&quot;&gt;Alignment: SFT to Preference Optimization&lt;/h1&gt;

&lt;p&gt;Pretraining teaches &lt;em&gt;what text looks like&lt;/em&gt;. SFT teaches &lt;em&gt;how to answer a request&lt;/em&gt;. &lt;strong&gt;Alignment&lt;/strong&gt; here means a further step: among many fluent answers, prefer the ones a rater (human or AI) would rank higher — helpful, harmless, honest enough for the product.&lt;/p&gt;

&lt;p&gt;This lesson is a &lt;strong&gt;map&lt;/strong&gt;, not a second RL course. The MDP, advantage, and PPO math live in Chapters 20–21; the 2022–2026 product stack is in &lt;strong&gt;21-99&lt;/strong&gt;. Read those if you need derivations. Here we only place the stages in the LLM pipeline.&lt;/p&gt;

&lt;h2 id=&quot;1-the-usual-three-stage-picture&quot;&gt;1. The usual three-stage picture&lt;/h2&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;pretrained LM  →  SFT (demonstrations)  →  preference optimization
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Stage A — SFT.&lt;/strong&gt; Collect (prompt, demonstration) pairs. Minimize next-token loss on the demonstration tokens. You already met this in &lt;strong&gt;26-02&lt;/strong&gt;. SFT is ordinary supervised learning on a curated distribution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stage B — a preference model (classic RLHF).&lt;/strong&gt; Collect pairs \((y_w, y_l)\) for the same prompt: a &lt;em&gt;winner&lt;/em&gt; and a &lt;em&gt;loser&lt;/em&gt;. Train a reward model \(r_\phi\) so that \(r_\phi(x, y_w) &amp;gt; r_\phi(x, y_l)\), typically with a Bradley–Terry / logistic loss. Then treat the LM as a policy \(\pi_\theta\) that emits tokens (actions) and optimize expected reward with a &lt;strong&gt;KL penalty&lt;/strong&gt; toward the SFT reference, so the policy does not wander into gibberish that fools \(r_\phi\).&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Ouyang et al., 2022&lt;/a&gt; (InstructGPT) popularized this loop with PPO. Chapter 21 already has actor–critic; &lt;strong&gt;21-99&lt;/strong&gt; writes the LM version.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stage C — preference optimization without a sampling loop.&lt;/strong&gt; &lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Rafailov et al., 2023&lt;/a&gt; (DPO) rewrite the constrained RL optimum as a classification loss on the same pairs \((y_w, y_l)\), comparing \(\pi_\theta\) to a frozen reference \(\pi_{\mathrm{ref}}\). No reward model and no PPO sampler at train time. Open-source stacks (for example &lt;a href=&quot;https://github.com/huggingface/trl&quot;&gt;trl&lt;/a&gt;) made this the default recipe for many 2024–2025 instruct models.&lt;/p&gt;

&lt;p&gt;The next section writes the &lt;strong&gt;high-level objectives&lt;/strong&gt; so you can read a paper abstract. You do &lt;strong&gt;not&lt;/strong&gt; need to re-derive DPO here. Remember the contract:&lt;/p&gt;

\[\text{SFT fixes the support (what kind of answers exist); preferences reweight that support.}\]

&lt;p&gt;If SFT data never show refusals, citations, or tool calls, preference training cannot invent those skills from a scalar “better/worse” alone.&lt;/p&gt;

&lt;h2 id=&quot;2-objectives-you-should-be-able-to-write-not-obscure-variants&quot;&gt;2. Objectives you should be able to write (not obscure variants)&lt;/h2&gt;

&lt;p&gt;Treat the LM as a policy \(\pi_\theta(y\mid x)\) that emits a token sequence \(y\) given prompt \(x\). Full PPO / advantage math stays in Chapters 20–21; &lt;strong&gt;21-99&lt;/strong&gt; is the LM-shaped recap. We omit named cousins (IPO, KTO, ORPO, …) unless you open those papers yourself.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Policy gradient (REINFORCE-shaped).&lt;/strong&gt; A return or advantage \(\hat{A}\) multiplies the score function:&lt;/p&gt;

\[\nabla_\theta J(\theta) \approx \mathbb{E}_{x,y\sim\pi_\theta}\big[\,\hat{A}(x,y)\,\nabla_\theta \log\pi_\theta(y\mid x)\,\big].\]

&lt;p&gt;For an autoregressive LM, \(\log\pi_\theta(y\mid x) = \sum_t \log\pi_\theta(y_t\mid x, y_{&amp;lt;t})\) — the same sum as the SFT NLL, with a &lt;em&gt;weight&lt;/em&gt; \(\hat{A}\) instead of “always 1.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;RLHF as KL-regularized reward.&lt;/strong&gt; After a reward model \(r_\phi\) is fit on pairs, the usual goal (&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Ouyang et al., 2022&lt;/a&gt;) is&lt;/p&gt;

\[\max_\theta\; \mathbb{E}_{x\sim\mathcal{D},\, y\sim\pi_\theta}\big[r_\phi(x,y)\big] - \beta\,\mathrm{KL}\big(\pi_\theta(\cdot\mid x)\,\|\,\pi_{\mathrm{ref}}(\cdot\mid x)\big).\]

&lt;p&gt;The KL term is why the policy does not collapse into a reward-hacking dialect that \(r_\phi\) likes and humans do not. \(\pi_{\mathrm{ref}}\) is typically the SFT checkpoint.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PPO clip (the optimizer, not the product).&lt;/strong&gt; PPO (&lt;a href=&quot;https://arxiv.org/abs/1707.06347&quot;&gt;Schulman et al., 2017&lt;/a&gt;) maximizes a &lt;em&gt;clipped&lt;/em&gt; surrogate on the probability ratio \(r_t(\theta) = \pi_\theta(a_t\mid s_t)/\pi_{\mathrm{old}}(a_t\mid s_t)\):&lt;/p&gt;

\[L^{\mathrm{CLIP}}(\theta) = \mathbb{E}\Big[\min\big(r_t(\theta)\,\hat{A}_t,\; \mathrm{clip}(r_t(\theta), 1-\varepsilon, 1+\varepsilon)\,\hat{A}_t\big)\Big].\]

&lt;p&gt;In the LM, \(a_t\) is a token and \(s_t\) is the prefix. InstructGPT used this loop; it is expensive (sampler, often a value head, instability).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;DPO (preferences without the sampler).&lt;/strong&gt; &lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Rafailov et al., 2023&lt;/a&gt; solve the KL-regularized problem in closed form and obtain a &lt;em&gt;classification&lt;/em&gt; loss on the same pairs \((y_w, y_l)\):&lt;/p&gt;

\[\mathcal{L}_{\mathrm{DPO}}(\theta) = -\log\sigma\Big(\beta\log\frac{\pi_\theta(y_w\mid x)}{\pi_{\mathrm{ref}}(y_w\mid x)} - \beta\log\frac{\pi_\theta(y_l\mid x)}{\pi_{\mathrm{ref}}(y_l\mid x)}\Big).\]

&lt;p&gt;Intuition: raise the implicit reward gap between winner and loser, measured in log-odds &lt;em&gt;relative to the reference&lt;/em&gt;. No \(r_\phi\) and no PPO rollout at train time. That is the contract; the derivation is in the paper and in &lt;strong&gt;21-99&lt;/strong&gt;.&lt;/p&gt;

&lt;pre&gt;&lt;code class=&quot;language-mermaid&quot;&gt;flowchart LR
  sft[&quot;SFT policy&quot;] --&amp;gt; pairs[&quot;Preference pairs winner / loser&quot;]
  pairs --&amp;gt; rm[&quot;RLHF: fit reward model&quot;]
  rm --&amp;gt; ppo[&quot;PPO against reward minus KL&quot;]
  pairs --&amp;gt; dpo[&quot;DPO: classify pairs vs reference&quot;]
  ppo --&amp;gt; aligned[&quot;Aligned policy&quot;]
  dpo --&amp;gt; aligned
&lt;/code&gt;&lt;/pre&gt;

&lt;h2 id=&quot;3-what-alignment-is-not&quot;&gt;3. What alignment is &lt;em&gt;not&lt;/em&gt;&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Not a replacement for retrieval.&lt;/strong&gt; Preferences do not add facts that were never in pretraining or in the prompt (Chapter 18-99).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Not a full safety proof.&lt;/strong&gt; Raters encode a policy; they do not certify robustness. Jailbreaks and distribution shift remain evaluation problems.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Not only RL.&lt;/strong&gt; RLHF is one implementation. DPO, other pairwise losses, and even careful SFT-only pipelines are alignment &lt;em&gt;in the product sense&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Not the same as distillation.&lt;/strong&gt; Distillation copies a teacher’s behavior into a smaller student (&lt;strong&gt;26-05&lt;/strong&gt;). Alignment changes &lt;em&gt;which&lt;/em&gt; behaviors are preferred. You can distill an already-aligned teacher; that is common for small product tiers.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-a-self-study-sketch-you-can-draw-on-paper&quot;&gt;4. A self-study sketch you can draw on paper&lt;/h2&gt;

&lt;p&gt;For one prompt \(x\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Sample or write two completions \(y_1, y_2\) from the SFT model.&lt;/li&gt;
  &lt;li&gt;A rater marks \(y_w \succ y_l\).&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;RLHF path:&lt;/em&gt; fit \(r_\phi\); run PPO on \(\pi_\theta\) with reward \(r_\phi - \beta \log(\pi_\theta/\pi_{\mathrm{ref}})\).&lt;/li&gt;
  &lt;li&gt;&lt;em&gt;DPO path:&lt;/em&gt; push up \(\log\pi_\theta(y_w\mid x)\) relative to \(\log\pi_\theta(y_l\mid x)\), scaled against the same logs under \(\pi_{\mathrm{ref}}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you can explain why the KL / reference term exists (reward hacking, style collapse), you are ready for Chapter 21-99. If you only need the product story, stop here.&lt;/p&gt;

&lt;h2 id=&quot;5-where-to-go-next-in-this-course&quot;&gt;5. Where to go next in this course&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Chapters 20–21&lt;/strong&gt; — states, actions, returns, PPO.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;21-99&lt;/strong&gt; — RLHF, DPO, GRPO for reasoning models.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;26-04&lt;/strong&gt; — serving the aligned policy cheaply.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;26-05&lt;/strong&gt; — shrinking an aligned teacher without redoing preference collection from scratch.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;further-reading&quot;&gt;Further reading&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Ouyang et al., 2022. &lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Training language models to follow instructions with human feedback&lt;/a&gt; (InstructGPT / RLHF + PPO).&lt;/li&gt;
  &lt;li&gt;Schulman et al., 2017. &lt;a href=&quot;https://arxiv.org/abs/1707.06347&quot;&gt;Proximal Policy Optimization Algorithms&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Rafailov et al., 2023. &lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Direct Preference Optimization&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Topic-map inspiration (not quoted): &lt;a href=&quot;https://alisawuffles.notion.site/alisa-s-book-of-llms&quot;&gt;Alisa’s Book of LLMs&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key takeaways&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Alignment in this chapter = SFT then preference reweighting.&lt;/li&gt;
  &lt;li&gt;Write three lines: policy gradient \(\hat{A}\nabla\log\pi\); RLHF = reward minus \(\beta\,\mathrm{KL}\) to a reference; PPO clips the probability ratio.&lt;/li&gt;
  &lt;li&gt;DPO is the same KL-regularized optimum as a logistic loss on \((y_w, y_l)\) — no reward model at train time.&lt;/li&gt;
  &lt;li&gt;Skills come from data (and tools); preferences rank skills you already have.&lt;/li&gt;
  &lt;li&gt;Full RL derivations stay in Chapters 20–21 — do not duplicate them here.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qPN_XZcJf_s&quot;&gt;Reinforcement Learning with Human Feedback (RLHF), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. The three-stage picture (pretrain, SFT, preference) is this lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=k2pD3k1485A&quot;&gt;Direct Preference Optimization (DPO) - How to fine-tune LLMs directly without reinforcement learning&lt;/a&gt; — Luis Serrano Academy, English. DPO, the preference objective the lesson asks you to be able to write.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=T_X4XFwKX8k&quot;&gt;Reinforcement Learning from Human Feedback (RLHF) Explained&lt;/a&gt; — IBM Technology, English. RLHF with a reward model, the stage DPO is offered as an alternative to.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-02 Prompting, In-Context Learning, and Instruction Following</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_02_Prompting_and_In_Context_Learning/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_02_Prompting_and_In_Context_Learning</id>
   <content type="html">&lt;p&gt;How can a frozen neural network—whose weights $\theta$ do not change by a single bit—learn a brand-new classification task just by reading four examples inside its prompt? In-Context Learning (ICL) works because self-attention conditions every next-token distribution $p_\theta(y \mid x_1, y_1, \dots, x_k, y_k, x_{\text{query}})$ on the entire prefix: the prompt acts as a temporary soft program that selects and composes latent skills already crystallized during pretraining.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mechanics-of-prompting--in-context-learning&quot;&gt;Key ideas: Mechanics of Prompting &amp;amp; In-Context Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Prefix Conditioning ($p_\theta(x_t \mid x_{&amp;lt;t})$)&lt;/strong&gt;: Frames every system prompt, few-shot example, and retrieved document strictly as conditioning context steering the same frozen next-token distribution.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Implicit Bayesian Task Selection &amp;amp; Induction Heads&lt;/strong&gt;: Explains how few-shot examples narrow posterior uncertainty over &lt;em&gt;which&lt;/em&gt; latent task concept is active, assisted by induction-head circuits copying patterns across context.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Base Pretrained vs. Instruction-Tuned Behavior&lt;/strong&gt;: Distinguishes a raw base model (which completes &lt;em&gt;“Translate to French: hello”&lt;/em&gt; with &lt;em&gt;“Translate to Spanish: …“&lt;/em&gt;) from an SFT/chat-tuned model trained on role-delimited assistant turns.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Prompt Sensitivity &amp;amp; Structured Verification&lt;/strong&gt;: Addresses order sensitivity, label-space bias, and why Chain-of-Thought (CoT) unlocks extra serial computation steps per token before committing to an answer.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-how-few-shot-context-shifts-next-token-probabilities-via-bayes-rule&quot;&gt;Worked example: How Few-Shot Context Shifts Next-Token Probabilities via Bayes’ Rule&lt;/h3&gt;

&lt;p&gt;Suppose a pretrained LM implicitly models two equally likely latent tasks ($P(T_{\text{syn}}) = P(T_{\text{ant}}) = 0.5$): Task $T_{\text{syn}}$ outputs synonyms (predicts &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;hot -&amp;gt; warm&quot;&lt;/code&gt; with prob $0.8$, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;hot -&amp;gt; cold&quot;&lt;/code&gt; with prob $0.1$) and Task $T_{\text{ant}}$ outputs antonyms (predicts &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;hot -&amp;gt; cold&quot;&lt;/code&gt; with prob $0.8$, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;hot -&amp;gt; warm&quot;&lt;/code&gt; with prob $0.1$).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Zero-shot prediction for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;big -&amp;gt; ?&quot;&lt;/code&gt;&lt;/strong&gt; (before seeing any examples):
Both tasks have posterior $0.5$, so &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;large&quot;&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;small&quot;&lt;/code&gt; tie at $0.45$ each—the model is ambiguous!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Now prepend 2 few-shot antonym examples&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;hot -&amp;gt; cold\nfast -&amp;gt; slow\n&quot;&lt;/code&gt; (each has likelihood $0.8$ under $T_{\text{ant}}$ and $0.1$ under $T_{\text{syn}}$):
    &lt;ul&gt;
      &lt;li&gt;Unnormalized posterior for $T_{\text{ant}}$: $0.5 \times 0.8^2 = 0.320$.&lt;/li&gt;
      &lt;li&gt;Unnormalized posterior for $T_{\text{syn}}$: $0.5 \times 0.1^2 = 0.005$.&lt;/li&gt;
      &lt;li&gt;Posterior $P(T_{\text{ant}} \mid \text{prompt}) = \frac{0.320}{0.325} = 98.46\%$!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Resulting predictive probability for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;big -&amp;gt; small&quot;&lt;/code&gt;&lt;/strong&gt;:
\(0.9846(0.8) + 0.0154(0.1) = 78.9\% \text{ vs. } 11.1\% \text{ for } \text{&quot;large&quot;}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Just two clean examples collapse task ambiguity from $50/50$ to $98.5\%$ without a single gradient update—illustrating why example quality and format consistency dominate prompt engineering.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;prompting-in-context-learning-and-instruction-following&quot;&gt;Prompting, In-Context Learning, and Instruction Following&lt;/h1&gt;

&lt;p&gt;After pretraining, the weights already implement a next-token machine. &lt;strong&gt;Prompting&lt;/strong&gt; is the cheapest way to steer that machine: you change the prefix \(x_{&amp;lt;t}\), not \(\theta\). &lt;strong&gt;Fine-tuning&lt;/strong&gt; changes \(\theta\). Most LLM products use both, in that order.&lt;/p&gt;

&lt;p&gt;This lesson separates three interfaces that interviews and blogs often mash together: zero-shot prompting, in-context (few-shot) learning, and instruction-following after supervised adaptation.&lt;/p&gt;

&lt;h2 id=&quot;1-the-prompt-is-part-of-the-sequence&quot;&gt;1. The prompt is part of the sequence&lt;/h2&gt;

&lt;p&gt;Because \(p_\theta(x_t \mid x_{&amp;lt;t})\) conditions on &lt;em&gt;everything&lt;/em&gt; in the window, a system prompt, retrieved documents, tool results, and the user’s question are just more tokens. There is no separate “prompt input” in the architecture. Formatting conventions (chat templates, XML-ish tags, JSON schemas) matter because they are &lt;strong&gt;stable prefixes&lt;/strong&gt; the model saw, or was later trained to expect.&lt;/p&gt;

&lt;p&gt;A useful habit: when a model “ignores the instruction,” first check whether the instruction is still inside the context window and whether the chat template is the one the checkpoint was adapted with. That is a data/format bug more often than an architecture bug.&lt;/p&gt;

&lt;h2 id=&quot;2-zero-shot-vs-in-context-learning&quot;&gt;2. Zero-shot vs in-context learning&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Zero-shot.&lt;/strong&gt; You describe the task in language (“Translate to Vietnamese:”) and decode. The model generalizes from pretraining patterns that look like that request.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In-context learning (ICL) / few-shot.&lt;/strong&gt; You put a handful of input–output exemplars in the prefix, then the new input. &lt;a href=&quot;https://arxiv.org/abs/2005.14165&quot;&gt;Brown et al., 2020&lt;/a&gt; (GPT-3) showed that at sufficient scale this can look like task learning &lt;em&gt;without a gradient step&lt;/em&gt;. The mechanism is still next-token prediction: the exemplars make the desired continuation more likely.&lt;/p&gt;

&lt;p&gt;ICL is &lt;strong&gt;not&lt;/strong&gt; the same as fine-tuning:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt; &lt;/th&gt;
      &lt;th&gt;In-context learning&lt;/th&gt;
      &lt;th&gt;Classical fine-tuning&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;What changes&lt;/td&gt;
      &lt;td&gt;Tokens in the window&lt;/td&gt;
      &lt;td&gt;Parameters \(\theta\) (or adapters)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Persistence&lt;/td&gt;
      &lt;td&gt;Dies when the prompt is gone&lt;/td&gt;
      &lt;td&gt;Survives across requests&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Cost&lt;/td&gt;
      &lt;td&gt;Extra prefill compute / cache&lt;/td&gt;
      &lt;td&gt;Training compute, then cheaper prompts&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Data&lt;/td&gt;
      &lt;td&gt;A few exemplars you can edit live&lt;/td&gt;
      &lt;td&gt;A dataset and an optimizer&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;When to prefer ICL: the task is new, labeled data are scarce, or you must change behavior per request (different customers, different schemas). When to prefer fine-tuning: the behavior must be stable, the prompt would become huge, or you need a smaller/faster specialist (often after distillation — &lt;strong&gt;26-05&lt;/strong&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Chain-of-thought&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.11903&quot;&gt;Wei et al., 2022&lt;/a&gt;) is a prompting pattern: ask the model to emit intermediate steps before the answer. It does not add a new module; it reallocates decode tokens to a longer, more checkable computation. Later “reasoning” models &lt;em&gt;train&lt;/em&gt; that habit (Chapter 25-99). Do not confuse a prompt trick with a new architecture.&lt;/p&gt;

&lt;h2 id=&quot;3-instruction-following-is-usually-not-raw-pretraining&quot;&gt;3. Instruction-following is usually not raw pretraining&lt;/h2&gt;

&lt;p&gt;A base LM completes text. If the prefix is a blog post, it continues the blog post. Users want a &lt;strong&gt;helpful assistant&lt;/strong&gt;: follow the request, refuse when appropriate, use a consistent tone.&lt;/p&gt;

&lt;p&gt;The standard first adaptation is &lt;strong&gt;supervised fine-tuning (SFT)&lt;/strong&gt; on (instruction, response) pairs — demonstrations written or filtered by humans, or generated by a stronger model and then edited. The loss is still next-token cross-entropy, but the &lt;em&gt;data distribution&lt;/em&gt; is now “answer this request,” not “continue the web.”&lt;/p&gt;

&lt;p&gt;After SFT, prompting still matters (tools, RAG, style), but the model is much more likely to treat the user text as a &lt;em&gt;task&lt;/em&gt; rather than as a document to extend. Preference optimization (next lesson) then ranks &lt;em&gt;which&lt;/em&gt; valid answers are preferred.&lt;/p&gt;

&lt;p&gt;Classical transfer learning (Chapter 15) updates a backbone for a fixed head and label set. Instruction SFT updates the same generative head on many tasks written in language. Same optimizer family; different interface.&lt;/p&gt;

&lt;h2 id=&quot;4-a-small-prompting-checklist-self-study&quot;&gt;4. A small prompting checklist (self-study)&lt;/h2&gt;

&lt;p&gt;Write these down and try them on any open instruct model:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;State the &lt;strong&gt;role&lt;/strong&gt; and the &lt;strong&gt;output contract&lt;/strong&gt; (plain text, JSON keys, language).&lt;/li&gt;
  &lt;li&gt;Put &lt;strong&gt;non-negotiable constraints&lt;/strong&gt; before long retrieved context (they can be pushed out of \(L\) if you append them last).&lt;/li&gt;
  &lt;li&gt;For ICL, keep exemplars &lt;strong&gt;format-identical&lt;/strong&gt; to the query you will ask.&lt;/li&gt;
  &lt;li&gt;If you need sources, retrieve first (Chapter 18-99); do not ask the model to invent citations.&lt;/li&gt;
  &lt;li&gt;If you need lasting behavior, plan SFT / adapters — do not grow a 8k-token prompt forever.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key takeaways&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Prompting edits the conditioning prefix; fine-tuning edits weights.&lt;/li&gt;
  &lt;li&gt;ICL is few-shot &lt;em&gt;in the window&lt;/em&gt;, not a hidden inner-loop optimizer you get for free.&lt;/li&gt;
  &lt;li&gt;Instruction-following is mostly a &lt;strong&gt;data&lt;/strong&gt; change (SFT) on top of the same next-token loss.&lt;/li&gt;
  &lt;li&gt;Alignment preferences are a further change — lesson &lt;strong&gt;26-03&lt;/strong&gt; — not a substitute for a clear prompt.&lt;/li&gt;
  &lt;li&gt;Decode-time sampling (temperature, top-\(k\) / top-\(p\)) is a serving knob, not a new prompt type — &lt;strong&gt;26-04&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=As9a15poQHs&quot;&gt;What Is In-Context Learning in Deep Learning?&lt;/a&gt; — Deep Learning with Yacine, English. In-context learning is conditioning on examples inside the prompt, which is this lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, English. A prompt is more tokens in the same next-token model; that is the lesson’s first section.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, English. You can see a prompt as nothing but the prefix the sampler continues.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26-01 Pretraining and Tokenization</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_01_Pretraining_and_Tokenization/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_01_Pretraining_and_Tokenization</id>
   <content type="html">&lt;p&gt;At the bottom of every trillion-parameter LLM lies one astonishingly clean equation: for next-token cross-entropy loss with a softmax language-model head, the gradient with respect to the raw vocabulary logits $z$ is simply $p - t$—predicted probability minus the one-hot target. Understanding how that gradient interacts with log-sum-exp numerical stability, SwiGLU activations, selective AdamW weight decay, and BPE tokenization turns LLM pretraining from black magic into transparent numerical engineering.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-foundations-of-llm-pretraining--tokenization&quot;&gt;Key ideas: Foundations of LLM Pretraining &amp;amp; Tokenization&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Causal Next-Token Objective &amp;amp; Softmax Gradient&lt;/strong&gt;: Shifts inputs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x[:-1]&lt;/code&gt; against targets &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x[1:]&lt;/code&gt; across sequence length $T$ and exploits $\frac{\partial \mathcal{L}}{\partial z} = p - t$ for fast, clean backpropagation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Log-Sum-Exp &amp;amp; Online Softmax Stability&lt;/strong&gt;: Subtracts $m = \max_j z_j$ before exponentiating to eliminate &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; overflows, and generalizes to streaming block-wise max/normalizer updates inside FlashAttention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Modern FFN Activations &amp;amp; Selective AdamW Decay&lt;/strong&gt;: Uses SwiGLU gated linear units and applies AdamW decoupled weight decay &lt;em&gt;only&lt;/em&gt; to 2D weight matrices—never to 1D LayerNorm/RMSNorm scales or biases.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Pillar 4 — Byte-Pair Encoding (BPE) Subword Trade-offs&lt;/strong&gt;: Iteratively merges the most frequent adjacent byte/symbol pairs to balance sequence compression against embedding-table size $&lt;/td&gt;
          &lt;td&gt;V&lt;/td&gt;
          &lt;td&gt;\times d_{\text{model}}$.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-log-sum-exp-softmax-cross-entropy-loss-and-exact-logit-gradient&quot;&gt;Worked example: Log-Sum-Exp Softmax, Cross-Entropy Loss, and Exact Logit Gradient&lt;/h3&gt;

&lt;p&gt;Suppose at position $t$, a tiny 3-token vocabulary &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{0: &quot;cat&quot;, 1: &quot;dog&quot;, 2: &quot;mat&quot;}&lt;/code&gt; produces raw logits $z = [100.0,\; 102.0,\; 100.0]$, and the true next token is index &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;dog&quot;&lt;/code&gt;, so $t = [0, 1, 0]$).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Shift by $m = \max(z) = 102.0$&lt;/strong&gt; (naive $e^{102}$ risks overflow in FP16 where max finite value is $65{,}504$!):
\(z - m = [-2.0,\; 0.0,\; -2.0].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute shifted exponentials and partition sum&lt;/strong&gt;:
\(e^{-2} \approx 0.1353, \quad e^0 = 1.0000, \quad e^{-2} \approx 0.1353 \implies Z = 1.2707.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Softmax probabilities $p$ and Cross-Entropy Loss $\mathcal{L}$&lt;/strong&gt;:
\(p = [0.1065,\; 0.7870,\; 0.1065], \qquad \mathcal{L} = -\ln(0.7870) \approx 0.2395\text{ nats (Perplexity } e^{0.2395} = 1.271\text{)}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact logit gradient $\frac{\partial \mathcal{L}}{\partial z} = p - t$&lt;/strong&gt;:
\(p - t = [0.1065,\; 0.7870 - 1,\; 0.1065] = [+0.1065,\; -0.2130,\; +0.1065].\)
Notice the gradients sum strictly to $0.0000$, pushing the true token logit up and suppressing wrong tokens proportionally to their probability!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Subtracting $m = 102.0$ keeps FP16/BF16 arithmetic completely finite while producing exact probabilities and zero-sum gradients.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;pretraining-and-tokenization&quot;&gt;Pretraining and Tokenization&lt;/h1&gt;

&lt;p&gt;A modern LLM is pretrained as a &lt;strong&gt;next-token predictor&lt;/strong&gt;. Everything later — prompting, instruction-following, tools — sits on top of a model that, given tokens \(x_1,\ldots,x_{t-1}\), outputs a distribution over the next token \(x_t\).&lt;/p&gt;

&lt;p&gt;This lesson stays conceptual. You do not need a full training stack; you need the objective, the tokenizer that defines the symbol set, and the context window that bounds what the model can “see.”&lt;/p&gt;

&lt;h2 id=&quot;1-next-token-prediction&quot;&gt;1. Next-token prediction&lt;/h2&gt;

&lt;p&gt;Let \(x = (x_1,\ldots,x_T)\) be a token sequence. A causal language model factorizes&lt;/p&gt;

\[p_\theta(x) = \prod_{t=1}^{T} p_\theta(x_t \mid x_{&amp;lt;t}).\]

&lt;p&gt;Training minimizes the average negative log-likelihood (cross-entropy) on a corpus:&lt;/p&gt;

\[\mathcal{L}(\theta) = -\frac{1}{T}\sum_{t=1}^{T} \log p_\theta(x_t \mid x_{&amp;lt;t}).\]

&lt;p&gt;At each position the network produces logits \(z \in \mathbb{R}^{V}\) (\(V\) is the vocabulary size). Softmax turns them into \(p_\theta(\cdot \mid x_{&amp;lt;t})\). The “label” is simply the observed next token — no human annotator is required. That is why this is &lt;strong&gt;self-supervised&lt;/strong&gt; in the sense of Chapter 16, even though the loss looks like ordinary classification.&lt;/p&gt;

&lt;p&gt;Two consequences matter later in the chapter:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The output space is &lt;strong&gt;huge&lt;/strong&gt; (often \(V \sim 32\mathrm{k}\)–\(200\mathrm{k}+\)). Classical knowledge distillation that matches a 1,000-class softmax (Chapter 23) does not copy over cheaply — see &lt;strong&gt;26-05&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Training is &lt;strong&gt;teacher-forced&lt;/strong&gt;: the model always conditions on the &lt;em&gt;true&lt;/em&gt; prefix, not on its own samples. At decode time it must condition on its own tokens. That train/serve mismatch is normal; alignment and decoding tricks try to live with it, not erase it.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A tiny PyTorch-shaped sketch of the loss (shapes only):&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;next_token_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# logits: (batch, seq, vocab) for positions 0..T-1
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# targets: next token at each position
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;ignore_index&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# padding
&lt;/span&gt;    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The rest of this lesson is the &lt;strong&gt;math the last layer actually uses&lt;/strong&gt;, then the tokenizer and the window. If a formula already lives in Chapters 02–03 or 10, we only restate the LM-shaped version.&lt;/p&gt;

&lt;h2 id=&quot;2-softmax-cross-entropy-and-partialmathcallpartial-z--p---t&quot;&gt;2. Softmax, cross-entropy, and \(\partial\mathcal{L}/\partial z = p - t\)&lt;/h2&gt;

&lt;p&gt;At one position the model emits logits \(z \in \mathbb{R}^{V}\). Softmax is&lt;/p&gt;

\[p_i = \frac{e^{z_i}}{\sum_{j=1}^{V} e^{z_j}}.\]

&lt;p&gt;The LM loss on a one-hot target \(t\) (the observed next token) is cross-entropy&lt;/p&gt;

\[\mathcal{L} = -\sum_{i=1}^{V} t_i \log p_i = -\log p_{t^*},\]

&lt;p&gt;where \(t^*\) is the index of the true token. Differentiating through softmax gives the interview identity&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial z} = p - t.\]

&lt;p&gt;That is the same cancellation Chapter 03 shows for CE + softmax on a small classifier. The LM does it at every time step, with \(V\) in the tens or hundreds of thousands.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CE, KL, and entropy.&lt;/strong&gt; For any two discrete distributions \(p^*\) and \(p\),&lt;/p&gt;

\[\mathrm{CE}(p^*, p) = H(p^*) + \mathrm{KL}(p^* \| p).\]

&lt;p&gt;A one-hot \(p^*\) has \(H(p^*) = 0\), so token-level CE &lt;strong&gt;is&lt;/strong&gt; \(\mathrm{KL}(\text{one-hot} \| p)\) &lt;strong&gt;is&lt;/strong&gt; negative log-likelihood. When the target is a &lt;em&gt;soft&lt;/em&gt; teacher (distillation, &lt;strong&gt;26-05&lt;/strong&gt;), \(H(p^*)\) is a constant w.r.t. the student and the extra signal is the KL. Temperature-scaled softmax in 26-05 is this identity with a flatter \(p^*\).&lt;/p&gt;

&lt;h2 id=&quot;3-log-sum-exp-and-why-flashattention-talks-about-online-softmax&quot;&gt;3. Log-sum-exp and why FlashAttention talks about “online softmax”&lt;/h2&gt;

&lt;p&gt;Naive \(e^{z_i}\) overflows when logits are large. The stable rewrite subtracts the row max \(m = \max_j z_j\):&lt;/p&gt;

\[\log\sum_j e^{z_j} = m + \log\sum_j e^{z_j - m}, \qquad p_i = \exp\big(z_i - \mathrm{LSE}(z)\big).\]

&lt;p&gt;That is &lt;strong&gt;log-sum-exp&lt;/strong&gt;. The same algebra can be run &lt;em&gt;incrementally&lt;/em&gt;: if you have already seen a prefix of logits with running max \(m\) and running sum \(s = \sum e^{z-m}\), and a new block arrives with max \(m&apos;\), you rescale&lt;/p&gt;

\[s \leftarrow s\, e^{m - m_{\mathrm{new}}} + \sum_{\text{new}} e^{z - m_{\mathrm{new}}}, \quad m_{\mathrm{new}} = \max(m, m&apos;).\]

&lt;p&gt;Keep a matching running weighted sum of values and you have &lt;strong&gt;online softmax&lt;/strong&gt; — the numerical story inside &lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;FlashAttention&lt;/a&gt;, without any CUDA. Lesson &lt;strong&gt;26-07&lt;/strong&gt; uses this as the reason the \(L\times L\) matrix never has to land in HBM.&lt;/p&gt;

&lt;h2 id=&quot;4-the-linear-layer-math-xw-vs-pytorch-w&quot;&gt;4. The linear layer: math \(XW\) vs PyTorch \(W\)&lt;/h2&gt;

&lt;p&gt;A batch of hidden states \(X \in \mathbb{R}^{B \times d_{\mathrm{in}}}\) and a math textbook write&lt;/p&gt;

\[Y = X W + b, \qquad W \in \mathbb{R}^{d_{\mathrm{in}} \times d_{\mathrm{out}}}.\]

&lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.Linear(n_in, n_out)&lt;/code&gt; stores &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight&lt;/code&gt; with shape &lt;strong&gt;\((n_{\mathrm{out}}, n_{\mathrm{in}})\)&lt;/strong&gt; and computes \(X W^\top + b\). Same affine map; the stored matrix is the textbook \(W\) &lt;em&gt;transposed&lt;/em&gt;. When you count parameters in &lt;strong&gt;26-07&lt;/strong&gt;, use \(d_{\mathrm{in}} \times d_{\mathrm{out}}\) and do not double-count because of the layout. When you port a paper, check which convention the authors drew.&lt;/p&gt;

&lt;h2 id=&quot;5-activations-the-ffn-actually-uses&quot;&gt;5. Activations the FFN actually uses&lt;/h2&gt;

&lt;p&gt;Chapter 02 already has the pictures. The LM-relevant three:&lt;/p&gt;

\[\begin{aligned}
\mathrm{ReLU}(z) &amp;amp;= \max(0, z), \\
\mathrm{SiLU}(z) = \mathrm{Swish}(z) &amp;amp;= z\,\sigma(z), \\
\mathrm{SwiGLU}(x) &amp;amp;= \big(\mathrm{SiLU}(x W_{\mathrm{gate}}) \odot (x W_{\mathrm{up}})\big) W_{\mathrm{down}}.
\end{aligned}\]

&lt;p&gt;ReLU is the 2017 FFN. SiLU is the smooth gate. SwiGLU is the &lt;em&gt;block&lt;/em&gt; (three matrices, Hadamard gate) that &lt;strong&gt;26-07&lt;/strong&gt; puts in the decoder diagram. GELU (Chapter 02) still appears in older GPT-style FFNs; it is not a third theory.&lt;/p&gt;

&lt;h2 id=&quot;6-adam--adamw-moments-and-which-parameters-decay&quot;&gt;6. Adam / AdamW: moments, and which parameters decay&lt;/h2&gt;

&lt;p&gt;Pretraining almost always uses &lt;strong&gt;AdamW&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/1711.05101&quot;&gt;Loshchilov &amp;amp; Hutter, 2019&lt;/a&gt;), not raw Adam (&lt;a href=&quot;https://arxiv.org/abs/1412.6980&quot;&gt;Kingma &amp;amp; Ba, 2015&lt;/a&gt;). The moments are the Chapter 10 ones:&lt;/p&gt;

\[\begin{aligned}
m_t &amp;amp;= \beta_1 m_{t-1} + (1-\beta_1) g_t, \\
v_t &amp;amp;= \beta_2 v_{t-1} + (1-\beta_2) g_t^{\odot 2}, \\
\hat{m}_t &amp;amp;= \frac{m_t}{1-\beta_1^t}, \quad
\hat{v}_t = \frac{v_t}{1-\beta_2^t}.
\end{aligned}\]

&lt;p&gt;Adam applies an adaptive step and, if you add L2 to the &lt;em&gt;loss&lt;/em&gt;, that L2 gradient is also rescaled by \(\sqrt{\hat{v}}\) — so “weight decay” is no longer a uniform pull toward zero. AdamW &lt;strong&gt;decouples&lt;/strong&gt; the decay:&lt;/p&gt;

\[\theta_t = \theta_{t-1} - \eta \left( \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\varepsilon} + \lambda \theta_{t-1} \right).\]

&lt;p&gt;&lt;strong&gt;Which parameters get \(\lambda &amp;gt; 0\)?&lt;/strong&gt; The usual LLM convention (Hugging Face &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AdamW&lt;/code&gt;, Llama-style trainers): apply decay to &lt;strong&gt;2-D weight matrices&lt;/strong&gt; (attention and FFN projections, often the embedding / LM head). Do &lt;strong&gt;not&lt;/strong&gt; decay 1-D tensors: biases (if any) and RMSNorm / LayerNorm gains. Those scales are not “weights that should shrink”; decaying them fights the normalizer. Details live in &lt;strong&gt;10-01&lt;/strong&gt;; this paragraph is only the LM checklist.&lt;/p&gt;

&lt;h2 id=&quot;7-why-we-do-not-train-on-raw-characters-or-raw-words&quot;&gt;7. Why we do not train on raw characters (or raw words)&lt;/h2&gt;

&lt;p&gt;Characters make sequences very long and waste capacity on spelling. Whole words explode the vocabulary and fail on rare or new spellings. &lt;strong&gt;Subword&lt;/strong&gt; tokenization sits in between: frequent words stay one token; rare words split into reusable pieces.&lt;/p&gt;

&lt;p&gt;Two families you will actually meet:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Byte Pair Encoding (BPE).&lt;/strong&gt; Start from characters (or bytes). Repeatedly merge the most frequent adjacent pair. The merge table &lt;em&gt;is&lt;/em&gt; the tokenizer. &lt;a href=&quot;https://arxiv.org/abs/1508.07909&quot;&gt;Sennrich et al., 2016&lt;/a&gt; introduced BPE for neural MT; GPT-2-style tokenizers are a widely used descendant. OpenAI’s &lt;a href=&quot;https://github.com/openai/tiktoken&quot;&gt;tiktoken&lt;/a&gt; is an engineering implementation of this idea, not a new algorithm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Unigram / SentencePiece.&lt;/strong&gt; Instead of greedy merges, a unigram model keeps a large candidate vocabulary and drops tokens that hurt a likelihood objective. &lt;a href=&quot;https://arxiv.org/abs/1808.06226&quot;&gt;Kudo &amp;amp; Richardson, 2018&lt;/a&gt; (SentencePiece) is the usual package: it trains from raw text and can emit either BPE or unigram vocabularies. Many multilingual open LMs use this stack.&lt;/p&gt;

&lt;p&gt;Intuition, not a training recipe:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Tokenization is a &lt;strong&gt;lossy, deterministic front-end&lt;/strong&gt;. The LM never sees characters the tokenizer fused, and it cannot invent a token ID that is not in the table.&lt;/li&gt;
  &lt;li&gt;The same English word can be 1 token in one vocab and 3 tokens in another. &lt;strong&gt;Cost and context are measured in tokens, not words.&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;Special tokens (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;bos&amp;gt;&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;eos&amp;gt;&lt;/code&gt;, chat template markers, tool tags) are first-class vocabulary entries. Off-by-one mistakes here waste the context window or break chat formatting.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Chapter 18’s embedding table \(E \in \mathbb{R}^{V \times d}\) is exactly layer 0 of this model: each token ID becomes a vector, then (in modern decoders) a positional method such as RoPE is applied inside attention (optional lesson &lt;strong&gt;08-99&lt;/strong&gt;).&lt;/p&gt;

&lt;h2 id=&quot;8-the-context-window&quot;&gt;8. The context window&lt;/h2&gt;

&lt;p&gt;Self-attention in a vanilla Transformer mixes every pair of positions in the window. If the window length is \(L\), one layer costs \(O(L^2)\) in attention (plus cheap position-wise MLPs). So \(L\) is both a &lt;strong&gt;capability&lt;/strong&gt; limit and a &lt;strong&gt;compute/memory&lt;/strong&gt; limit.&lt;/p&gt;

&lt;p&gt;What the window actually bounds:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The model can only condition on the last \(L\) tokens of the concatenated prompt + generation (plus whatever you retrieve and paste — RAG, Chapter 18-99).&lt;/li&gt;
  &lt;li&gt;Long documents must be truncated, summarized, or retrieved in chunks. “The model read my 200-page PDF” usually means &lt;em&gt;a retrieval system stuffed selected chunks into \(L\)&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;During decode, keys and values for those \(L\) positions are the natural thing to &lt;strong&gt;cache&lt;/strong&gt; (lesson &lt;strong&gt;26-04&lt;/strong&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Extensions (sliding windows, grouped-query attention, extra-long RoPE scaling) change the constants; they do not remove the idea that the model has a finite working tape.&lt;/p&gt;

&lt;h2 id=&quot;9-pretraining-data-briefly&quot;&gt;9. Pretraining data, briefly&lt;/h2&gt;

&lt;p&gt;Pretraining corpora mix web text, books, code, and filtered crawls. You do not need a secret mix to understand the objective. You &lt;em&gt;do&lt;/em&gt; need to remember:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The loss rewards &lt;strong&gt;fluency and corpus statistics&lt;/strong&gt;, not truth. Hallucination is not a separate bug; it is next-token sampling from an imperfect \(p_\theta\).&lt;/li&gt;
  &lt;li&gt;Data filters and deduplication are part of the model. Two LMs with the same architecture can behave differently because the corpus differed.&lt;/li&gt;
  &lt;li&gt;Scaling (Chapter 25; train-time sketch in &lt;strong&gt;26-07&lt;/strong&gt;) relates loss to parameters, tokens, and compute. This lesson assumes that curve exists; it does not re-fit it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key takeaways&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Pretraining = maximize next-token likelihood under a causal mask.&lt;/li&gt;
  &lt;li&gt;Softmax + CE collapses to \(\partial\mathcal{L}/\partial z = p - t\). CE = entropy + KL; one-hot targets make that just NLL.&lt;/li&gt;
  &lt;li&gt;Log-sum-exp is the stable softmax; the incremental version is the FlashAttention narrative (&lt;strong&gt;26-07&lt;/strong&gt;).&lt;/li&gt;
  &lt;li&gt;PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear&lt;/code&gt; stores \(W\) as \((n_{\mathrm{out}}, n_{\mathrm{in}})\) and applies \(X W^\top\). AdamW decays 2-D weights, not norm gains.&lt;/li&gt;
  &lt;li&gt;The tokenizer defines the discrete alphabet; BPE and SentencePiece are the two practical stories.&lt;/li&gt;
  &lt;li&gt;Context length \(L\) is the working memory of attention — and the size of the KV-cache you will pay for at serve time.&lt;/li&gt;
  &lt;li&gt;The same softmax-over-\(V\) view that makes pretraining simple is what makes &lt;strong&gt;classical logit distillation expensive&lt;/strong&gt; for LMs (continue in &lt;strong&gt;26-05&lt;/strong&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=zduSFxRajkE&quot;&gt;Let’s build the GPT Tokenizer&lt;/a&gt; — Andrej Karpathy, English. Byte-pair encoding and the tokenizer are this lesson’s second half. The video is long and is the canonical build.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=hL4ZnAWSyuU&quot;&gt;LLM Tokenizers Explained: BPE Encoding, WordPiece and SentencePiece&lt;/a&gt; — DataMListic, English. A short comparison of BPE, WordPiece, and SentencePiece before that build.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, English. Next-token cross-entropy on characters, the objective the lesson writes before tokens get merged.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>26 Large Language Models</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter26/26_00_Introduction</id>
   <content type="html">&lt;p&gt;Every single chapter you studied earlier—backpropagation, LayerNorm, attention, Transformers, word embeddings, transfer learning, RLHF, and quantization—converges right here. A modern Large Language Model is not a mysterious alien artifact; it is an autoregressive decoder-only Transformer scaled to trillions of tokens, aligned with human preferences, and engineered down to the byte of KV-cache memory. This hub connects every piece into one coherent end-to-end engineering blueprint.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-end-to-end-llm-stack&quot;&gt;Key ideas: The End-to-End LLM Stack&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Pretraining &amp;amp; Tokenization&lt;/strong&gt;: Converts raw corpora into subword token IDs (BPE) and trains a decoder-only Transformer via causal next-token cross-entropy loss across trillions of tokens.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Prompting &amp;amp; Post-Training Alignment&lt;/strong&gt;: Steers pretrained knowledge first with zero/few-shot prompts (in-context learning), then shapes helpful, safe behavior via SFT, RLHF/PPO, DPO, and verifiable-reward RL.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Modern Decoder Internals &amp;amp; Memory Accounting&lt;/strong&gt;: Replaces 2017 Transformer blocks with RMSNorm, RoPE, SwiGLU, GQA, and FlashAttention, enabling exact back-of-the-envelope parameter, FLOP, and KV-cache calculations.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Serving, Quantization, and Distillation&lt;/strong&gt;: Optimizes real-world Time-To-First-Token (TTFT) and Time-Per-Output-Token (TPOT) via prefill/decode separation, continuous batching, INT4/FP8 quantization, speculative decoding, and distillation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-mapping-one-user-request-across-the-4-llm-stages&quot;&gt;Worked example: Mapping One User Request Across the 4 LLM Stages&lt;/h3&gt;

&lt;p&gt;Suppose a user sends a $1{,}000$-token prompt to an 8B-parameter LLM (2 bytes/param in BF16 $= 16\text{ GB}$ weights) and receives a $200$-token answer.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tokenization&lt;/strong&gt;: Roughly $1{,}000$ English tokens $\approx 750$ words (average $\sim 1.33$ tokens/word).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Prefill FLOPs&lt;/strong&gt; (processing all $1{,}000$ prompt tokens in parallel, using $2N$ FLOPs/token):
\(2 \times (8 \times 10^9) \times 1{,}000 = 1.6 \times 10^{13}\text{ FLOPs (compute-bound!)}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decode FLOPs &amp;amp; Weight Bandwidth&lt;/strong&gt; (generating $200$ tokens sequentially):
    &lt;ul&gt;
      &lt;li&gt;Total decode FLOPs: $2 \times (8 \times 10^9) \times 200 = 3.2 \times 10^{12}\text{ FLOPs}$ ($5\times$ fewer FLOPs than prefill!).&lt;/li&gt;
      &lt;li&gt;Yet total weight bytes read from HBM: $200 \times 16\text{ GB} = 3{,}200\text{ GB}$ ($200\times$ more memory traffic than prefill!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: That $200\times$ bandwidth asymmetry between prefill and decode explains almost every systems innovation in Chapter 26—from GQA and KV-cache compression to speculative decoding and quantization.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;chapter-26--large-language-models&quot;&gt;Chapter 26 — Large Language Models&lt;/h1&gt;

&lt;p&gt;This chapter is the course’s &lt;strong&gt;dedicated LLM hub&lt;/strong&gt;. Earlier chapters already built the pieces: attention (Chapter 07), the Transformer block (Chapter 08), static and contextual embeddings (Chapter 18), compression (Chapter 23), and preference-based alignment as an application of RL (Chapters 20–21). What was missing is a single track that treats a &lt;strong&gt;decoder-only language model at scale&lt;/strong&gt; as the object of study — how it is pretrained, prompted, aligned, served, and distilled.&lt;/p&gt;

&lt;p&gt;Chapter 25 still surveys scaling, multimodality, and open research problems. This chapter is more concrete: it is the self-study path for &lt;em&gt;using and reasoning about&lt;/em&gt; modern LLMs without re-deriving every Transformer equation. Lesson &lt;strong&gt;26-07&lt;/strong&gt; then puts the 2024–2026 decoder block, the interview-style FLOP / memory arithmetic, and a Chinchilla-style scaling sketch in one place.&lt;/p&gt;

&lt;h2 id=&quot;why-this-chapter-exists&quot;&gt;Why this chapter exists&lt;/h2&gt;

&lt;p&gt;An LLM, in the sense used here, is a &lt;strong&gt;causal (decoder-only) Transformer language model&lt;/strong&gt; trained to predict the next token on a very large text corpus, then usually adapted so that it follows instructions and stays inside a product’s safety and style constraints.&lt;/p&gt;

&lt;p&gt;That sentence hides four design choices you should be able to name:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Decoder-only&lt;/strong&gt; — the model conditions on the left context only (causal mask). There is no separate encoder stack as in the original Vaswani encoder–decoder, though encoder–decoder LMs (T5-style) still exist.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Language model&lt;/strong&gt; — the training objective is next-token prediction, not a supervised class label.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;At scale&lt;/strong&gt; — width, depth, data, and compute are large enough that prompting and in-context learning become useful interfaces, not just curiosities.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adapted after pretraining&lt;/strong&gt; — raw next-token models complete text; products need instruction-following and preference alignment.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If you can already walk one encoder layer and one decoder step from Chapter 08, you have the architecture. This chapter answers: &lt;em&gt;what do we do with that stack when it is the product?&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;how-this-chapter-connects-to-the-rest-of-the-course&quot;&gt;How this chapter connects to the rest of the course&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Earlier chapter&lt;/th&gt;
      &lt;th&gt;What you reuse here&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;01–03, 10 Math / training&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;MLP as a batch matmul, softmax + CE gradient, Adam / AdamW — refreshed in &lt;strong&gt;26-01&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;02 Activations / MLP&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;ReLU, SiLU/Swish, SwiGLU packaging (&lt;strong&gt;02-99&lt;/strong&gt;); reused in &lt;strong&gt;26-07&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;05–06 RNN / LSTM&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Contrast with attention + growing KV state (&lt;strong&gt;26-07&lt;/strong&gt;)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;07 Attention&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Scaled dot-product, causal masks, multi-head mixing; FlashAttention / GQA in &lt;strong&gt;07-99&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08 Transformers&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Residual + norm + FFN block; RoPE / KV-cache appear in the optional 08-99 note and are derived for LMs in &lt;strong&gt;26-07&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;18 NLP / embeddings&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Token embedding table as layer 0; static vs contextual vectors; RAG is in 18-99&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;20–21 RL / deep RL&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;The RLHF &lt;em&gt;sketch&lt;/em&gt; (reward model + PPO, then DPO) — this chapter only maps the pipeline&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;23 Efficient DL&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Quantization, pruning, &lt;em&gt;classical&lt;/em&gt; knowledge distillation&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;25 Future directions&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Broader scaling and test-time compute — train-time Chinchilla sketch is in &lt;strong&gt;26-07&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Distillation is split on purpose.&lt;/strong&gt; Chapter 23 teaches teacher/student KD for a &lt;em&gt;fixed&lt;/em&gt; output space (image classes, small classifiers). Lesson &lt;strong&gt;26-05&lt;/strong&gt; is the LLM-era continuation: why logit matching is awkward for huge vocabularies, and why synthetic-data / response distillation became the default.&lt;/p&gt;

&lt;h2 id=&quot;learning-goals&quot;&gt;Learning goals&lt;/h2&gt;

&lt;p&gt;By the end of this chapter you should be able to:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Define an LLM as a scaled causal Transformer LM and contrast it with BERT-style encoders and T5-style encoder–decoders.&lt;/li&gt;
  &lt;li&gt;Explain next-token pretraining, subword tokenization, and what a context window actually limits.&lt;/li&gt;
  &lt;li&gt;Separate &lt;strong&gt;prompting / in-context learning&lt;/strong&gt; from &lt;strong&gt;parameter-updating fine-tuning&lt;/strong&gt;, and say when each is the right tool.&lt;/li&gt;
  &lt;li&gt;Sketch the alignment pipeline &lt;strong&gt;SFT → preference optimization (RLHF / DPO)&lt;/strong&gt; and know where Chapters 20–21 do the RL math.&lt;/li&gt;
  &lt;li&gt;Write the softmax + cross-entropy gradient \(\partial\mathcal{L}/\partial z = p - t\), the stable log-sum-exp, and the CE / KL / entropy relationship used as LM loss.&lt;/li&gt;
  &lt;li&gt;Name the serving knobs that matter at decode time (KV-cache, batching, speculative decoding, sampling) and decide &lt;strong&gt;when distillation is the remaining lever&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Sketch a modern decoder layer (RMSNorm → attention + RoPE → SwiGLU), give order-of-magnitude FLOPs and inference memory, and state the Chinchilla compute-optimal idea without inventing a fitted curve.&lt;/li&gt;
  &lt;li&gt;Distinguish classical KD, synthetic-data distillation, and white-box feature/logit distillation — including the legitimate vs unauthorized-use tension — without treating headlines as evidence.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;roadmap&quot;&gt;Roadmap&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Lesson&lt;/th&gt;
      &lt;th&gt;Focus&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-01 Pretraining and tokenization&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Next-token loss, softmax/CE math, AdamW, BPE / SentencePiece, context window&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-02 Prompting and in-context learning&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Zero/few-shot, instruction-following vs classical fine-tuning&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-03 Alignment sketch&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;SFT → reward model / PPO → DPO with high-level objectives; pointer to Ch.20–21&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-04 Serving and efficiency&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;KV-cache, batching, speculative decoding, sampling, when to distill&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-05 Model distillation for LLMs&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Core KD refresh + modern LLM families + a small code sketch&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-07 Internals and accounting&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;RMSNorm / SwiGLU / RoPE, FlashAttention narrative, FLOPs / memory, scaling, parallelism&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;26-06 Interviews practice&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Optional original discussion prompts (not a reprint of any book)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Chapter 07–08 (attention + Transformer layer, causal mask)&lt;/li&gt;
  &lt;li&gt;Softmax as a categorical distribution; cross-entropy as negative log-likelihood (Chapter 03)&lt;/li&gt;
  &lt;li&gt;A conceptual picture of embeddings (Chapter 18)&lt;/li&gt;
  &lt;li&gt;Optional but helpful: Chapter 23 compression; Chapter 21-99 for DPO / RLHF&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;mental-model&quot;&gt;Mental model&lt;/h2&gt;

&lt;p&gt;Think of a deployed LLM as &lt;strong&gt;four stacked adaptations of the same decoder&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Pretrain&lt;/strong&gt; — learn \(p(x_t \mid x_{&amp;lt;t})\) on broad text.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adapt the interface&lt;/strong&gt; — prompts, few-shot exemplars, and (usually) supervised instruction data.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adapt the preferences&lt;/strong&gt; — human or AI pairwise feedback, not just “next token on the web.”&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adapt the cost&lt;/strong&gt; — cache, quantize, batch, or &lt;strong&gt;distill&lt;/strong&gt; into a smaller student so the capability is cheaper to serve.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When you can tell which layer a technique lives on, the rest of the chapter is bookkeeping.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (interview practice):&lt;/strong&gt; After the distillation and internals lessons, see &lt;strong&gt;26-06 Interviews Practice&lt;/strong&gt; for original prompts. The course-wide map remains &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;further-reading-inspiration-not-a-source-text&quot;&gt;Further reading (inspiration, not a source text)&lt;/h2&gt;

&lt;p&gt;Public study notes that motivated the &lt;em&gt;topic map&lt;/em&gt; of &lt;strong&gt;26-01&lt;/strong&gt;, &lt;strong&gt;26-03&lt;/strong&gt;, &lt;strong&gt;26-04&lt;/strong&gt;, and &lt;strong&gt;26-07&lt;/strong&gt;. The prose and diagrams in this chapter are course-written; do not treat the notes as a text to quote.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Alisa Liu, &lt;a href=&quot;https://alisawuffles.notion.site/alisa-s-book-of-llms&quot;&gt;Alisa’s Book of LLMs&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;Alisa Liu, &lt;a href=&quot;https://alisawuffles.notion.site/math-notes&quot;&gt;Math notes&lt;/a&gt; (Notion SPA; the page may render empty via a plain fetch — the URL is still the pointer).&lt;/li&gt;
  &lt;li&gt;Primary papers used in the hub: &lt;a href=&quot;https://arxiv.org/abs/2001.08361&quot;&gt;Kaplan et al., 2020&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Hoffmann et al., 2022&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Ouyang et al., 2022&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Rafailov et al., 2023&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;Dao et al., 2022&lt;/a&gt;; &lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Leviathan et al., 2023&lt;/a&gt;. Full lists sit at the end of &lt;strong&gt;26-03&lt;/strong&gt;, &lt;strong&gt;26-04&lt;/strong&gt;, and &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, English. What a large language model is, matching this hub’s opening map.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=LPZh9BOjkQs&quot;&gt;Large Language Models explained briefly&lt;/a&gt; — 3Blue1Brown, English. The same map, if you want the outline before the full talk.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=7xTGNNLPyMI&quot;&gt;Deep Dive into LLMs like ChatGPT&lt;/a&gt; — Andrej Karpathy, English. The long 2025 walk through pretraining, alignment, and inference. Use it as the hub’s overview, not as a single sitting for one lesson.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>25-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter25/25_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter25/25_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;For five years, the scaling game had only one lever: make pretraining bigger. Between 2024 and 2026, a second axis broke wide open—&lt;strong&gt;test-time compute scaling&lt;/strong&gt;: letting a reasoning model spend extra thinking tokens, verify intermediate steps, call external tools (code interpreters, search, APIs), and process native images/audio in a single unified stream. Meanwhile, real-world energy and water constraints turned compute efficiency from an academic footnote into a first-class systems requirement.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-what-shipped-at-the-frontier-20222026&quot;&gt;Key ideas: What Shipped at the Frontier (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Test-Time Compute Scaling&lt;/strong&gt;: Trades extra inference tokens (long chains of thought, best-of-$N$ verifier search, tree search) for dramatic gains on math, coding, and planning—complementing pretraining scaling.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Tool-Using Agent Loops&lt;/strong&gt;: Connects LLM reasoning to deterministic external execution (Python sandboxes, SQL, browsers, MCP tools) via structured observe–think–act–verify loops.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Native Multimodal Architectures&lt;/strong&gt;: Tokenizes text, image patches, audio frames, and video clips into one shared Transformer backbone instead of bolting fragile adapters onto a text-only LLM.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Energy, Cost, and Routing Constraints&lt;/strong&gt;: Uses model routing (small fast models for easy queries, large reasoning models for hard ones) and batching to bound carbon footprint and serving cost.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-passk--best-of-n-test-time-compute-trade-off&quot;&gt;Worked example: Pass@$k$ / Best-of-$N$ Test-Time Compute Trade-off&lt;/h3&gt;

&lt;p&gt;Suppose on a hard coding problem, a single sample from a small model succeeds with independent probability $p = 0.25$ and costs $c = $0.001$ per attempt, and we have a unit-test suite that verifies correctness with $100\%$ precision.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Probability that at least 1 of $N$ independent samples passes (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pass@N&lt;/code&gt;)&lt;/strong&gt;:
\(\text{pass@}N = 1 - (1 - p)^N.\)
    &lt;ul&gt;
      &lt;li&gt;$N = 1$: $25.0\%$ (cost $$0.001$).&lt;/li&gt;
      &lt;li&gt;$N = 4$: $1 - (0.75)^4 = 1 - 0.3164 = 68.4\%$ (cost $$0.004$).&lt;/li&gt;
      &lt;li&gt;$N = 8$: $1 - (0.75)^8 = 1 - 0.1001 = 90.0\%$ (cost $$0.008$).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare against a $10\times$ larger model&lt;/strong&gt; that achieves $85\%$ on a single pass at cost $$0.015$:
Spending $8\times$ test-time compute on the small model reaches &lt;strong&gt;higher accuracy ($90.0\%$ vs. $85.0\%$)&lt;/strong&gt; at almost &lt;strong&gt;half the dollar cost ($$0.008$ vs. $$0.015$)&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Whenever a reliable verifier exists (unit tests, compilers, formal proof checkers), test-time compute scaling can beat brute-force parameter scaling on both accuracy and cost.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-what-actually-shipped--test-time-compute-agents-multimodal&quot;&gt;Optional: what actually shipped — test-time compute, agents, multimodal&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; rewrite the chapter’s scaling-law / multimodal / safety survey. That note already looks forward; this lesson lists &lt;strong&gt;concrete 2024–2026 deployments&lt;/strong&gt; so the “future” section stays tied to systems you can run.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The core chapter’s power-law&lt;/p&gt;

\[L \propto N^{-\alpha}\]

&lt;p&gt;still describes pretraining. The new industrial knob is &lt;strong&gt;test-time compute&lt;/strong&gt;: spend more FLOPs &lt;em&gt;per query&lt;/em&gt;.&lt;/p&gt;

&lt;h2 id=&quot;1-inference-time-scaling&quot;&gt;1. Inference-time scaling&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://openai.com/index/learning-to-reason-with-llms/&quot;&gt;OpenAI o1&lt;/a&gt; (2024) and follow-on reasoning models (DeepSeek-R1-class, 2025) train models to emit long chains of thought and search. Empirically, accuracy can scale with extra samples or longer traces, closer to&lt;/p&gt;

\[\text{error} \approx c \cdot C_{\mathrm{test}}^{-\gamma}\]

&lt;p&gt;than to a bigger pretrained \(N\) alone (&lt;a href=&quot;https://arxiv.org/abs/2408.03314&quot;&gt;Snell et al., 2024&lt;/a&gt;, “Scaling LLM Test-Time Compute”). This is complementary to Chinchilla’s &lt;em&gt;train&lt;/em&gt;-time scaling (Chapter 00/01 optional).&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;tool-using-agents&quot;&gt;Tool-using agents&lt;/h3&gt;

&lt;p&gt;Production “agents” (2024–2026) are loops: LM → tool (SQL, browser, code) → observation. Software: &lt;a href=&quot;https://platform.openai.com&quot;&gt;OpenAI Agents / Responses tools&lt;/a&gt;, &lt;a href=&quot;https://github.com/langchain-ai/langgraph&quot;&gt;LangGraph&lt;/a&gt;, &lt;a href=&quot;https://github.com/huggingface/smolagents&quot;&gt;smolagents&lt;/a&gt;. The research risk is still reliability, not a new neuron.&lt;/p&gt;

&lt;h3 id=&quot;native-multimodal&quot;&gt;Native multimodal&lt;/h3&gt;

&lt;p&gt;GPT-4V-class, Gemini, and open VLMs (LLaVA, Qwen2-VL, PaliGemma) take images/audio in one stack. The chapter’s CLIP/Flamingo pointer was the research seed; these are the APIs.&lt;/p&gt;

&lt;h3 id=&quot;sustainability-as-a-constraint&quot;&gt;Sustainability as a constraint&lt;/h3&gt;

&lt;p&gt;Serving 70B models for every click is not a “future problem”: quantization (Chapter 23 optional), routing to small models, and batching are the deployed answers to the chapter’s energy paragraph.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt; / &lt;a href=&quot;https://github.com/sgl-project/sglang&quot;&gt;SGLang&lt;/a&gt; — high-throughput + speculative / structured decode.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/transformers&quot;&gt;huggingface/transformers&lt;/a&gt; reasoning-model cards (DeepSeek-R1 distillations, etc.).&lt;/li&gt;
  &lt;li&gt;Open evaluation: &lt;a href=&quot;https://github.com/EleutherAI/lm-evaluation-harness&quot;&gt;lm-evaluation-harness&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2408.03314&quot;&gt;Scaling LLM Test-Time Compute Optimally (Snell et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2501.12948&quot;&gt;DeepSeek-R1 (DeepSeek-AI, 2025)&lt;/a&gt; — large-scale reasoning with RL (see Chapter 21 optional).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.08485&quot;&gt;Visual Instruction Tuning — LLaVA (Liu et al., 2023)&lt;/a&gt; — the open VLM recipe widely copied in 2024–2026.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Keep the chapter’s discussion of scaling, NAS, continual learning, and safety. This lesson only pins &lt;strong&gt;test-time compute, agents, and open VLMs&lt;/strong&gt; as the items that moved from “future” to “default product” between 2024 and 2026.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=7xTGNNLPyMI&quot;&gt;Deep Dive into LLMs like ChatGPT&lt;/a&gt; — Andrej Karpathy, English. Karpathy’s 2025 deep dive includes inference-time reasoning, the knob this note adds on top of pretraining. It is long and canonical.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PZXN7jm9IC0&quot;&gt;Chinchilla Explained: Compute-Optimal Massive Language Models&lt;/a&gt; — Edan Meyer, English. Chinchilla is the train-time law the note says test-time compute does not replace.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=N1fbskTpwZ0&quot;&gt;MIT 6.S191 (2024): Language Models and New Frontiers&lt;/a&gt; — Alexander Amini, English. The 2024 frontier lecture for agents and multimodal systems the note lists next.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>25-98 Interviews Practice (Bayesian and uncertainty)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter25/25_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter25/25_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Feed a standard ImageNet classifier a photo of pure TV static, and it will happily declare &lt;em&gt;“99.4% confident: toaster.”&lt;/em&gt; That dangerous overconfidence is why senior ML interviews probe Bayesian Deep Learning and uncertainty quantification: can you distinguish irreducible data noise (&lt;em&gt;aleatoric&lt;/em&gt;) from model ignorance (&lt;em&gt;epistemic&lt;/em&gt;), show why L2 weight decay is secretly a Gaussian prior, and estimate predictive uncertainty cheaply with Monte Carlo Dropout?&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-bayesian-deep-learning--uncertainty-quantification&quot;&gt;Key ideas: Bayesian Deep Learning &amp;amp; Uncertainty Quantification&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Aleatoric vs. Epistemic Uncertainty&lt;/strong&gt;: Separates irreducible observation noise in $p(y \mid x)$ (unreducible even with infinite data) from parameter uncertainty in $p(\theta \mid \mathcal{D})$ (which shrinks as you gather more data).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — MAP Estimation &amp;amp; Regularization Duality&lt;/strong&gt;: Proves that minimizing $\text{NLL} + \lambda |\theta|_2^2$ is mathematically identical to Maximum A Posteriori (MAP) inference under an isotropic Gaussian prior $\theta \sim \mathcal{N}(0, \sigma_0^2 I)$, while L1 corresponds to a Laplace prior.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Point Estimates vs. Posterior Predictive Marginalization&lt;/strong&gt;: Explains why a single MAP weight $\hat{\theta}$ extrapolates linearly with unbounded logits far from training data, whereas averaging $p(y \mid x, \mathcal{D}) = \int p(y \mid x, \theta)p(\theta \mid \mathcal{D})\,d\theta$ moderates confidence.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Practical Approximations (MC Dropout &amp;amp; Deep Ensembles)&lt;/strong&gt;: Runs $T$ stochastic forward passes with dropout active at test time (or averages $M$ independently trained models) to decompose total predictive variance.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-decomposing-predictive-uncertainty-via-mc-dropout&quot;&gt;Worked example: Decomposing Predictive Uncertainty via MC Dropout&lt;/h3&gt;

&lt;p&gt;Suppose we run $T = 4$ stochastic MC Dropout forward passes on an out-of-distribution image for a binary classifier, obtaining predicted probabilities $p^{(t)} = [0.90,\; 0.10,\; 0.80,\; 0.20]$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Predictive mean probability&lt;/strong&gt;:
\(\bar{p} = \frac{0.90 + 0.10 + 0.80 + 0.20}{4} = 0.50.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Total predictive entropy $H(\bar{p})$&lt;/strong&gt;:
\(H(0.50) = -0.5\ln(0.5) - 0.5\ln(0.5) = 0.6931\text{ nats (maximum uncertainty!)}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Expected individual entropy (Aleatoric component) $\frac{1}{T}\sum_t H(p^{(t)})$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;$H(0.90) = H(0.10) = -0.9\ln(0.9) - 0.1\ln(0.1) = 0.3251\text{ nats}$.&lt;/li&gt;
      &lt;li&gt;$H(0.80) = H(0.20) = -0.8\ln(0.8) - 0.2\ln(0.2) = 0.5004\text{ nats}$.&lt;/li&gt;
      &lt;li&gt;Mean aleatoric entropy $= \frac{0.3251 + 0.3251 + 0.5004 + 0.5004}{4} = 0.4128\text{ nats}$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mutual Information (Epistemic uncertainty)&lt;/strong&gt;:
\(I(y; \theta \mid x, \mathcal{D}) = H(\bar{p}) - \mathbb{E}[H(p^{(t)})] = 0.6931 - 0.4128 = 0.2803\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Individual passes look confident ($0.90$ vs. $0.10$), yet they wildly disagree—producing a high epistemic Mutual Information score ($0.280$ nats) that cleanly flags the input as out-of-distribution.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-interview-practice--bayesian-deep-learning-and-uncertainty&quot;&gt;Optional: interview practice — Bayesian deep learning and uncertainty&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; rewrite the chapter’s survey of future directions. After that survey (and the probability notes in Chapter 00), use this drill, then open &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for solved items on probabilistic programming and Bayesian deep learning.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Book themes for this chapter (study in the PDF, not here):&lt;/strong&gt; Bayesian reasoning, priors / posteriors at a conceptual level, and uncertainty in deep models. There is no dedicated Bayesian chapter in this course; Chapter 25 is the advanced-topics home.&lt;/p&gt;

&lt;p&gt;Hub: &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;practice-prompts-original&quot;&gt;Practice prompts (original)&lt;/h2&gt;

&lt;h3 id=&quot;q1-two-uncertainties&quot;&gt;Q1. Two uncertainties&lt;/h3&gt;

&lt;p&gt;A medical model outputs \(p(\text{disease}=1\mid\mathbf{x})=0.51\). Give one story in which that number is &lt;em&gt;aleatoric&lt;/em&gt; and one in which it is &lt;em&gt;epistemic&lt;/em&gt;. What extra experiment would distinguish them?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Aleatoric: noise that remains with infinite data. Epistemic: shrinks if you collect more relevant labels.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Aleatoric: the image is genuinely ambiguous (motion blur, two overlapping findings); more training data of the same kind will not push the probability to 0 or 1. Epistemic: this scanner / hospital is new and the weights are under-determined; more in-domain labels or a better prior should concentrate the posterior. Repeating the forward pass with MC dropout or deep ensembles (below) changes little in the first story and a lot in the second.&lt;/p&gt;

&lt;h3 id=&quot;q2-l2-as-a-gaussian-prior&quot;&gt;Q2. L2 as a Gaussian prior&lt;/h3&gt;

&lt;p&gt;Show that maximizing \(p(\mathbf{w}\mid\mathcal{D}) \propto p(\mathcal{D}\mid\mathbf{w})\,p(\mathbf{w})\) with \(p(\mathbf{w})=\mathcal{N}(\mathbf{0},\lambda^{-1}I)\) and a Gaussian observation model is (up to constants) the same as minimizing MSE plus \(\frac{\lambda}{2}\|\mathbf{w}\|_2^2\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Take \(-\log\) of the posterior; the prior contributes a quadratic.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; \(-\log p(\mathbf{w}) = \frac{\lambda}{2}\|\mathbf{w}\|_2^2 + \mathrm{const}\). Under a Gaussian likelihood, \(-\log p(\mathcal{D}\mid\mathbf{w})\) is MSE (or a scaled square loss). So MAP with that prior &lt;em&gt;is&lt;/em&gt; L2-regularized regression. This is the bridge from Chapter 00 / 09 to “Bayesian language.” It does &lt;strong&gt;not&lt;/strong&gt; by itself give you error bars — MAP is still a point.&lt;/p&gt;

&lt;h3 id=&quot;q3-why-a-point-estimate-net-looks-overconfident&quot;&gt;Q3. Why a point-estimate net looks overconfident&lt;/h3&gt;

&lt;p&gt;A softmax trained with CE on a clean set assigns \(0.99\) to the wrong class on an OOD input. In Bayesian language, what did the training procedure throw away?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; You optimized \(\mathbf{w}_{\mathrm{MAP}}\) (or a SGD point) and then treated \(p(y\mid\mathbf{x},\mathbf{w}_{\mathrm{MAP}})\) as \(p(y\mid\mathbf{x},\mathcal{D})\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; The predictive distribution should integrate \(p(y\mid\mathbf{x},\mathbf{w})\) against \(p(\mathbf{w}\mid\mathcal{D})\). A single \(\mathbf{w}\) ignores disagreement among weight settings that all fit the training set. On OOD \(\mathbf{x}\), that disagreement is often large, so the mixture is closer to uniform than any one sharp softmax. Temperature scaling can fix &lt;em&gt;in-domain&lt;/em&gt; calibration without being Bayesian; it will not systematically fix OOD.&lt;/p&gt;

&lt;h3 id=&quot;q4-mc-dropout-as-a-cheap-posterior-sketch&quot;&gt;Q4. MC dropout as a cheap posterior sketch&lt;/h3&gt;

&lt;p&gt;You run the same dropout network \(T=20\) times at test time and average the softmaxes. What Bayesian object is this approximating &lt;em&gt;informally&lt;/em&gt;, and name one thing it is not?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Each mask is a different function; the average is a mixture.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Informally it is a mixture predictive \(\frac1T\sum_t p(y\mid\mathbf{x},\mathbf{w}\odot m_t)\), sometimes motivated as variational inference over dropout masks. It is &lt;strong&gt;not&lt;/strong&gt; a guarantee that the mixture matches the true posterior, and it is not free: you pay \(T\) forwards. Deep ensembles (several independently trained nets) are a competing sketch; they live on the hub’s ensemble note, not in a new chapter.&lt;/p&gt;

&lt;h3 id=&quot;q5-a-prior-you-can-defend&quot;&gt;Q5. A prior you can defend&lt;/h3&gt;

&lt;p&gt;You must put a prior on a bias parameter in a well-specified logistic model (Chapter 03). Why is \(\mathcal{N}(0,10^2)\) often more defensible than a point-mass at \(0\), and when would you &lt;em&gt;not&lt;/em&gt; want a huge variance?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; A Dirac at 0 is “I already know the intercept.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; A wide Gaussian says “the intercept is unknown but not insane.” A hard zero forces the decision boundary through a particular log-odds when features are zero — a strong scientific claim. Huge variance is a problem if the feature coding is arbitrary (unstandardized inputs): the prior then depends on units. Hierarchical / weakly informative priors belong in the book’s Bayesian chapters; here the course-level point is that “I used the default” is still a prior.&lt;/p&gt;

&lt;h2 id=&quot;attribution&quot;&gt;Attribution&lt;/h2&gt;

&lt;p&gt;Kashani, S., and Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Download the PDF from arXiv for the full solved Q&amp;amp;A. This page is original course practice, not a reprint.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=j4yxsEQqPMI&quot;&gt;MaDL - Bayesian Decision Theory&lt;/a&gt; — Tübingen Machine Learning, English. Bayesian decisions are this practice set’s theme.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Bayes’ theorem, the identity those prompts start from.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vPvnpC0PNVQ&quot;&gt;MaDL - Kullback-Leibler Divergence&lt;/a&gt; — Tübingen Machine Learning, English. KL divergence, the uncertainty comparison the prompts often ask for.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>25-01 Future Directions in Deep Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter25/25_01_Future_Directions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter25/25_01_Future_Directions</id>
   <content type="html">&lt;p&gt;As deep learning matures from isolated benchmarks into general-purpose infrastructure, three deep mathematical questions define the research frontier: how far do power-law scaling curves extend, how can a network adapt to a brand-new task from 5 examples without erasing prior skills, and how do we optimize conflicting real-world objectives (accuracy, fairness, latency, safety) simultaneously? Each question turns out to have a crisp mathematical formulation you can test in twenty lines of code.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mathematical-core-of-emerging-deep-learning-paradigms&quot;&gt;Key ideas: Mathematical Core of Emerging Deep Learning Paradigms&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Power-Law Scaling &amp;amp; Irreducible Entropy&lt;/strong&gt;: Models test loss as $L(N, D) = E + \frac{A}{N^\alpha} + \frac{B}{D^\beta}$, separating reducible capacity/data error from the irreducible entropy floor $E$ of natural language.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Bi-Level Meta-Learning (MAML) &amp;amp; Metric Few-Shot&lt;/strong&gt;: Finds an initialization $\theta^*$ such that just 1–5 gradient steps on a new task $\mathcal{T}_i$ yield strong generalization, or classifies queries by distance to class prototypes in embedding space.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Continual Learning &amp;amp; Fisher Information (EWC)&lt;/strong&gt;: Protects parameters vital to Task A when learning Task B by adding a quadratic penalty $\frac{\lambda}{2}\sum_i F_i (\theta_i - \theta_{A,i}^*)^2$ weighted by the diagonal Fisher Information Matrix $F_i$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Multi-Objective Optimization &amp;amp; Pareto Fronts&lt;/strong&gt;: Balances competing objectives (engagement vs. diversity vs. safety) using Pareto-optimal trade-offs rather than myopic single-metric maximization.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-an-elastic-weight-consolidation-ewc-penalty&quot;&gt;Worked example: Computing an Elastic Weight Consolidation (EWC) Penalty&lt;/h3&gt;

&lt;p&gt;Suppose after mastering Task A, a model has two weights $\theta_A^* = (2.0,\; 1.0)$ with diagonal Fisher sensitivities $F = (10.0,\; 0.5)$ (meaning $\theta_1$ is $20\times$ more critical to Task A than $\theta_2$). While training on Task B with EWC strength $\lambda = 2.0$, we test two candidate updates of identical Euclidean length ($0.5$):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Candidate 1&lt;/strong&gt; (moves important weight $\theta_1$): $\theta^{(1)} = (2.5,\; 1.0)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Candidate 2&lt;/strong&gt; (moves flexible weight $\theta_2$): $\theta^{(2)} = (2.0,\; 1.5)$.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute EWC penalty $\Omega(\theta) = \frac{\lambda}{2}\big[F_1(\theta_1 - \theta_{A,1}^&lt;em&gt;)^2 + F_2(\theta_2 - \theta_{A,2}^&lt;/em&gt;)^2\big]$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Candidate 1: $\frac{2.0}{2}\big[10.0(0.5)^2 + 0.5(0)^2\big] = 10.0 \times 0.25 = 2.500$.&lt;/li&gt;
      &lt;li&gt;Candidate 2: $\frac{2.0}{2}\big[10.0(0)^2 + 0.5(0.5)^2\big] = 0.5 \times 0.25 = 0.125$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare&lt;/strong&gt;: Moving $\theta_1$ incurs a $20\times$ stiffer penalty ($2.500$ vs. $0.125$), steering Task B’s optimizer to store new knowledge inside the underused weight $\theta_2$ while leaving Task A intact!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: EWC turns catastrophic forgetting into a clean geometric constraint using second-order curvature (Fisher information) as an anchor.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;the-future-of-deep-learning-emerging-trends-and-open-challenges&quot;&gt;The Future of Deep Learning: Emerging Trends and Open Challenges&lt;/h1&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Deep learning has achieved remarkable success over the past decade, yet we stand at the beginning rather than the end of its potential impact. While current systems excel at specific tasks with abundant data and computation, numerous fundamental challenges remain unsolved and exciting directions are emerging. Understanding these frontiers—both technical challenges and promising approaches—prepares practitioners and researchers to contribute to the field’s continued evolution and helps anticipate how AI capabilities will expand in coming years.&lt;/p&gt;

&lt;p&gt;The scaling hypothesis has driven much recent progress: larger models trained on more data with more compute consistently improve performance, with no clear ceiling yet observed. GPT-3’s 175 billion parameters exceeded GPT-2’s 1.5 billion by 100×, producing qualitatively new capabilities like few-shot learning. Yet scaling raises critical questions: Is this trend sustainable given energy costs and data availability? Do we hit fundamental limits or discover emergent capabilities? How do we train and serve models orders of magnitude larger? Understanding scaling’s promises and limitations shapes expectations for AI’s trajectory.&lt;/p&gt;

&lt;p&gt;Multimodal learning—systems processing multiple modalities (vision, language, audio) together—represents a crucial frontier because human intelligence is inherently multimodal. Models like CLIP (learning from image-text pairs) and GPT-4 (processing both text and images) demonstrate that multimodal pre-training enables rich cross-modal understanding: describing images, answering visual questions, generating images from text descriptions. Future systems will likely be inherently multimodal, learning unified representations spanning modalities much as humans seamlessly integrate sight, sound, and language.&lt;/p&gt;

&lt;p&gt;Efficiency and sustainability emerge as critical concerns as models grow. Training GPT-3 reportedly consumed hundreds of thousands of dollars in compute and substantial carbon emissions. Democratizing AI requires techniques making advanced capabilities accessible beyond tech giants: efficient architectures, better algorithms requiring less data or compute, knowledge distillation from large to small models, and specialized hardware. Understanding the efficiency frontier—how to maximize capabilities per unit computation—will increasingly matter as AI deployment scales.&lt;/p&gt;

&lt;p&gt;Safety, robustness, and alignment represent perhaps the most important challenges. Current systems can be brittle (failing unpredictably on out-of-distribution inputs), biased (reflecting and amplifying societal biases in training data), and misaligned (optimizing objectives that don’t match true human values). As AI systems become more capable and deployed in critical applications, ensuring they behave reliably and beneficially becomes paramount. Research on adversarial robustness, fairness, interpretability, and value alignment will be crucial for responsible AI development.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;h3 id=&quot;scaling-laws&quot;&gt;Scaling Laws&lt;/h3&gt;

&lt;p&gt;Empirical observations suggest power-law relationships between model performance and scale:&lt;/p&gt;

\[L \propto N^{-\alpha}\]

&lt;p&gt;where \(L\) is loss, \(N\) is number of parameters (or data size, or compute), and \(\alpha\) is a constant (typically 0.05-0.1). This implies diminishing returns: doubling parameters might reduce loss by 5-10%, requiring exponentially more parameters for linear loss improvements. Yet the relationship is surprisingly consistent across architectures and domains, suggesting fundamental regularities in how neural networks learn.&lt;/p&gt;

&lt;p&gt;The compute-optimal frontier trades off model size and training data:&lt;/p&gt;

\[N_{\text{optimal}} \propto C^{0.5}, \quad D_{\text{optimal}} \propto C^{0.5}\]

&lt;p&gt;where \(C\) is compute budget, \(N\) is parameters, \(D\) is training tokens. This suggests optimal use of compute equally balances model size and data quantity, informing how to allocate resources when scaling.&lt;/p&gt;

&lt;h3 id=&quot;few-shot-learning&quot;&gt;Few-Shot Learning&lt;/h3&gt;

&lt;p&gt;Meta-learning formalizes learning from few examples. Given task distribution \(p(\mathcal{T})\), learn initialization \(\theta_0\) that adapts quickly:&lt;/p&gt;

\[\theta_0 = \arg\min_\theta \mathbb{E}_{\mathcal{T} \sim p(\mathcal{T})}\left[\mathcal{L}_\mathcal{T}(\theta - \alpha \nabla_\theta \mathcal{L}_\mathcal{T}(\theta))\right]\]

&lt;p&gt;MAML learns \(\theta_0\) such that one gradient step on new task yields good performance. This enables rapid adaptation with minimal data.&lt;/p&gt;

&lt;h3 id=&quot;continual-learning&quot;&gt;Continual Learning&lt;/h3&gt;

&lt;p&gt;Learning new tasks without forgetting old ones requires balancing plasticity (learning new) and stability (retaining old). Elastic Weight Consolidation penalizes changes to parameters important for previous tasks:&lt;/p&gt;

\[\mathcal{L}_{\text{EWC}} = \mathcal{L}_{\text{new}} + \sum_i \frac{\lambda}{2} F_i (\theta_i - \theta_i^*)^2\]

&lt;p&gt;where \(F_i\) is Fisher information (second derivative of old task loss), \(\theta_i^*\) are parameters after learning old tasks. This allows learning new tasks while protecting parameters critical for old tasks.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Consider the progression from GPT-2 (1.5B parameters) to GPT-3 (175B parameters) to GPT-4 (rumored 1.7T parameters). Each scaling step enabled new capabilities:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GPT-2&lt;/strong&gt;: Coherent text generation, basic completion&lt;br /&gt;
&lt;strong&gt;GPT-3&lt;/strong&gt;: Few-shot learning, simple reasoning, basic coding&lt;br /&gt;
&lt;strong&gt;GPT-4&lt;/strong&gt;: Complex reasoning, multimodal understanding, sophisticated coding&lt;/p&gt;

&lt;p&gt;These aren’t just quantitative improvements but qualitative capability changes. GPT-3 could follow instructions it wasn’t explicitly trained on. GPT-4 can reason about images. These emergent abilities—capabilities that appear suddenly at certain scales—suggest scaling might continue yielding surprises.&lt;/p&gt;

&lt;p&gt;Multimodal learning enables novel applications. DALL-E generates images from text: “an astronaut riding a horse in photorealistic style.” The model must understand both language (parsing the description) and vision (what astronauts and horses look like, what photorealistic means) and the mapping between them (how linguistic concepts translate to visual features). Future systems might seamlessly process video, audio, and text together, much closer to human-like perception.&lt;/p&gt;

&lt;h3 id=&quot;recommendation-systems-multi-objective-optimization--responsibility&quot;&gt;Recommendation systems: multi-objective optimization &amp;amp; responsibility&lt;/h3&gt;

&lt;p&gt;Short-video platforms show that AI “alignment” is not only about chatbots: every feed swipe is a decision optimizing many metrics at once (watch time, engagement, topic diversity, safety, ad revenue…). That is &lt;strong&gt;multi-objective optimization&lt;/strong&gt; — there is no single loss.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter25/recsys_multi_objective.jpg&quot; alt=&quot;Multi-objective tradeoffs&quot; /&gt;
&lt;em&gt;Figure: Feed ranking must balance many objectives simultaneously, not a single metric. (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Related challenges:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Filter bubbles / echo chambers&lt;/strong&gt; — pure engagement optimization narrows a user’s world&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Feedback loops&lt;/strong&gt; — models amplify past behavior, further skewing future data&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Value alignment&lt;/strong&gt; — “maximize time spent” can conflict with digital wellbeing / information diversity&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Future directions (fairness, diversity constraints, causal recsys, human-in-the-loop) sit at the intersection of scaling, alignment, and production ML systems — not only “train a higher-accuracy model.”&lt;/p&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Few-shot learning example
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;FewShotLearner&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Meta-learning for few-shot classification.
    
    Learns from episodes: each episode has support set (few examples)
    and query set (test examples). Model learns to adapt quickly
    to new classes from few examples.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Feature extractor
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Classifier (dynamically created for each episode)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Placeholder
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;adapt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;support_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;support_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_steps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Adapt to new task from support set.
        
        Creates and trains task-specific classifier on few examples.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Extract features from support set
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;support_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;support_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Create and train task-specific classifier
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;support_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;task_classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;support_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;task_classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Quick adaptation
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_steps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;task_classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;support_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;support_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;task_classifier&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Few-Shot Learning: Rapid Adaptation to New Tasks&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Meta-learning enables learning from few examples (5-10 per class)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;by learning how to learn quickly across many related tasks.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This is crucial for data-scarce domains!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Neuromorphic computing and brain-inspired architectures suggest radically different approaches. Spiking neural networks process discrete events (spikes) rather than continuous values, potentially more efficient and biologically plausible. Hardware specialized for neural computation (TPUs, neuromorphic chips) co-designs algorithms and hardware for efficiency.&lt;/p&gt;

&lt;p&gt;Quantum machine learning explores quantum computing for ML, potentially offering exponential speedups for certain operations. While mostly theoretical currently, quantum advantage for specific ML tasks might emerge as quantum hardware matures.&lt;/p&gt;

&lt;p&gt;Neural architecture search automated architecture design, discovering novel architectures (EfficientNet, NAS-derived networks) that humans might not conceive. Future: AI designing AI systems, co-evolving architectures and training procedures.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;“Attention is All You Need” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Transformers’ impact continues growing—foundation for GPT, BERT, essentially all modern LLMs. Understanding Transformers is understanding the future of deep learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2103.00020&quot;&gt;“CLIP: Learning Transferable Visual Models From Natural Language Supervision” (2021)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Alec Radford, Jong Wook Kim, et al. (OpenAI)&lt;br /&gt;
CLIP learned vision-language representations from 400M image-text pairs, enabling zero-shot image classification through text prompts. Demonstrated multimodal pre-training’s power and flexible task specification through natural language.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;“An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale” (2021)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Vision Transformers showed attention-based architectures can match or exceed CNNs on vision, suggesting Transformers might become universal architecture across modalities.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;“Training Compute-Optimal Large Language Models” (2022)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Jordan Hoffmann, Sebastian Borgeaud, et al. (DeepMind)&lt;br /&gt;
Chinchilla paper showed most LLMs undertrained—optimal scaling balances model size and data. Influenced how we think about scaling laws and resource allocation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.12712&quot;&gt;“Sparks of Artificial General Intelligence: Early experiments with GPT-4” (2023)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Microsoft Research&lt;br /&gt;
Analyzed GPT-4’s capabilities across diverse tasks, documenting emergent abilities suggesting progress toward more general intelligence. While controversial, highlights rapid capability advancement.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;Overhyping near-term capabilities while underestimating long-term potential is common. Current systems have significant limitations (no common sense, brittle reasoning, data inefficiency) that won’t be solved next year. Yet long-term progress (10-20 years) might be more dramatic than currently imaginable.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Deep learning’s future involves scaling to larger models discovering emergent capabilities, multimodal systems integrating vision-language-audio for richer understanding, efficiency innovations enabling democratized access despite growing model size, few-shot and meta-learning reducing data requirements, continual learning enabling lifelong learning without forgetting, and fundamental research on robustness, fairness, and alignment ensuring beneficial deployment. Open challenges include sample efficiency (learning from less data), reasoning and common sense (beyond pattern matching), interpretability (understanding decisions), robustness (handling distribution shift), and scalability (training and serving ever-larger models). The field progresses through parallel advances in architectures (Transformers), training techniques (self-supervised learning), applications (multimodal models), and theory (understanding why deep learning works), with breakthrough innovations often coming from unexpected directions. Understanding current frontiers and open problems prepares practitioners to contribute to deep learning’s continued evolution while maintaining realistic expectations about near-term capabilities and long-term potential.&lt;/p&gt;

&lt;p&gt;The future of deep learning will be shaped by technical innovations, computational advances, and thoughtful consideration of societal impacts, requiring both ambitious research pushing capabilities forward and careful work ensuring systems benefit humanity.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1444915507374636&quot;&gt;Recommendation algorithms (TikTok-style)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PZXN7jm9IC0&quot;&gt;Chinchilla Explained: Compute-Optimal Massive Language Models&lt;/a&gt; — Edan Meyer, English. Compute-optimal scaling is the power-law section of this lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=N1fbskTpwZ0&quot;&gt;MIT 6.S191 (2024): Language Models and New Frontiers&lt;/a&gt; — Alexander Amini, English. Multimodal models and open problems, the rest of the lesson’s survey.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=LPZh9BOjkQs&quot;&gt;Large Language Models explained briefly&lt;/a&gt; — 3Blue1Brown, English. A short picture of the language models the scaling section is about.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>25 Advanced Topics and Future Directions</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter25/25_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter25/25_00_Introduction</id>
   <content type="html">&lt;p&gt;Ten years ago, deep learning was a collection of siloed specialists—one CNN for vision, one RNN for text, one policy network for games—each needing tens of thousands of labeled examples and forgetting everything the moment you trained it on a second task. The frontier of deep learning pushes past every one of those walls: unified multimodal models, meta-learning from a handful of shots, continual learning without catastrophic forgetting, privacy-preserving federated training, and empirical scaling laws that predict intelligence as a function of compute.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-frontier-research-directions-in-deep-learning&quot;&gt;Key ideas: Frontier Research Directions in Deep Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Empirical Scaling Laws&lt;/strong&gt;: Quantifies how cross-entropy loss decays smoothly as a power law in parameter count $N$, dataset tokens $D$, and compute $C$ (Kaplan / Chinchilla), guiding billion-dollar training runs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Multimodal Fusion &amp;amp; Grounding&lt;/strong&gt;: Aligns vision, audio, text, and action tokens inside shared latent spaces (CLIP, Flamingo, native multimodal Transformers).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Meta-Learning &amp;amp; Continual Adaptation&lt;/strong&gt;: Enables fast few-shot adaptation (MAML, Prototypical Networks) and prevents catastrophic forgetting on sequential tasks via Elastic Weight Consolidation (EWC).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Decentralized &amp;amp; Responsible AI&lt;/strong&gt;: Covers Federated Learning (FedAvg) for edge privacy, neural architecture search, and multi-objective alignment for real-world deployment.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-compute-optimal-scaling-allocation-chinchilla-ratio&quot;&gt;Worked example: Compute-Optimal Scaling Allocation (Chinchilla Ratio)&lt;/h3&gt;

&lt;p&gt;Under Chinchilla scaling, training compute for a dense Transformer is approximately $C \approx 6 N D$ FLOPs, and compute-optimal pretraining balances model size $N$ and dataset tokens $D$ at roughly $D \approx 20 N$ tokens per parameter.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Given a fixed training compute budget of $C = 1.2 \times 10^{22}$ FLOPs&lt;/strong&gt;:
Substitute $D = 20 N$ into $C = 6 N D = 120 N^2$:
\(N = \sqrt{\frac{1.2 \times 10^{22}}{120}} = \sqrt{10^{20}} = 10^{10} = 10\text{ billion parameters}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the optimal dataset size $D$&lt;/strong&gt;:
\(D = 20 N = 20 \times 10^{10} = 200\text{ billion tokens}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check FLOPs&lt;/strong&gt;: $6 \times 10^{10} \times (2 \times 10^{11}) = 1.2 \times 10^{22}$ FLOPs (exact!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Scaling laws transform pretraining from guesswork into an exact resource-allocation equation—explaining why modern 7B–8B models are often &lt;em&gt;over-trained&lt;/em&gt; far beyond $20N$ (e.g., $15\text{T}$ tokens) to optimize downstream inference cost rather than training cost.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This chapter explores cutting-edge research and future directions in deep learning: multimodal models (CLIP, Flamingo), neural architecture search, meta-learning (learning to learn), continual learning, federated learning, neuromorphic computing, quantum machine learning, and emerging challenges like AI safety, fairness, and sustainability. We look at where deep learning is heading and open research problems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After the future-directions survey, see &lt;strong&gt;25-99 Modern Applications and Updates&lt;/strong&gt; for test-time compute, agents, and open VLMs that already shipped.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (interview practice):&lt;/strong&gt; After the advanced-topics survey, see &lt;strong&gt;25-98 Interviews Practice&lt;/strong&gt; for original Bayesian / uncertainty prompts; open &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for the solved bank.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dedicated LLM hub:&lt;/strong&gt; Pretraining, prompting, alignment, serving, and distillation of large language models are in &lt;strong&gt;Chapter 26&lt;/strong&gt;, not in this survey. The qualitative Chinchilla-style compute-optimal sketch (Kaplan / Hoffmann, no invented curves) is &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=N1fbskTpwZ0&quot;&gt;MIT 6.S191 (2024): Language Models and New Frontiers&lt;/a&gt; — Alexander Amini, English. MIT’s 2024 frontier lecture is this chapter’s overview.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PZXN7jm9IC0&quot;&gt;Chinchilla Explained: Compute-Optimal Massive Language Models&lt;/a&gt; — Edan Meyer, English. Chinchilla scaling, the mathematical claim the future-directions lesson writes.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, English. A concrete map of the systems those frontiers turned into.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>24-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter24/24_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter24/24_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;In 2023–2026, interpretability leaped from highlighting input pixels to reverse-engineering the internal algorithms of frontier LLMs—a field called &lt;strong&gt;Mechanistic Interpretability&lt;/strong&gt;. The core obstacle was &lt;em&gt;polysemanticity&lt;/em&gt;: a single Transformer neuron often fires for unrelated concepts (both French poetry and Python brackets) because models pack more concepts than dimensions via &lt;strong&gt;superposition&lt;/strong&gt;. Sparse Autoencoders (SAEs) broke that code by projecting residual-stream activations into an overcomplete sparse basis where individual latents correspond cleanly to monosemantic concepts like “Golden Gate Bridge” or “SQL injection.”&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mechanistic-interpretability--saes-20222026&quot;&gt;Key ideas: Mechanistic Interpretability &amp;amp; SAEs (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Superposition &amp;amp; Polysemanticity&lt;/strong&gt;: Explains how an $n$-dimensional residual stream can pack $m \gg n$ nearly orthogonal sparse features using Johnson–Lindenstrauss geometry.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Sparse Autoencoders (SAEs) on Residual Streams&lt;/strong&gt;: Trains an overcomplete encoder $f = \operatorname{ReLU}(W_{\text{enc}} x + b_{\text{enc}})$ with an $L_1$ or Top-$k$ sparsity penalty to decompose polysemantic activations into interpretable monosemantic features.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Activation Patching &amp;amp; Circuit Discovery&lt;/strong&gt;: Performs causal interventions—swapping activations from a corrupted prompt into a clean prompt—to isolate exact attention-head circuits (e.g., Induction Heads, Indirect Object Identification).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Feature Steering &amp;amp; Safety Evals&lt;/strong&gt;: Clamps or amplifies discovered SAE features at inference time to test honesty, refusal, and sycophancy behaviors causally.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-superposition-geometry--top-k-sae-feature-decomposition&quot;&gt;Worked example: Superposition Geometry &amp;amp; Top-$k$ SAE Feature Decomposition&lt;/h3&gt;

&lt;p&gt;Suppose a 2D residual stream ($d = 2$) packs $m = 3$ unit-norm concept directions $120^\circ$ apart:
\(d_1 = (1, 0), \qquad d_2 = (-0.5, +0.866), \qquad d_3 = (-0.5, -0.866).\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Check pairwise interference (dot products)&lt;/strong&gt;:
\(d_1^\top d_2 = d_1^\top d_3 = d_2^\top d_3 = -0.5.\)
Even though 3 vectors cannot be mutually orthogonal in $\mathbb{R}^2$, if at most 1 concept is active at a time, a ReLU bias $b = -0.6$ cleanly separates them!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate an SAE encoder&lt;/strong&gt; $f_j = \operatorname{ReLU}(d_j^\top x - 0.6)$ on an activation $x = 2.0\,d_1 = (2.0, 0.0)$:
    &lt;ul&gt;
      &lt;li&gt;$f_1 = \operatorname{ReLU}(2.0(1) - 0.6) = 1.4$ (active!).&lt;/li&gt;
      &lt;li&gt;$f_2 = \operatorname{ReLU}(2.0(-0.5) - 0.6) = \operatorname{ReLU}(-1.6) = 0.0$ (suppressed!).&lt;/li&gt;
      &lt;li&gt;$f_3 = \operatorname{ReLU}(2.0(-0.5) - 0.6) = 0.0$ (suppressed!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: An overcomplete sparse basis ($m &amp;gt; d$) combined with ReLU thresholding cleanly disentangles superposed features that look hopelessly mixed when inspecting raw coordinates $x_1, x_2$.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-interpretability-after-limeshap--circuits-and-sparse-autoencoders&quot;&gt;Optional: interpretability after LIME/SHAP — circuits and sparse autoencoders&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace saliency, LIME, SHAP, or the implementation notes. It covers &lt;strong&gt;mechanistic interpretability&lt;/strong&gt; of Transformers — the 2022–2026 research/product line for LLMs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;SHAP still answers “which input feature moved the score?” For a 70B chat model the interesting question is often “which &lt;strong&gt;internal feature&lt;/strong&gt; implements refusal / code syntax / a latent fact?”&lt;/p&gt;

&lt;h2 id=&quot;1-sparse-autoencoders-on-activations&quot;&gt;1. Sparse autoencoders on activations&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2309.08600&quot;&gt;Cunningham et al., 2023&lt;/a&gt; and &lt;a href=&quot;https://transformer-circuits.pub/2024/scaling-monosemanticity/index.html&quot;&gt;Templeton et al., 2024&lt;/a&gt; (Anthropic, &lt;em&gt;Scaling Monosemanticity&lt;/em&gt;) train a sparse AE on residual-stream activations \(x\):&lt;/p&gt;

\[\hat{x} = W_{\mathrm{dec}}\,\mathrm{ReLU}(W_{\mathrm{enc}}x + b) + b&apos;, \quad \mathcal{L}=\|x-\hat{x}\|_2^2 + \lambda\|f\|_1.\]

&lt;p&gt;The sparse code \(f\) is treated as &lt;strong&gt;monosemantic features&lt;/strong&gt;. Teams then steer or ablate those features (gold-standard evals remain messy). This is an autoencoder (Chapter 12) used as an &lt;em&gt;interpretability instrument&lt;/em&gt;, not a generative model.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;attribution-still-ships&quot;&gt;Attribution still ships&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://captum.ai/&quot;&gt;Captum&lt;/a&gt; integrated gradients and attention-rollout remain what regulated industries put in model cards. Use the theory lesson’s SHAP/LIME for tabular DS; do not replace them with SAEs on a credit model.&lt;/p&gt;

&lt;h3 id=&quot;circuit-style-analyses&quot;&gt;Circuit-style analyses&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://transformer-circuits.pub/&quot;&gt;Elhage et al., Transformer Circuits&lt;/a&gt; (2022–2024) reverse-engineer induction heads and other motifs. Complementary reading, not a homework replacement for Grad-CAM.&lt;/p&gt;

&lt;h3 id=&quot;safety-evals&quot;&gt;Safety evals&lt;/h3&gt;

&lt;p&gt;Interpretability is now a &lt;strong&gt;governance&lt;/strong&gt; input: can we locate a “deception” feature? Papers are preliminary; the course takeaway is the &lt;em&gt;tooling&lt;/em&gt;, not a claim that models are fully explained.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/pytorch/captum&quot;&gt;captum&lt;/a&gt; — production attribution.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/openai/sparse_autoencoder&quot;&gt;openai/sparse_autoencoder&lt;/a&gt; and &lt;a href=&quot;https://github.com/decoderesearch/SAELens&quot;&gt;decoderesearch/SAELens&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/TransformerLensOrg/TransformerLens&quot;&gt;TransformerLens&lt;/a&gt; — hook-based circuit work.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2309.08600&quot;&gt;Sparse Autoencoders Find Highly Interpretable Features in Language Models (Cunningham et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://transformer-circuits.pub/2024/scaling-monosemanticity/index.html&quot;&gt;Scaling Monosemanticity (Templeton et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://transformer-circuits.pub/2021/framework/index.html&quot;&gt;A Mathematical Framework for Transformer Circuits (Elhage et al., 2021/2022)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Run LIME/SHAP and saliency from the chapter first. This lesson only adds &lt;strong&gt;LLM mechanistic tools&lt;/strong&gt; (SAEs, circuits) that appeared after the classic XAI catalog.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [A Window  Into LLMs&lt;/td&gt;
          &lt;td&gt;Sparse Autoencoders Explained](https://www.youtube.com/watch?v=TKozVZoXAYs) — Papers Are Wonderful, English. Sparse autoencoders on activations are the feature-finding method this note describes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=UGO_Ehywuxc&quot;&gt;The Dark Matter of AI [Mechanistic Interpretability]&lt;/a&gt; — Welch Labs, English. Welch Labs on mechanistic interpretability, the program those autoencoders belong to.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, English. The older visualization program this line of work is continuing.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>24-01 Neural Network Interpretability and Explainability</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter24/24_01_Model_Interpretability/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter24/24_01_Model_Interpretability</id>
   <content type="html">&lt;p&gt;Opening the black box of a deep neural network requires both mathematical axioms (so your explanations don’t lie to you) and clean PyTorch instrumentation (so you can inspect real models in seconds). This module pairs the theory of saliency, SHAP, and LRP directly with hands-on Grad-CAM and attribution code.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-theory-to-practice-interpretability-guide&quot;&gt;Key ideas: Theory-to-Practice Interpretability Guide&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Gradient vs. Perturbation Methods&lt;/strong&gt;: Contrasts fast single-pass gradient methods (Saliency, Grad-CAM) with model-agnostic perturbation methods (LIME, KernelSHAP).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Conservation Axioms&lt;/strong&gt;: Uses Completeness and Shapley Efficiency to separate principled attributions from noisy edge-detector visualizations.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — PyTorch Hook Engineering&lt;/strong&gt;: Extracts intermediate layer activations and gradients cleanly for visual and tabular diagnostics.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Pitfall Awareness&lt;/strong&gt;: Recognizes confirmation bias, baseline sensitivity, and adversarial manipulation of explanations.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-baseline-sensitivity-in-integrated-gradients&quot;&gt;Worked example: Baseline Sensitivity in Integrated Gradients&lt;/h3&gt;

&lt;p&gt;Consider a single-pixel model $f(x) = x^2$ evaluated at $x = 2.0$. Compare attributions using two different baselines: black baseline $x’_A = 0.0$ versus gray baseline $x’_B = 1.0$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Exact integral $\text{IG}(x; x’) = (x - x’)\int_0^1 f’(x’ + \alpha(x-x’))\,d\alpha = f(x) - f(x’)$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;With black baseline $x’_A = 0.0$: $\text{IG} = 2^2 - 0^2 = +4.0$.&lt;/li&gt;
      &lt;li&gt;With gray baseline $x’_B = 1.0$: $\text{IG} = 2^2 - 1^2 = +3.0$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What happens if a black pixel ($x = 0$) is actually the critical feature?&lt;/strong&gt;
With black baseline $x’ = 0$, $x - x’ = 0 \implies \text{IG} = 0$ identically—making the black feature completely invisible!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Choosing a semantically neutral baseline (or averaging over multiple random/blurred baselines as in Expected Gradients) is essential so attribution maps never go blind to dark features.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Model interpretability:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Theory&lt;/strong&gt; — saliency, SHAP, LRP, intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implementation&lt;/strong&gt; — Grad-CAM and SHAP code, papers, pitfalls&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, English. The difference between looking inside a net and explaining one prediction.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[SHAP values for beginners&lt;/td&gt;
          &lt;td&gt;What they mean and their applications](https://www.youtube.com/watch?v=MQ6fFDwjuco) — A Data Odyssey, English. SHAP values as one explanation of a single prediction.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Explainable AI explained!&lt;/td&gt;
          &lt;td&gt;#3 LIME](https://www.youtube.com/watch?v=d6j6bofhj2M) — DeepFindr, English. LIME as the other local explanation.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>24-01-02 Interpretability Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter24/24_01_02_Interpretability_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter24/24_01_02_Interpretability_Implementation</id>
   <content type="html">&lt;p&gt;Grad-CAM is the Swiss Army knife of visual debugging in PyTorch because it requires zero retraining and works on any CNN—provided you wire PyTorch’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;register_forward_hook&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;register_full_backward_hook&lt;/code&gt; cleanly without leaking GPU memory! One misplaced &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.detach()&lt;/code&gt; or forgotten &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;hook.remove()&lt;/code&gt; inside a loop will silently accumulate computation graphs until CUDA throws an Out-Of-Memory error.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-implementing-grad-cam--attribution-hooks-in-pytorch&quot;&gt;Key ideas: Implementing Grad-CAM &amp;amp; Attribution Hooks in PyTorch&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Forward &amp;amp; Backward Hook Mechanics&lt;/strong&gt;: Captures intermediate convolutional feature maps $A^k \in \mathbb{R}^{H \times W}$ during the forward pass and class-specific gradients $\frac{\partial y^c}{\partial A^k}$ during &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.backward()&lt;/code&gt;, always removing hooks after use.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Global Average Pooling of Gradients&lt;/strong&gt;: Collapses spatial gradients into per-channel importance weights $\alpha_k^c = \frac{1}{HW}\sum_{i,j} \frac{\partial y^c}{\partial A^k_{ij}}$ before forming the linear combination $\sum_k \alpha_k^c A^k$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — ReLU Positive Filtering &amp;amp; Bilinear Upsampling&lt;/strong&gt;: Applies $\operatorname{ReLU}(\cdot)$ to keep only pixels that &lt;em&gt;positively&lt;/em&gt; support target class $c$, then upsamples the coarse $(7 \times 7)$ map to full image resolution $(224 \times 224)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Faithfulness Verification (Deletion Metric)&lt;/strong&gt;: Masks out the top-$p\%$ Grad-CAM pixels and checks whether target class confidence drops sharply, confirming the heatmap is causally faithful.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-a-exact-2-times-2-grad-cam-heatmap-by-hand&quot;&gt;Worked example: Computing a Exact $2 \times 2$ Grad-CAM Heatmap by Hand&lt;/h3&gt;

&lt;p&gt;Suppose the last convolutional layer has $K = 2$ channels of spatial size $2 \times 2$, with forward activations $A^1, A^2$ and backward gradients $G^1, G^2$ for target class $c$:
\(A^1 = \begin{bmatrix}2 &amp;amp; 0\\ 1 &amp;amp; 3\end{bmatrix}, \quad G^1 = \begin{bmatrix}0.4 &amp;amp; 0.0\\ 0.2 &amp;amp; 0.2\end{bmatrix}; \qquad A^2 = \begin{bmatrix}1 &amp;amp; 4\\ 0 &amp;amp; 1\end{bmatrix}, \quad G^2 = \begin{bmatrix}-0.1 &amp;amp; -0.3\\ 0.0 &amp;amp; 0.0\end{bmatrix}.\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Global-average-pool gradients to obtain channel weights $\alpha_k^c$&lt;/strong&gt; ($H \times W = 4$):
\(\alpha_1^c = \frac{0.4 + 0.0 + 0.2 + 0.2}{4} = +0.20, \qquad \alpha_2^c = \frac{-0.1 - 0.3 + 0.0 + 0.0}{4} = -0.10.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Weighted channel sum $S = \alpha_1^c A^1 + \alpha_2^c A^2$&lt;/strong&gt;:
\(S = 0.20\begin{bmatrix}2 &amp;amp; 0\\ 1 &amp;amp; 3\end{bmatrix} - 0.10\begin{bmatrix}1 &amp;amp; 4\\ 0 &amp;amp; 1\end{bmatrix} = \begin{bmatrix}0.4 - 0.1 &amp;amp; 0.0 - 0.4\\ 0.2 - 0.0 &amp;amp; 0.6 - 0.1\end{bmatrix} = \begin{bmatrix}0.3 &amp;amp; -0.4\\ 0.2 &amp;amp; 0.5\end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply ReLU and min-max normalize to $[0, 1]$&lt;/strong&gt;:
\(L_{\text{Grad-CAM}} = \operatorname{ReLU}(S) = \begin{bmatrix}0.3 &amp;amp; 0.0\\ 0.2 &amp;amp; 0.5\end{bmatrix} \xrightarrow{\div 0.5} \begin{bmatrix}0.6 &amp;amp; 0.0\\ 0.4 &amp;amp; 1.0\end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: The bottom-right cell ($1.0$) is the hottest positive driver of class $c$, while the top-right cell ($-0.4 \to 0.0$)—which belonged to a competing class—is cleanly zeroed out by ReLU.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GradCAM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Gradient-weighted Class Activation Mapping.
    
    Visualizes which regions of image are important for prediction
    by computing gradients of class score with respect to final
    convolutional layer activations.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        model: CNN model
        target_layer: name of convolutional layer to visualize
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_layer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_layer&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Storage for forward activations and backward gradients
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Register hooks
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_register_hooks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_register_hooks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Register forward and backward hooks on target layer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Find target layer
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;named_modules&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;register_forward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;forward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;register_full_backward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;backward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_class&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Generate CAM for target class.
        
        input_image: (1, 3, H, W)
        target_class: index of class to explain
        
        Returns: (H, W) heatmap
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass for target class
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;class_score&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_class&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;class_score&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Get activations and gradients
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, C, H, W)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, C, H, W)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Global average pool gradients to get weights
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, C, 1, 1)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Weighted combination of activation maps
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, 1, H, W)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# ReLU (only positive contributions)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Normalize to [0, 1]
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example usage
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Grad-CAM: Visualizing CNN Decisions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Load pre-trained model
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;PIL&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Image&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;resnet50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DEFAULT&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create Grad-CAM
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradcam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GradCAM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_layer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;layer4&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Load and preprocess image (simulated here)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generating Grad-CAM for sample image...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;input_tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;224&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;224&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Get prediction
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;predicted_class&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;confidence&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted_class&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted class: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predicted_class&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; with confidence &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;confidence&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate CAM for predicted class
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradcam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;generate_cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted_class&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CAM shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CAM range: [&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CAM highlights image regions important for prediction!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;High values = important regions, low values = irrelevant&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# SHAP approximation
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSHAP&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Simplified SHAP for neural networks&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;background_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        model: neural network
        background_data: reference dataset for baselines
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;background&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;background_data&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;explain&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Approximate SHAP values for input x.
        
        Uses sampling to approximate Shapley values:
        repeatedly mask random subsets of features,
        measure prediction changes.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Get baseline prediction (average over background)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;baseline_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Generate random feature masks
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;masks&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute predictions with different feature subsets
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;masks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Mask some features (use background average)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;x_masked&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clone&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;bg_avg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;x_masked&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bg_avg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;x_masked&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_masked&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Compute prediction
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_masked&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Marginal contribution of each feature
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;pred_diff&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;baseline_output&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred_diff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SHAP: Feature Attribution&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simple example with a linear model (for verification)
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;simple_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;background&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reference data
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;shap&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSHAP&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;simple_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;background&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Explain a prediction
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shap&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;explain&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature attributions (SHAP values):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attributions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Positive = feature increased prediction&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Negative = feature decreased prediction&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Magnitude = importance&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Adversarial examples for probing robustness:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fgsm_attack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Fast Gradient Sign Method: minimal perturbation to fool model.
    
    Reveals model&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s decision boundaries and vulnerabilities.
    Shows what patterns strongly influence predictions.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Backward to get gradients
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Create adversarial example
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Move in direction that increases loss (fools model)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;perturbation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sign&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;adversarial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;perturbation&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adversarial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adversarial Examples: Probing Model Robustness&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simple classifier
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyClassifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;toy_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyClassifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;toy_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Original image (random for demo)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;original&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;true_label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Get original prediction
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;orig_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;toy_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;original&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;orig_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;orig_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;orig_conf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orig_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;orig_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Original prediction: class &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orig_pred&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;orig_conf&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; confidence)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate adversarial example
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adversarial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fgsm_attack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;toy_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;original&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clone&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test adversarial
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;adv_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;toy_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adversarial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;adv_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adv_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;adv_conf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adv_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adv_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adversarial prediction: class &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adv_pred&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adv_conf&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; confidence)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Measure perturbation
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perturbation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adversarial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;original&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Average perturbation: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perturbation&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adv_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;orig_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✗ Model fooled by imperceptible perturbation!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This reveals model&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s decision boundary is fragile&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✓ Model robust to this perturbation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Interpretability connects to causality through attempts to move beyond correlation to understanding causal mechanisms. Attribution methods identify correlations between inputs and outputs, but correlation doesn’t imply causation. Causal interpretability seeks to answer “would changing this input feature actually cause the prediction to change?” requiring interventions and counterfactual reasoning beyond standard attribution.&lt;/p&gt;

&lt;p&gt;The relationship to uncertainty quantification provides complementary understanding. Interpretability shows why a prediction was made. Uncertainty quantification shows how confident the model is. Together, they provide comprehensive understanding: “the model predicts class A because of feature X, with confidence Y.” Bayesian deep learning, dropout for uncertainty, and ensemble methods complement interpretability by quantifying prediction reliability.&lt;/p&gt;

&lt;p&gt;Interpretability relates to fairness and bias detection. If a hiring model uses gender or race features (directly or through proxies), interpretability methods reveal this, enabling auditing for discriminatory behavior. Understanding what features drive predictions is prerequisite for ensuring fairness, though interpretability alone doesn’t guarantee fairness—we must also determine whether identified features are legitimate or biased.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.6034&quot;&gt;“Deep Inside Convolutional Networks: Visualising Image Classification Models and Saliency Maps” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Karen Simonyan, Andrea Vedaldi, Andrew Zisserman&lt;br /&gt;
Introduced gradient-based saliency maps for CNNs, showing derivatives reveal which pixels matter for predictions. Established visualization as key interpretability tool.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1311.2901&quot;&gt;“Visualizing and Understanding Convolutional Networks” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Matthew Zeiler, Rob Fergus&lt;br /&gt;
Deconvolution networks visualized what features CNN layers learn. Showed early layers detect edges/colors, middle layers detect textures/patterns, deep layers detect object parts. Foundational for understanding CNN hierarchical features.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1610.02391&quot;&gt;“Grad-CAM: Visual Explanations from Deep Networks via Gradient-based Localization” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ramprasaath Selvaraju, Michael Cogswell, Abhishek Das, Ramakrishna Vedantam, Devi Parikh, Dhruv Batra&lt;br /&gt;
Grad-CAM generates visual explanations by using gradients to weight feature maps, producing class-discriminative localization without modifying architecture. Became standard for CNN interpretability.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1705.07874&quot;&gt;“A Unified Approach to Interpreting Model Predictions” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Scott Lundberg, Su-In Lee&lt;br /&gt;
SHAP unified multiple attribution methods under Shapley value framework from game theory, providing theoretically grounded explanations with desirable properties. Became standard for tabular data and model-agnostic explanations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1703.01365&quot;&gt;“Axiomatic Attribution for Deep Networks” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Mukund Sundararajan, Ankur Taly, Qiqi Yan&lt;br /&gt;
Integrated Gradients satisfied attribution axioms (sensitivity, implementation invariance) that gradient-based methods violate. Provided principled attribution method with theoretical guarantees.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;Saliency maps can be misleading. High gradient doesn’t always mean high importance—could be artifact of network architecture (batch norm, ReLU) or optimization. Always verify interpretations with ablation (actually remove features and measure impact) or by checking if explanations align with domain knowledge.&lt;/p&gt;

&lt;p&gt;Adversarial examples don’t necessarily indicate poor models. All models have adversarial vulnerabilities—it’s a fundamental property of high-dimensional spaces. Focus on robustness to natural perturbations (noise, blur) rather than adversarially crafted worst-cases unless security is critical.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Neural network interpretability enables understanding why models make predictions through attribution methods (which inputs mattered), visualization techniques (what features were learned), and explanation frameworks (how decisions decompose). Gradient-based saliency highlights input regions with high sensitivity to prediction changes. Grad-CAM visualizes spatial importance in CNNs through gradient-weighted feature maps. SHAP provides theoretically grounded attributions through Shapley values from game theory. Adversarial examples reveal model robustness by finding minimal perturbations changing predictions. Different interpretability methods provide complementary insights—saliency for input importance, activation visualization for learned features, SHAP for faithful attribution—often requiring multiple techniques for comprehensive understanding. Interpretability enables debugging spurious correlations, building trust in high-stakes applications, satisfying regulatory requirements, and generating scientific insights from learned patterns, making it increasingly important as deep learning deployment expands to critical domains requiring explainability beyond accuracy.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Explainable AI explained!&lt;/td&gt;
          &lt;td&gt;#3 LIME](https://www.youtube.com/watch?v=d6j6bofhj2M) — DeepFindr, English. A method you can implement as a weighted local model.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[SHAP values for beginners&lt;/td&gt;
          &lt;td&gt;What they mean and their applications](https://www.youtube.com/watch?v=MQ6fFDwjuco) — A Data Odyssey, English. What the SHAP library is computing if you call it instead of writing the sum.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, English. The visualization pitfalls (interpretations that look meaningful and are not).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>24-01-01 Interpretability Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter24/24_01_01_Interpretability_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter24/24_01_01_Interpretability_Theory</id>
   <content type="html">&lt;p&gt;Raw gradient saliency maps suffer from a nasty mathematical flaw: inside a saturated ReLU or sigmoid region, a feature can be the &lt;em&gt;sole reason&lt;/em&gt; a prediction is high and still have a local gradient of zero! Axiomatic attribution theory—culminating in Shapley values (SHAP), Integrated Gradients, and Layer-wise Relevance Propagation (LRP)—fixes this by insisting on rigorous conservation laws: the sum of feature attributions must equal the exact difference between the model’s output and a neutral baseline.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-axiomatic-attribution-theory&quot;&gt;Key ideas: Axiomatic Attribution Theory&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Integrated Gradients &amp;amp; Completeness&lt;/strong&gt;: Integrates gradients along the straight-line path from baseline $x’$ to input $x$: $\text{IG}_i(x) = (x_i - x’_i)\int_0^1 \frac{\partial F(x’ + \alpha(x-x’))}{\partial x_i}\,d\alpha$, satisfying both Sensitivity and Completeness axioms.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Cooperative Game Theory &amp;amp; Shapley Values (SHAP)&lt;/strong&gt;: Treats features as players in a coalition game and proves there is a &lt;em&gt;unique&lt;/em&gt; attribution satisfying Efficiency, Symmetry, Dummy, and Additivity.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Layer-Wise Relevance Propagation (LRP)&lt;/strong&gt;: Propagates the output logit $f(x)$ backward layer by layer while conserving total relevance $\sum_i R_i^{(l)} = \sum_j R_j^{(l+1)}$ at every layer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Attention vs. Explanation Debate&lt;/strong&gt;: Clarifies why raw Transformer attention weights do not automatically equal causal feature importance unless validated by gradient or ablation tests.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-exact-shapley-values-for-a-2-feature-classifier&quot;&gt;Worked example: Computing Exact Shapley Values for a 2-Feature Classifier&lt;/h3&gt;

&lt;p&gt;Suppose a loan-approval model $v(S)$ uses two binary features: $A$ (high income) and $B$ (clean credit history), with subset outputs:
\(v(\varnothing) = 0.20, \quad v(\{A\}) = 0.50, \quad v(\{B\}) = 0.40, \quad v(\{A, B\}) = 0.90.\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute marginal contributions of Feature $A$ across both arrival orders&lt;/strong&gt; ($2! = 2$ permutations):
    &lt;ul&gt;
      &lt;li&gt;Order $(A, B)$: $v({A}) - v(\varnothing) = 0.50 - 0.20 = +0.30$.&lt;/li&gt;
      &lt;li&gt;Order $(B, A)$: $v({A, B}) - v({B}) = 0.90 - 0.40 = +0.50$.&lt;/li&gt;
      &lt;li&gt;Average Shapley value $\phi_A = \frac{0.30 + 0.50}{2} = +0.40$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute marginal contributions of Feature $B$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Order $(B, A)$: $v({B}) - v(\varnothing) = 0.40 - 0.20 = +0.20$.&lt;/li&gt;
      &lt;li&gt;Order $(A, B)$: $v({A, B}) - v({A}) = 0.90 - 0.50 = +0.40$.&lt;/li&gt;
      &lt;li&gt;Average Shapley value $\phi_B = \frac{0.20 + 0.40}{2} = +0.30$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify the Efficiency Axiom&lt;/strong&gt;:
\(v(\varnothing) + \phi_A + \phi_B = 0.20 + 0.40 + 0.30 = 0.90 = v(\{A, B\}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Notice the $0.20$ synergy bonus when both $A$ and $B$ are present is split fairly ($+0.10$ each) between the two features—something single-feature leave-one-out ablation fails to conserve.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;model-interpretability-understanding-the-black-box&quot;&gt;Model Interpretability: Understanding the Black Box&lt;/h1&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Neural network interpretability addresses one of deep learning’s most significant challenges: understanding why models make particular predictions. While neural networks achieve remarkable performance on diverse tasks, their decision-making process often appears opaque—millions of parameters interacting through nonlinear transformations make it difficult to trace how inputs map to outputs. This “black box” nature creates problems in high-stakes domains like medicine (why did the model diagnose this condition?), law (why was this defendant classified as high-risk?), and autonomous vehicles (why did the car brake suddenly?), where we need not just accurate predictions but justifications we can audit, trust, and debug.&lt;/p&gt;

&lt;p&gt;Understanding the distinction between interpretability and explainability clarifies what we’re seeking. Interpretability means the model’s internal workings are transparent—we can understand the computation from inspection. Simple models like linear regression or decision trees are inherently interpretable; we can see exactly how features combine to produce predictions. Explainability means we can provide post-hoc explanations of why a model made specific predictions, even if the model itself isn’t inherently transparent. Deep neural networks are rarely interpretable (understanding millions of parameters is infeasible) but can be made explainable through techniques that highlight relevant inputs, visualize learned features, or approximate decisions with interpretable surrogates.&lt;/p&gt;

&lt;p&gt;The motivation for interpretability extends beyond satisfying curiosity. In scientific applications, understanding what features models use can generate new hypotheses—if a medical imaging model identifies a subtle pattern doctors missed, investigating this pattern might reveal new diagnostic markers. In debugging, interpretability reveals when models exploit spurious correlations (detecting huskies by snow in background rather than dog features) or fail to use relevant features. In safety-critical applications, interpretability enables verification that models behave reasonably across diverse scenarios. In regulated industries, explainability may be legally required for decisions affecting individuals. Understanding these diverse motivations helps appreciate that interpretability isn’t a single goal but multiple related objectives requiring different techniques.&lt;/p&gt;

&lt;p&gt;The landscape of interpretability methods is vast, reflecting the multiple ways we might understand neural networks. Saliency methods highlight which input regions most influenced a prediction, answering “what did the model look at?” Activation visualization shows what patterns activate neurons, revealing “what features has the network learned?” Attribution methods decompose predictions into feature contributions, explaining “how much did each input feature matter?” Concept-based explanations identify high-level concepts the model uses, moving beyond pixel or word-level attributions to semantic understanding. Each approach provides different insights, and comprehensive interpretability often requires multiple complementary techniques.&lt;/p&gt;

&lt;p&gt;Yet interpretability has fundamental tensions. More interpretable models are often less accurate (linear models vs deep networks). Faithful explanations (accurately describing model behavior) might be complex and hard to understand. Simple explanations might be understandable but unfaithful to actual model behavior. Perfect interpretability might require understanding millions of parameters—as complex as understanding the phenomenon the model learned. These tensions mean interpretability research involves careful tradeoffs between fidelity, simplicity, and utility, without universal solutions that satisfy all desiderata simultaneously.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;Interpretability methods often formalize the question “which inputs matter most for this prediction?” through attribution. Given input \(\mathbf{x}\) and model \(f\), compute attribution \(\mathbf{a}\) where \(a_i\) indicates importance of input dimension \(i\) for the prediction \(f(\mathbf{x})\).&lt;/p&gt;

&lt;h3 id=&quot;gradient-based-saliency&quot;&gt;Gradient-Based Saliency&lt;/h3&gt;

&lt;p&gt;The simplest attribution uses gradients:&lt;/p&gt;

\[\mathbf{a} = \left|\frac{\partial f(\mathbf{x})}{\partial \mathbf{x}}\right|\]

&lt;p&gt;This measures how much the output would change for small changes in each input dimension. Large gradient indicates high sensitivity—that input dimension strongly influences the output. For images, this produces saliency maps highlighting important pixels.&lt;/p&gt;

&lt;p&gt;However, gradient can saturate in ReLU networks (gradient is zero or one, not informative about magnitude of change) and doesn’t account for baseline (what are we comparing against?). Improvements address these issues:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Integrated Gradients&lt;/strong&gt; accumulates gradients along path from baseline \(\mathbf{x}&apos;\) to input \(\mathbf{x}\):&lt;/p&gt;

\[\mathbf{a}_i = (x_i - x_i&apos;) \int_{\alpha=0}^1 \frac{\partial f(\mathbf{x}&apos; + \alpha(\mathbf{x} - \mathbf{x}&apos;))}{\partial x_i} d\alpha\]

&lt;p&gt;This satisfies desirable axioms: sensitivity (if input doesn’t affect output, attribution is zero) and implementation invariance (equivalent networks give same attributions).&lt;/p&gt;

&lt;h3 id=&quot;shap-shapley-additive-explanations&quot;&gt;SHAP: Shapley Additive Explanations&lt;/h3&gt;

&lt;p&gt;SHAP uses Shapley values from cooperative game theory. The contribution of feature \(i\) is:&lt;/p&gt;

\[\phi_i = \sum_{S \subseteq \mathcal{F} \backslash \{i\}} \frac{|S|!(|\mathcal{F}|-|S|-1)!}{|\mathcal{F}|!} [f(S \cup \{i\}) - f(S)]\]

&lt;p&gt;where \(\mathcal{F}\) is all features, \(S\) are feature subsets, \(f(S)\) is model output with only features in \(S\) present (others set to baseline). This computes the average marginal contribution of feature \(i\) across all possible feature coalitions—a fair allocation of prediction among features.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Computing exact Shapley values requires $$2^{&lt;/td&gt;
      &lt;td&gt;\mathcal{F}&lt;/td&gt;
      &lt;td&gt;}$$ model evaluations (exponential in features), so approximations are used. Kernel SHAP approximates through weighted linear regression. For tree-based models, TreeSHAP computes exactly in polynomial time.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;layer-wise-relevance-propagation-lrp&quot;&gt;Layer-wise Relevance Propagation (LRP)&lt;/h3&gt;

&lt;p&gt;LRP backpropagates relevance from output to input:&lt;/p&gt;

\[R_i^{(l)} = \sum_j \frac{z_{ij}}{\sum_k z_{kj}} R_j^{(l+1)}\]

&lt;p&gt;where \(z_{ij} = a_i^{(l)} w_{ij}\) is contribution of neuron \(i\) in layer \(l\) to neuron \(j\) in layer \(l+1\). Starting with \(R_{\text{out}} = f(\mathbf{x})\) at output, relevance propagates backward, decomposing prediction into input contributions satisfying \(\sum_i R_i^{(0)} = f(\mathbf{x})\) (conservation).&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Consider a CNN classifying an image as “dog” with 95% confidence. Without interpretability, we don’t know why. Was it the dog’s face, body shape, background context, or spurious patterns like grass (if all dogs in training had grass backgrounds)?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gradient saliency&lt;/strong&gt; computes \(\partial p_{\text{dog}}/\partial \text{pixels}\). Large gradients highlight pixels that, if changed slightly, would most affect the dog probability. Visualized as a heatmap overlay on the image, we might see high values around the dog’s face and ears—good, the model uses actual dog features. If high values appear in background, the model might be exploiting spurious correlations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Class Activation Mapping (CAM)&lt;/strong&gt; for CNNs with global average pooling shows which regions the final convolutional layer found important. For “dog” class, we compute weighted combination of final conv layer’s feature maps using the classification weights:&lt;/p&gt;

\[\text{CAM} = \sum_k w_k^{\text{dog}} \cdot \text{FeatureMap}_k\]

&lt;p&gt;This produces a heatmap at feature map resolution showing which spatial regions contributed to the “dog” prediction. Upsampling to input resolution and overlaying on the image reveals the model focused on the dog’s head and body—interpretable and reassuring.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SHAP values&lt;/strong&gt; for a particular prediction might show:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Pixel region containing dog face: +0.35 (strong positive contribution)&lt;/li&gt;
  &lt;li&gt;Pixel region with dog body: +0.28&lt;/li&gt;
  &lt;li&gt;Background grass: +0.08 (small contribution - concerning if high)&lt;/li&gt;
  &lt;li&gt;Sky region: -0.02 (slight negative - expected for irrelevant regions)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If grass has high SHAP value, we’ve discovered the model uses spurious correlation (dogs often photographed on grass). We can then collect more diverse training data or use data augmentation to fix this.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adversarial examples&lt;/strong&gt; provide another interpretability lens. By finding minimal input perturbations that change predictions, we reveal model vulnerabilities. If adding imperceptible noise to dog image causes “cat” prediction, the model’s representation is fragile—it hasn’t learned robust features. Studying these adversarial perturbations reveals what features matter: perturbations often add patterns the model strongly associates with target class, revealing learned (but perhaps spurious) class indicators.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [SHAP values for beginners&lt;/td&gt;
          &lt;td&gt;What they mean and their applications](https://www.youtube.com/watch?v=MQ6fFDwjuco) — A Data Odyssey, English. A SHAP value is a fair share of the prediction, the theory’s main definition.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, English. Feature visualization, the other theoretical tradition in the lesson (what a unit responds to).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Explainable AI explained!&lt;/td&gt;
          &lt;td&gt;#3 LIME](https://www.youtube.com/watch?v=d6j6bofhj2M) — DeepFindr, English. A local linear surrogate, so SHAP is not the only formal story.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>24 Interpretability and Explainability</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter24/24_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter24/24_00_Introduction</id>
   <content type="html">&lt;p&gt;A famous wolf-vs-husky classifier achieved 95% test accuracy—until researchers ran an explanation map and discovered it was completely ignoring the animals and only looking at whether there was snow in the background. In medicine, finance, and autonomous driving, high test accuracy is never enough if the model relies on brittle shortcuts (“Clever Hans” features). Interpretability and Explainable AI (XAI) turn opaque neural networks into auditable instruments by attributing predictions to input pixels, tokens, and internal circuits.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-foundations-of-neural-network-interpretability&quot;&gt;Key ideas: Foundations of Neural Network Interpretability&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Local vs. Global Explanations&lt;/strong&gt;: Separates explaining &lt;em&gt;one specific prediction&lt;/em&gt; (saliency maps, LIME, SHAP) from understanding &lt;em&gt;general learned concepts&lt;/em&gt; across the whole network (feature visualization, concept activation vectors).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Gradient &amp;amp; Backpropagation Attribution&lt;/strong&gt;: Uses local first-order sensitivity $\nabla_x f_c(x)$, Integrated Gradients, and Grad-CAM to highlight which pixels or tokens move the target class logit.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Perturbation &amp;amp; Game-Theoretic Attribution&lt;/strong&gt;: Measures feature importance by masking inputs and averaging marginal contributions over subsets (LIME surrogate models, Shapley values).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Sanity Checks &amp;amp; Faithfulness&lt;/strong&gt;: Distinguishes visually pleasing heatmaps from truly faithful explanations using randomization tests (Adebayo et al.) and insertion/deletion AUC curves.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-input--gradient-saliency-on-a-2-feature-linear-relu-unit&quot;&gt;Worked example: Computing Input × Gradient Saliency on a 2-Feature Linear-ReLU Unit&lt;/h3&gt;

&lt;p&gt;Consider a toy model $f(x_1, x_2) = \operatorname{ReLU}(3x_1 - 2x_2 + 1)$ evaluated at input $x = (x_1 = 2.0,\; x_2 = 1.0)$ relative to baseline $x’ = (0, 0)$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Forward pass&lt;/strong&gt;:
\(f(2, 1) = \operatorname{ReLU}(3(2) - 2(1) + 1) = \operatorname{ReLU}(5) = 5.0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vanilla Gradient saliency&lt;/strong&gt; ($\nabla_x f$):
\(\frac{\partial f}{\partial x_1} = +3, \qquad \frac{\partial f}{\partial x_2} = -2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Input × Gradient attribution&lt;/strong&gt; ($x_i \cdot \frac{\partial f}{\partial x_i}$):
\(\text{Attr}(x_1) = 2.0 \times 3 = +6.0, \qquad \text{Attr}(x_2) = 1.0 \times (-2) = -2.0.\)
Notice that $\text{Attr}(x_1) + \text{Attr}(x_2) = 6.0 - 2.0 = 4.0 = f(2, 1) - f(0, 0) = 5.0 - 1.0$ (exact completeness!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Raw gradients measure &lt;em&gt;local sensitivity&lt;/em&gt; (slope), whereas Input × Gradient (and Integrated Gradients on nonlinear nets) accounts for feature magnitude so attributions sum cleanly to the actual prediction shift.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Understanding why deep learning models make certain predictions is crucial for trust, debugging, and compliance. This chapter covers visualization techniques (saliency maps, activation visualization), attention analysis, feature importance, LIME, SHAP, counterfactual explanations, and adversarial examples. We explore methods to make black-box models more interpretable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After LIME/SHAP, see &lt;strong&gt;24-99 Modern Applications and Updates&lt;/strong&gt; for sparse autoencoders and mechanistic interpretability of LLMs.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 12&lt;/td&gt;
          &lt;td&gt;Visualizing and Understanding](https://www.youtube.com/watch?v=6wcs6szJWMY) — Stanford University School of Engineering, English. CS231n on visualizing and understanding networks is this chapter’s starting point.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[SHAP values for beginners&lt;/td&gt;
          &lt;td&gt;What they mean and their applications](https://www.youtube.com/watch?v=MQ6fFDwjuco) — A Data Odyssey, English. SHAP, the attribution method the lessons then define.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Explainable AI explained!&lt;/td&gt;
          &lt;td&gt;#3 LIME](https://www.youtube.com/watch?v=d6j6bofhj2M) — DeepFindr, English. LIME, the local surrogate set beside SHAP.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>23-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter23/23_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter23/23_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Naive round-to-nearest 4-bit quantization wrecks a 70B LLM because a tiny handful of activation channels (~0.1% of features) carry massive outlier magnitudes that blow up quantization scales. Between 2023 and 2026, efficient LLM serving conquered that outlier problem through Hessian-guided quantization (GPTQ), activation-aware channel scaling (AWQ), portable consumer formats (GGUF), Sparse Mixture-of-Experts (MoE), and lossless speculative decoding.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-modern-llm-efficiency-stack-20222026&quot;&gt;Key ideas: Modern LLM Efficiency Stack (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Outlier-Aware Weight Quantization (GPTQ &amp;amp; AWQ)&lt;/strong&gt;: Compensates quantization rounding error across remaining weights using inverse Hessian updates (GPTQ) or rescales the ~1% salient weight channels protected by large input activations (AWQ).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Consumer Edge Formats (GGUF / K-Quants)&lt;/strong&gt;: Packs group-wise quantized blocks (e.g., &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Q4_K_M&lt;/code&gt;, 32-weight super-blocks with FP16 scales) into a single memory-mapped file for fast CPU/Apple-Silicon inference (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;llama.cpp&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Lossless Speculative Decoding&lt;/strong&gt;: Uses a tiny draft model to propose $K$ tokens rapidly, then verifies all $K$ in a &lt;em&gt;single&lt;/em&gt; parallel forward pass of the large target model via rejection sampling—preserving the &lt;strong&gt;exact&lt;/strong&gt; target distribution.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Sparse Mixture-of-Experts (MoE)&lt;/strong&gt;: Decouples total knowledge capacity (e.g., 8×7B or 671B total params) from per-token compute (routing each token to only top-2 experts).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-effective-bits-per-weight-bpw-of-group-wise-int4--speculative-speedup&quot;&gt;Worked example: Effective Bits-Per-Weight (BPW) of Group-Wise INT4 &amp;amp; Speculative Speedup&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Part A — Group-Wise INT4 Effective Bit-Width&lt;/strong&gt;: Suppose weights are stored in 4-bit integers in groups of $g = 128$ weights, where each group stores one FP16 scale ($16$ bits) and one FP16 zero-point ($16$ bits).&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Total bits per 128 weights: $128 \times 4 + 16 + 16 = 512 + 32 = 544\text{ bits}$.&lt;/li&gt;
  &lt;li&gt;Effective bits per weight: $544 / 128 = 4.25\text{ BPW}$ (only $0.25$ bits overhead for huge accuracy gains!).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Part B — Speculative Decoding Speedup&lt;/strong&gt;: Suppose the target model costs $T = 40\text{ ms}$ per forward pass, a draft model costs $t_d = 4\text{ ms}$ per token, we draft $K = 4$ tokens per round, and on average $3.0$ drafted tokens are accepted (yielding $3.0 + 1 = 4.0$ verified target tokens per round, including the bonus token).&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Time per round: $4 \times 4\text{ ms} + 40\text{ ms} = 56\text{ ms}$ for $4.0$ tokens $\implies 14.0\text{ ms/token}$.&lt;/li&gt;
  &lt;li&gt;Speedup vs. standard target decoding ($40\text{ ms/token}$): $40 / 14 = 2.86\times$ faster with &lt;strong&gt;zero&lt;/strong&gt; quality loss!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Combining group-wise 4.25-BPW quantization with speculative decoding turns a sluggish 70B server model into a responsive interactive assistant.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-efficient-llms--gptq-awq-gguf-and-speculative-decoding&quot;&gt;Optional: efficient LLMs — GPTQ, AWQ, GGUF, and speculative decoding&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace pruning, quantization math, distillation, or MobileNet/EfficientNet in the core note. Those still matter for CNNs and edge vision. This lesson is the &lt;strong&gt;LLM serving&lt;/strong&gt; efficiency stack of 2022–2026.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;INT8&lt;/p&gt;

\[w_q = \mathrm{round}\big((w-z)/s\big)\]

&lt;p&gt;is the same idea. The new work is &lt;strong&gt;weight-only 4-bit&lt;/strong&gt; for Transformers and &lt;strong&gt;decoding algorithms&lt;/strong&gt; that cut sequential steps.&lt;/p&gt;

&lt;h2 id=&quot;1-post-training-quantization-for-lms&quot;&gt;1. Post-training quantization for LMs&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.17323&quot;&gt;GPTQ (Frantar et al., 2023)&lt;/a&gt; — layer-wise second-order PTQ; foundation of many Hub &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;gptq&lt;/code&gt; models.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2306.00978&quot;&gt;AWQ (Lin et al., 2024)&lt;/a&gt; — protect &lt;em&gt;salient&lt;/em&gt; channels (activation-aware) before 4-bit rounding; strong on instruction-tuned LMs.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;GGUF / llama.cpp&lt;/a&gt; — k-quants (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Q4_K_M&lt;/code&gt;, …) for CPU and Apple Silicon.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These complement, not duplicate, the chapter’s general quantizer: they are &lt;strong&gt;recipe + kernel&lt;/strong&gt; for attention blocks.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;lora--quant-qlora&quot;&gt;LoRA + quant (QLoRA)&lt;/h3&gt;

&lt;p&gt;Already sketched in Chapter 15 optional: 4-bit base, 16-bit adapters. Serving then merges or swaps adapters. Efficiency &lt;em&gt;and&lt;/em&gt; transfer.&lt;/p&gt;

&lt;h3 id=&quot;speculative-decoding&quot;&gt;Speculative decoding&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Leviathan et al., 2023&lt;/a&gt;: a cheap draft model proposes \(K\) tokens; the large model accepts a prefix in one parallel forward. Wall-clock speedup without changing \(\pi\). vLLM and many APIs ship this.&lt;/p&gt;

&lt;h3 id=&quot;moe-routing-as-efficiency&quot;&gt;MoE routing as efficiency&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2401.04088&quot;&gt;Mixtral (Jiang et al., 2024)&lt;/a&gt; activates a subset of experts per token: more parameters, similar FLOPs. Complementary to compression: &lt;em&gt;sparse compute&lt;/em&gt;, not fewer stored weights.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/AutoGPTQ/AutoGPTQ&quot;&gt;AutoGPTQ&lt;/a&gt;, &lt;a href=&quot;https://github.com/mit-han-lab/llm-awq&quot;&gt;mit-han-lab/llm-awq&lt;/a&gt;, &lt;a href=&quot;https://github.com/TimDettmers/bitsandbytes&quot;&gt;bitsandbytes&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;ggerganov/llama.cpp&lt;/a&gt; and &lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vllm-project/vllm&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.17323&quot;&gt;GPTQ (Frantar et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2306.00978&quot;&gt;AWQ: Activation-aware Weight Quantization (Lin et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Fast Inference from Transformers via Speculative Decoding (Leviathan et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2401.04088&quot;&gt;Mixtral of Experts (Jiang et al., 2024)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Keep the pruning / KD / MobileNet derivations. This lesson only adds &lt;strong&gt;LLM-specific PTQ, GGUF, speculative decoding, and MoE&lt;/strong&gt; — the tools you use when the “model” is a 7B–70B Transformer.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, English. Post-training quantization of language models is this note.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[QLoRA: Efficient Finetuning of Quantized LLMs&lt;/td&gt;
          &lt;td&gt;Tim Dettmers](https://www.youtube.com/watch?v=fQirE9N5q_Y) — AMLD Intelligence Summit, English. QLoRA, the fine-tune that stays in 4-bit, from Tim Dettmers.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jrJKRYAdh7I&quot;&gt;Knowledge Distillation: How LLMs train each other&lt;/a&gt; — Julia Turc, English. Distillation as the other way to get a smaller deployed model.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>23-01 Model Compression and Efficiency</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter23/23_01_Model_Compression/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter23/23_01_Model_Compression</id>
   <content type="html">&lt;p&gt;Over-parameterized neural networks are remarkably redundant: studies on the Lottery Ticket Hypothesis and post-training quantization show you can zero out 70% of weights or round 32-bit floats down to 8-bit integers and lose less than half a percent of accuracy. Understanding the exact arithmetic of affine quantization, temperature-scaled KL distillation, and depthwise-separable FLOPs lets you engineer compression budgets quantitatively instead of guessing.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mathematical-mechanics-of-model-compression&quot;&gt;Key ideas: Mathematical Mechanics of Model Compression&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Affine &amp;amp; Symmetric Quantization Arithmetic&lt;/strong&gt;: Maps floating-point ranges $[\alpha, \beta]$ to $b$-bit integers via scale $s = \frac{\beta - \alpha}{2^b - 1}$ and zero-point $z$, with Quantization-Aware Training (QAT) using Straight-Through Estimators (STE) to differentiate through &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;round()&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Temperature-Scaled Knowledge Distillation&lt;/strong&gt;: Softens teacher and student logits via $p_i^{(T)} = \operatorname{softmax}(z_i / T)$ and scales KL loss by $T^2$ so gradient magnitudes stay invariant to $T$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Structured vs. Unstructured Pruning&lt;/strong&gt;: Balances fine-grained weight-magnitude pruning against structured filter/neuron removal that immediately shrinks dense GEMM matrix dimensions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Depthwise Separable Convolutions&lt;/strong&gt;: Factors a $K \times K \times C_{\text{in}} \times C_{\text{out}}$ convolution into a $K \times K$ spatial pass plus a $1 \times 1$ pointwise mix, cutting MACs by roughly $K^2 \approx 8\times$–$9\times$.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-symmetric-int8-quantization--depthwise-separable-flop-ratio&quot;&gt;Worked example: Symmetric INT8 Quantization &amp;amp; Depthwise-Separable FLOP Ratio&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Part A — Symmetric INT8 Quantization&lt;/strong&gt; ($q \in [-127, 127]$) of weight vector $w = [-0.635,\; 0.120,\; 1.270]$:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Find max absolute value: $\alpha = \max&lt;/td&gt;
          &lt;td&gt;w&lt;/td&gt;
          &lt;td&gt;= 1.270$.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;Compute scale: $s = \frac{1.270}{127} = 0.010$.&lt;/li&gt;
  &lt;li&gt;Quantize $q = \operatorname{round}(w / s)$:
\(q = [\operatorname{round}(-63.5),\; \operatorname{round}(12.0),\; \operatorname{round}(127.0)] = [-64,\; 12,\; 127].\)&lt;/li&gt;
  &lt;li&gt;Dequantize $\hat{w} = s \cdot q$:
\(\hat{w} = [-0.640,\; 0.120,\; 1.270], \quad \text{max error } |w - \hat{w}| = 0.005 \text{ (exactly } s/2\text{!)}.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Part B — Depthwise Separable Parameter Reduction&lt;/strong&gt; for $K = 3, C_{\text{in}} = 64, C_{\text{out}} = 128$:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Standard Conv2d: $3 \times 3 \times 64 \times 128 = 73{,}728$ weights.&lt;/li&gt;
  &lt;li&gt;Depthwise ($3 \times 3 \times 64$) + Pointwise ($1 \times 1 \times 64 \times 128$): $576 + 8{,}192 = 8{,}768$ weights ($8.41\times$ fewer!).
    &lt;ol&gt;
      &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Both quantization error ($s/2$) and separable-conv savings ($\frac{1}{C_{\text{out}}} + \frac{1}{K^2}$) can be calculated on the back of an envelope before touching a GPU.&lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h1 id=&quot;efficient-deep-learning-compression-and-acceleration&quot;&gt;Efficient Deep Learning: Compression and Acceleration&lt;/h1&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;As deep learning models have grown to billions of parameters, deploying them on resource-constrained devices (mobile phones, embedded systems, edge devices) or serving them at scale (millions of queries) has become challenging. Model compression techniques reduce model size, memory footprint, and computational requirements while maintaining accuracy, enabling deployment in scenarios where full models are impractical. These techniques—pruning, quantization, knowledge distillation, and efficient architectures—represent crucial engineering innovations making deep learning accessible beyond cloud servers with powerful GPUs.&lt;/p&gt;

&lt;p&gt;Pruning removes unnecessary parameters or connections, exploiting the observation that many neural network weights contribute minimally to outputs. Studies show networks remain effective after removing 50-90% of weights, suggesting significant redundancy. Structured pruning removes entire filters or layers, providing hardware-friendly speedups. Unstructured pruning removes individual weights, achieving higher compression but requiring specialized hardware for acceleration.&lt;/p&gt;

&lt;p&gt;Quantization reduces numerical precision, representing weights and activations with fewer bits (8-bit integers instead of 32-bit floats), reducing memory by 4× and enabling faster integer arithmetic on many processors. Post-training quantization applies to trained models without retraining. Quantization-aware training includes quantization in the training loop, allowing the network to adapt to reduced precision.&lt;/p&gt;

&lt;p&gt;Knowledge distillation transfers knowledge from large “teacher” networks to small “student” networks by training students to match teacher predictions (soft targets) rather than just hard labels. Students learn from teacher’s uncertainty and similarities between classes, often achieving better performance than training on labels alone despite being much smaller. &lt;strong&gt;For LLM-era distillation&lt;/strong&gt; — why full-vocab logit matching is awkward, synthetic-data / response distillation, and legitimate vs unauthorized use — see &lt;strong&gt;Chapter 26&lt;/strong&gt;, lesson &lt;strong&gt;26-05&lt;/strong&gt;. This lesson stays with the classical, fixed-output-space picture.&lt;/p&gt;

&lt;p&gt;Efficient architectures like MobileNet and EfficientNet are designed for efficiency from the start through depthwise separable convolutions, neural architecture search, and careful scaling. These achieve competitive accuracy with fraction of computation/parameters compared to standard architectures.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;h3 id=&quot;pruning&quot;&gt;Pruning&lt;/h3&gt;

&lt;p&gt;Define importance score for parameter \(w\):&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;$$I(w) =&lt;/td&gt;
      &lt;td&gt;\frac{\partial \mathcal{L}}{\partial w}&lt;/td&gt;
      &lt;td&gt;$$ (magnitude pruning)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;or&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;$$I(w) =&lt;/td&gt;
      &lt;td&gt;w \cdot \frac{\partial \mathcal{L}}{\partial w}&lt;/td&gt;
      &lt;td&gt;$$ (Taylor expansion approximation)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Remove weights with \(I(w) &amp;lt; \tau\) (threshold). After pruning, fine-tune remaining weights.&lt;/p&gt;

&lt;h3 id=&quot;quantization&quot;&gt;Quantization&lt;/h3&gt;

&lt;p&gt;Map continuous values to discrete levels. For 8-bit quantization:&lt;/p&gt;

\[w_{\text{quant}} = \text{round}\left(\frac{w - w_{\min}}{w_{\max} - w_{\min}} \cdot 255\right)\]

&lt;p&gt;Dequantize for computation:&lt;/p&gt;

\[w \approx w_{\min} + w_{\text{quant}} \cdot \frac{w_{\max} - w_{\min}}{255}\]

&lt;h3 id=&quot;knowledge-distillation&quot;&gt;Knowledge Distillation&lt;/h3&gt;

&lt;p&gt;Student network trained on soft targets from teacher:&lt;/p&gt;

\[\mathcal{L} = \alpha \mathcal{L}_{\text{hard}}(y, \hat{y}_{\text{student}}) + (1-\alpha) \mathcal{L}_{\text{soft}}(\hat{y}_{\text{teacher}}, \hat{y}_{\text{student}})\]

&lt;p&gt;Soft targets use temperature \(T\):&lt;/p&gt;

\[p_i = \frac{\exp(z_i/T)}{\sum_j \exp(z_j/T)}\]

&lt;p&gt;Higher \(T\) creates softer distributions revealing teacher’s uncertainty.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Imagine compressing a ResNet-50 (25M parameters, 4GB memory). Pruning might find that 60% of weights have magnitude &amp;lt; 0.001 and contribute negligibly. Removing these yields 10M parameters, 1.6GB—60% reduction with minimal accuracy loss.&lt;/p&gt;

&lt;p&gt;Quantization to INT8 (8-bit integers) from FP32 (32-bit floats) gives 4× memory reduction: 10M parameters now only 10MB vs 40MB. Combined with pruning: 2.5GB → 1GB → 250MB—10× total compression.&lt;/p&gt;

&lt;p&gt;Knowledge distillation transfers this compressed model’s knowledge to a MobileNet (4M parameters). The MobileNet learns from ResNet’s soft predictions, achieving 75% accuracy versus 70% training on labels alone—the extra 5% comes from learning what ResNet thinks about hard examples.&lt;/p&gt;

&lt;p&gt;Final: 4M parameters, 40MB INT8 model achieving 75% accuracy versus original 25M parameters, 4GB FP32 achieving 78% accuracy. 100× smaller, 10× faster inference, only 3% accuracy loss—enabling mobile deployment!&lt;/p&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Pruning example
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;magnitude_prune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sparsity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Remove smallest magnitude weights&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;modules&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;isinstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;or&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;isinstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;quantile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sparsity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Quantization
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;quantize_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_bits&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Quantize tensor to num_bits&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;qmin&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;qmax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_bits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;min_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;qmax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;qmin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clamp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;qmin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;qmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_val&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Knowledge distillation
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;distillation_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;teacher_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Combine hard and soft targets&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;hard_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;soft_student&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;student_logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;soft_teacher&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;teacher_logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;soft_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;kl_div&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;soft_student&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;soft_teacher&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reduction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;batchmean&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hard_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;soft_loss&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Model compression connects to neural architecture search (NAS), which discovers efficient architectures automatically. NAS explores architecture space, evaluating candidates by accuracy-efficiency tradeoffs.&lt;/p&gt;

&lt;p&gt;Compression relates to lottery ticket hypothesis: random networks contain subnetworks that, when trained, match full network performance. Finding these “winning tickets” provides alternative to post-training pruning.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1506.02626&quot;&gt;“Learning both Weights and Connections for Efficient Neural Networks” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Song Han, Jeff Pool, John Tran, William Dally&lt;br /&gt;
Introduced magnitude-based pruning achieving 9-13× compression on AlexNet and VGGNet with minimal accuracy loss.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1503.02531&quot;&gt;“Distilling the Knowledge in a Neural Network” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Geoffrey Hinton, Oriol Vinyals, Jeff Dean&lt;br /&gt;
Knowledge distillation paper showing student networks learn better from teacher predictions than from labels alone.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1704.04861&quot;&gt;“MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Andrew Howard et al.&lt;br /&gt;
MobileNets use depthwise separable convolutions, reducing computation 8-9× versus standard convolutions while maintaining accuracy.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Model compression makes deep learning practical on resource-constrained devices through pruning (removing unnecessary parameters), quantization (reducing numerical precision), knowledge distillation (transferring large model knowledge to small models), and efficient architectures (designed for efficiency from scratch). These techniques enable 10-100× compression with minimal accuracy loss, democratizing deep learning deployment beyond cloud servers to edge devices, enabling real-time inference, and reducing environmental impact through lower computational requirements.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 15&lt;/td&gt;
          &lt;td&gt;Efficient Methods and Hardware for Deep Learning](https://www.youtube.com/watch?v=eZdOkDtYMoo) — Stanford University School of Engineering, English. Pruning, quantization, and the hardware constraints together.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, English. Low-precision weights, the quantization section’s subject.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[2.3 Knowledge Distillation&lt;/td&gt;
          &lt;td&gt;Geoffery Hinton&lt;/td&gt;
          &lt;td&gt;Soft Labels&lt;/td&gt;
          &lt;td&gt;Softmax with Temperature](https://www.youtube.com/watch?v=g1r4Esohw-g) — AI_Snippets, English. Hinton’s soft labels and temperature, the classical distillation the lesson stops at before Chapter 26.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>23 Efficient Deep Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter23/23_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter23/23_00_Introduction</id>
   <content type="html">&lt;p&gt;A state-of-the-art model that needs four $30,000 GPUs and 800 milliseconds per inference is a research demo, not a product. Efficient Deep Learning asks a sharper engineering question: how much of a neural network’s memory footprint, FLOPs, and energy is genuinely essential, and how much can be stripped away via &lt;strong&gt;pruning&lt;/strong&gt;, &lt;strong&gt;quantization&lt;/strong&gt;, &lt;strong&gt;knowledge distillation&lt;/strong&gt;, and &lt;strong&gt;hardware-aware architectures&lt;/strong&gt; without surrendering accuracy?&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-four-levers-of-efficient-deep-learning&quot;&gt;Key ideas: The Four Levers of Efficient Deep Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Pruning (Unstructured vs. Structured)&lt;/strong&gt;: Removes low-magnitude weights (high theoretical sparsity) or entire channels/heads (real wall-clock GPU speedup without specialized sparse kernels).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Quantization (FP32 → FP16/BF16 → INT8/INT4)&lt;/strong&gt;: Maps continuous weights and activations onto low-bit integer grids, slashing VRAM footprint and memory-bandwidth bottlenecks by $2\times$–$8\times$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Knowledge Distillation&lt;/strong&gt;: Trains a compact student model to mimic a large teacher’s softened probability distributions (“dark knowledge”), preserving inter-class similarity structure.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Hardware-Aware Architectures &amp;amp; Roofline Thinking&lt;/strong&gt;: Uses depthwise separable convolutions (MobileNet) and compound scaling (EfficientNet), optimizing for &lt;em&gt;memory bandwidth&lt;/em&gt; (bytes moved) as much as raw FLOPs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-memory--bandwidth-reduction-from-fp32-to-int4&quot;&gt;Worked example: Memory &amp;amp; Bandwidth Reduction from FP32 to INT4&lt;/h3&gt;

&lt;p&gt;Consider a 7-billion-parameter ($7 \times 10^9$) dense neural network deployed on a GPU with $320\text{ GB/s}$ memory bandwidth.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Weight storage footprint&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;FP32 ($4\text{ bytes/param}$): $7 \times 10^9 \times 4 = 28.0\text{ GB}$ (won’t even fit on a 24 GB GPU!).&lt;/li&gt;
      &lt;li&gt;FP16/BF16 ($2\text{ bytes/param}$): $14.0\text{ GB}$.&lt;/li&gt;
      &lt;li&gt;INT8 ($1\text{ byte/param}$): $7.0\text{ GB}$.&lt;/li&gt;
      &lt;li&gt;INT4 ($0.5\text{ bytes/param}$): $3.5\text{ GB}$ ($8\times$ smaller than FP32!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Memory-bound single-token decode latency lower bound&lt;/strong&gt; (reading all weights once per token):
    &lt;ul&gt;
      &lt;li&gt;FP16: $14.0\text{ GB} / 320\text{ GB/s} = 43.75\text{ ms/token}$ ($\approx 22.9\text{ tok/s}$).&lt;/li&gt;
      &lt;li&gt;INT4: $3.5\text{ GB} / 320\text{ GB/s} = 10.94\text{ ms/token}$ ($\approx 91.4\text{ tok/s}$ — a $4\times$ speedup!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Because autoregressive decoding is memory-bandwidth bound, shrinking weight bit-width delivers an almost linear speedup in tokens per second, not just disk savings.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Efficient deep learning makes models faster, smaller, and more deployable. This chapter covers model compression (pruning, quantization, knowledge distillation), efficient architectures (MobileNet, EfficientNet), hardware acceleration (GPUs, TPUs), mixed-precision training, and deployment strategies for edge devices and production systems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After pruning/quantization/distillation, see &lt;strong&gt;23-99 Modern Applications and Updates&lt;/strong&gt; for GPTQ, AWQ, GGUF, and speculative decoding.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LLM distillation hub:&lt;/strong&gt; Classical KD in &lt;strong&gt;23-01&lt;/strong&gt; is the fixed-class recipe. For modern LLM students (synthetic data, white-box features/logits, serving-vs-distill decisions) see &lt;strong&gt;Chapter 26&lt;/strong&gt;. Speculative decoding as a &lt;em&gt;serving&lt;/em&gt; loop (not a student) is &lt;strong&gt;26-04&lt;/strong&gt;; FLOP / KV accounting is &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 15&lt;/td&gt;
          &lt;td&gt;Efficient Methods and Hardware for Deep Learning](https://www.youtube.com/watch?v=eZdOkDtYMoo) — Stanford University School of Engineering, English. CS231n’s efficient-methods lecture is this chapter’s menu (prune, quantize, distill).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, English. Quantization, the method the chapter’s modern note leans on.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jrJKRYAdh7I&quot;&gt;Knowledge Distillation: How LLMs train each other&lt;/a&gt; — Julia Turc, English. Distillation, the teacher-student method.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>22-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter22/22_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter22/22_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Standard message-passing GNNs are nearsighted: a 2-layer GCN can only see 2 hops away, and trying to route long-range signals through a narrow graph bottleneck causes &lt;em&gt;over-squashing&lt;/em&gt;. Between 2022 and 2026, geometric deep learning broke that barrier by fusing global Transformer attention with graph structural encodings (GraphGPS) and 3D equivariant diffusion (AlphaFold 3)—predicting joint structures of proteins, DNA, RNA, and small-molecule ligands at atomic precision.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-modern-geometric--graph-deep-learning-20222026&quot;&gt;Key ideas: Modern Geometric &amp;amp; Graph Deep Learning (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Graph Transformers &amp;amp; Structural Encodings&lt;/strong&gt;: Allows every node to attend globally to every other node while injecting graph topology via Laplacian eigenvectors, random-walk landing probabilities, or shortest-path attention biases (Graphormer, GraphGPS).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — 3D Equivariance &amp;amp; AlphaFold 3&lt;/strong&gt;: Combines Pairformer relational attention with diffusion directly over 3D atomic coordinates, respecting $\text{SE}(3)$ rotations and translations without brittle handcrafted torsion angles.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Industrial Heterogeneous Graphs&lt;/strong&gt;: Scales GNNs to billion-edge user–item–creator recommendation graphs (PinSage, PyG) using temporal neighbor sampling and multi-relation message passing.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Hybrid Local + Global Layers&lt;/strong&gt;: Pairs a local MPNN (inductive bias for immediate bonds/edges) with global self-attention (long-range communication) in parallel within every block.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-shortest-path-attention-bias-in-a-graph-transformer&quot;&gt;Worked example: Computing Shortest-Path Attention Bias in a Graph Transformer&lt;/h3&gt;

&lt;p&gt;Consider a 4-node linear molecule $1 - 2 - 3 - 4$. Suppose raw dot-product attention logits from node 1 to all 4 nodes are equal: $q_1^\top k_j / \sqrt{d} = [1.0, 1.0, 1.0, 1.0]$. A Graphormer layer adds a learned shortest-path bias $b(\text{spd}(1, j))$ where $b(0) = 0.5,\; b(1) = 0.2,\; b(2) = -0.3,\; b(3) = -0.8$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute biased attention logits $z_{1j} = 1.0 + b(\text{spd}(1, j))$&lt;/strong&gt;:
\(z_1 = [1.5,\; 1.2,\; 0.7,\; 0.2].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply Softmax&lt;/strong&gt;:
\(e^{1.5} = 4.482, \quad e^{1.2} = 3.320, \quad e^{0.7} = 2.014, \quad e^{0.2} = 1.221 \implies Z = 11.037.\)
\(\alpha_1 = [40.6\%,\; 30.1\%,\; 18.2\%,\; 11.1\%].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Unlike a 1-hop GCN (which puts $0\%$ weight on nodes 3 and 4), the Graph Transformer lets node 1 communicate directly with node 4 ($11.1\%$ weight) in a single layer while still honoring graph distance.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-gnns-after-message-passing--graph-transformers-and-alphafold-3&quot;&gt;Optional: GNNs after message passing — graph Transformers and AlphaFold 3&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace message passing, permutation invariance, or the GCN-style update. It covers 2022–2025 models that mix &lt;strong&gt;attention on graphs&lt;/strong&gt; with classical MPNN layers, plus the structure-prediction products that made GNNs famous outside recsys.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The MPNN step&lt;/p&gt;

\[\mathbf{h}_i^{(t+1)} = \mathrm{UPD}\Big(\mathbf{h}_i^{(t)},\; \mathrm{AGG}_{j\in\mathcal{N}(i)} \mathrm{MSG}(\mathbf{h}_i^{(t)},\mathbf{h}_j^{(t)},e_{ij})\Big)\]

&lt;p&gt;is still the right first algorithm. Many SOTA models now let &lt;strong&gt;every node attend to many others&lt;/strong&gt; (Graphormer, GraphGPS) when the graph is small enough (molecules, proteins).&lt;/p&gt;

&lt;h2 id=&quot;1-graph-transformers&quot;&gt;1. Graph Transformers&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2106.05234&quot;&gt;Ying et al., 2021&lt;/a&gt; (Graphormer) and &lt;a href=&quot;https://arxiv.org/abs/2205.12454&quot;&gt;Rampášek et al., 2022&lt;/a&gt; (GraphGPS) add Laplacian / spatial encodings so a Transformer respects graph distance. Use them on molecules (hundreds of nodes), not on a 10M-node social graph — there you still want neighbor sampling (GraphSAGE) as in the theory notes.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;alphafold-3&quot;&gt;AlphaFold 3&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://www.nature.com/articles/s41586-024-07487-w&quot;&gt;Abramson et al., 2024&lt;/a&gt; (AlphaFold 3) predict biomolecular complexes with a &lt;strong&gt;diffusion&lt;/strong&gt; module on atom coordinates plus a pair/token trunk. The pairwise trunk is the intellectual descendant of attention-on-graphs from AlphaFold 2. Application: drug discovery and structural biology, not a new GCN formula.&lt;/p&gt;

&lt;h3 id=&quot;recsys-and-knowledge-graphs&quot;&gt;Recsys and knowledge graphs&lt;/h3&gt;

&lt;p&gt;Production recommenders still run &lt;strong&gt;bipartite GNNs&lt;/strong&gt; or two-tower embeddings (PinSage-class). 2023–2025 papers add LLM features on nodes; the aggregator stays a GNN.&lt;/p&gt;

&lt;h3 id=&quot;software&quot;&gt;Software&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/pyg-team/pytorch_geometric&quot;&gt;pyg-team/pytorch_geometric&lt;/a&gt; 2.x — &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;TransformerConv&lt;/code&gt;, GraphGPS examples.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/dmlc/dgl&quot;&gt;dmlc/dgl&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google-deepmind/alphafold3&quot;&gt;google-deepmind/alphafold3&lt;/a&gt; (inference code, 2024+).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;3-citations-20222026&quot;&gt;3. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.12454&quot;&gt;Recipe for a General, Powerful, Scalable Graph Transformer — GraphGPS (Rampášek et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2106.05234&quot;&gt;Do Transformers Really Perform Badly for Graph Representation? — Graphormer (Ying et al., 2021)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.nature.com/articles/s41586-024-07487-w&quot;&gt;Accurate structure prediction of biomolecular interactions with AlphaFold 3 (Abramson et al., 2024)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-how-this-complements-the-core-notes&quot;&gt;4. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Write a message-passing layer first. This lesson only adds &lt;strong&gt;graph Transformers&lt;/strong&gt; and &lt;strong&gt;AlphaFold 3&lt;/strong&gt; as the applications that cite this chapter’s ideas in 2024–2026.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=eGoszzMkGfU&quot;&gt;Graph Neural Networks Explained: A Clear Guide to GNN Basics &amp;amp; Models&lt;/a&gt; — IBM Technology, English. Message passing is what a graph transformer still does, with a learned attention mask.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=1DmNdMUbDkg&quot;&gt;Message Passing: How Graph Neural Networks Actually Work&lt;/a&gt; — The Synthetic Mind, English. A single round, so the graph-transformer block has a baseline.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. Self-attention is the mixer that block uses once neighbors are not the only tokens it may read.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>22-01 Graph Neural Networks</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter22/22_01_GNN_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter22/22_01_GNN_Fundamentals</id>
   <content type="html">&lt;p&gt;At first glance, the Graph Convolutional Network (GCN) update rule $H^{(l+1)} = \sigma(\tilde{D}^{-1/2}\tilde{A}\tilde{D}^{-1/2} H^{(l)} W^{(l)})$ looks intimidating—until you unpack it into three crystal-clear operations: add self-loops so a node remembers itself ($\tilde{A} = A + I$), normalize by $\sqrt{\tilde{d}_i \tilde{d}_j}$ so high-degree hubs do not explode feature scales, and mix features with a shared weight matrix $W$. Yet stack too many GCN layers and every node’s representation blurs into the same average—the infamous &lt;strong&gt;over-smoothing&lt;/strong&gt; phenomenon.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mathematical-core-of-gcn-graphsage-and-gat&quot;&gt;Key ideas: Mathematical Core of GCN, GraphSAGE, and GAT&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Symmetric Spectral Normalization ($\tilde{D}^{-1/2}\tilde{A}\tilde{D}^{-1/2}$)&lt;/strong&gt;: Derives Kipf &amp;amp; Welling’s first-order Chebyshev approximation to spectral graph convolutions, preventing hub nodes from dominating gradient magnitudes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Inductive Neighborhood Sampling (GraphSAGE)&lt;/strong&gt;: Samples a fixed number of neighbors per layer and concatenates &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self || agg(neighbors)&lt;/code&gt;, enabling generalization to unseen nodes and billion-edge graphs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Anisotropic Attention (GAT)&lt;/strong&gt;: Replaces fixed degree weights with learned edge attention coefficients $\alpha_{ij} = \operatorname{softmax}_j(\text{LeakyReLU}(a^\top[Wh_i | Wh_j]))$ so nodes focus on their most informative neighbors.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Over-Smoothing, Over-Squashing, and Expressivity&lt;/strong&gt;: Explains why deep GNNs lose node distinctiveness (fixed point of Laplacian smoothing) and why 1-WL message passing cannot distinguish certain non-isomorphic graphs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-one-exact-gcn-layer-on-a-3-node-path&quot;&gt;Worked example: Computing One Exact GCN Layer on a 3-Node Path&lt;/h3&gt;

&lt;p&gt;Consider the 3-node path $1 - 2 - 3$ with self-loops $\tilde{A} = A + I = \begin{bmatrix}1&amp;amp;1&amp;amp;0\1&amp;amp;1&amp;amp;1\0&amp;amp;1&amp;amp;1\end{bmatrix}$, degree matrix $\tilde{D} = \operatorname{diag}(2, 3, 2)$, scalar features $H^{(0)} = \begin{bmatrix}2\ 3\ 6\end{bmatrix}$, and weight $W = [1]$ with ReLU.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute $\tilde{D}^{-1/2} = \operatorname{diag}(1/\sqrt{2},\; 1/\sqrt{3},\; 1/\sqrt{2}) \approx \operatorname{diag}(0.7071,\; 0.5774,\; 0.7071)$&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute normalized message weights $\hat{A}&lt;em&gt;{ij} = \frac{\tilde{A}&lt;/em&gt;{ij}}{\sqrt{\tilde{d}_i \tilde{d}_j}}$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;$\hat{A}&lt;em&gt;{11} = \frac{1}{2} = 0.500$, $\quad \hat{A}&lt;/em&gt;{12} = \frac{1}{\sqrt{6}} \approx 0.4082$.&lt;/li&gt;
      &lt;li&gt;$\hat{A}&lt;em&gt;{21} = \hat{A}&lt;/em&gt;{23} = \frac{1}{\sqrt{6}} \approx 0.4082$, $\quad \hat{A}_{22} = \frac{1}{3} \approx 0.3333$.&lt;/li&gt;
      &lt;li&gt;$\hat{A}&lt;em&gt;{32} = 0.4082$, $\quad \hat{A}&lt;/em&gt;{33} = 0.500$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute $H^{(1)} = \operatorname{ReLU}(\hat{A} H^{(0)} W)$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Node 1: $0.500(2) + 0.4082(3) = 1.000 + 1.225 = 2.225$.&lt;/li&gt;
      &lt;li&gt;Node 2: $0.4082(2) + 0.3333(3) + 0.4082(6) = 0.816 + 1.000 + 2.449 = 4.265$.&lt;/li&gt;
      &lt;li&gt;Node 3: $0.4082(3) + 0.500(6) = 1.225 + 3.000 = 4.225$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Notice how the initial spread $[2, 3, 6]$ tightened toward $[2.23, 4.27, 4.23]$ in just one layer—illustrating both local neighborhood smoothing and why stacking 20 GCN layers without residual connections collapses all nodes together.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;graph-neural-networks-deep-learning-on-graphs&quot;&gt;Graph Neural Networks: Deep Learning on Graphs&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://distill.pub/2021/gnn-intro/graph_neural_network.png&quot; alt=&quot;Graph Neural Network&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc Graph Neural Network với message passing. Nguồn: Distill.pub&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Graph Neural Networks extend deep learning to graph-structured data, enabling neural networks to process networks of entities and relationships that pervade real-world data: social networks connecting people, molecular graphs connecting atoms, knowledge graphs linking concepts, citation networks relating papers, and recommendation systems connecting users and items. Unlike images (regular 2D grids) or sequences (1D chains), graphs have arbitrary structure—variable numbers of neighbors, no spatial ordering, complex connectivity patterns—requiring specialized neural architectures that can leverage this structure while remaining differentiable and trainable via backpropagation.&lt;/p&gt;

&lt;p&gt;The fundamental challenge graphs present is permutation invariance: a graph’s representation shouldn’t depend on how we order its nodes. If nodes are numbered 1,2,3 versus 3,2,1, the graph is identical, so representations should be too. This rules out naive approaches like feeding adjacency matrices to standard neural networks (which treat different orderings as different inputs). GNNs solve this through message passing: nodes iteratively aggregate information from neighbors through learned transformations, with aggregation functions (sum, mean, max) that are permutation-invariant. After several iterations, each node’s representation incorporates information from its neighborhood, with larger neighborhoods accessible through more iterations.&lt;/p&gt;

&lt;p&gt;Understanding GNNs requires appreciating that different graph learning tasks require different outputs. Node classification predicts labels for nodes (categorizing users in social networks). Link prediction predicts missing or future edges (recommending friendships or products). Graph classification predicts labels for entire graphs (classifying molecules as active/inactive for drugs). Each task uses the same message passing framework but differs in how node representations are aggregated and what predictions are made.&lt;/p&gt;

&lt;p&gt;The applications of GNNs span diverse domains. In chemistry, molecular graphs (atoms as nodes, bonds as edges) are processed by GNNs to predict properties like solubility or toxicity. In social networks, GNNs detect communities, predict friendships, or identify influential users. In recommender systems, bipartite graphs (users and items) are processed to predict preferences. In protein structure prediction, GNNs model amino acid interactions. In traffic prediction, road networks inform forecasting. This versatility demonstrates that graph structure is ubiquitous, and GNNs provide a general framework for learning from it.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;A graph \(\mathcal{G} = (\mathcal{V}, \mathcal{E})\) consists of nodes \(\mathcal{V} = \{v_1, \ldots, v_n\}\) and edges \(\mathcal{E} \subseteq \mathcal{V} \times \mathcal{V}\). Nodes have features \(\mathbf{x}_i \in \mathbb{R}^d\), and edges may have features \(\mathbf{e}_{ij}\). The adjacency matrix \(\mathbf{A} \in \{0,1\}^{n \times n}\) encodes structure: \(A_{ij} = 1\) if edge \((v_i, v_j) \in \mathcal{E}\), else 0.&lt;/p&gt;

&lt;h3 id=&quot;message-passing-framework&quot;&gt;Message Passing Framework&lt;/h3&gt;

&lt;p&gt;GNNs update node representations through iterative message passing. At layer \(k\), node \(i\)’s representation \(\mathbf{h}_i^{(k)}\) is updated based on neighbors:&lt;/p&gt;

\[\mathbf{h}_i^{(k)} = \text{UPDATE}^{(k)}\left(\mathbf{h}_i^{(k-1)}, \text{AGGREGATE}^{(k)}\left(\{\mathbf{h}_j^{(k-1)} : j \in \mathcal{N}(i)\}\right)\right)\]

&lt;p&gt;where \(\mathcal{N}(i)\) are neighbors of \(i\). AGGREGATE combines neighbor features (must be permutation-invariant), UPDATE combines node’s own features with aggregated neighbor information.&lt;/p&gt;

&lt;h3 id=&quot;graph-convolutional-networks-gcn&quot;&gt;Graph Convolutional Networks (GCN)&lt;/h3&gt;

&lt;p&gt;GCN uses spectral graph theory, defining convolution through graph Laplacian. The practical form:&lt;/p&gt;

\[\mathbf{H}^{(k+1)} = \sigma(\tilde{\mathbf{D}}^{-1/2}\tilde{\mathbf{A}}\tilde{\mathbf{D}}^{-1/2}\mathbf{H}^{(k)}\mathbf{W}^{(k)})\]

&lt;p&gt;where \(\tilde{\mathbf{A}} = \mathbf{A} + \mathbf{I}\) (adjacency plus self-loops), \(\tilde{\mathbf{D}}\) is degree matrix, \(\mathbf{H}^{(k)}\) are node representations at layer \(k\), \(\mathbf{W}^{(k)}\) are learned weights.&lt;/p&gt;

&lt;p&gt;This performs weighted aggregation of neighbors followed by linear transformation and nonlinearity, with weights inversely proportional to node degrees (high-degree nodes contribute less per neighbor).&lt;/p&gt;

&lt;h3 id=&quot;graphsage&quot;&gt;GraphSAGE&lt;/h3&gt;

&lt;p&gt;GraphSAGE samples fixed-size neighborhoods and uses learned aggregation:&lt;/p&gt;

\[\mathbf{h}_{\mathcal{N}(i)}^{(k)} = \text{AGGREGATE}(\{\mathbf{h}_j^{(k-1)} : j \in \mathcal{N}(i)\})\]

\[\mathbf{h}_i^{(k)} = \sigma(\mathbf{W}^{(k)} \cdot [\mathbf{h}_i^{(k-1)}, \mathbf{h}_{\mathcal{N}(i)}^{(k)}])\]

&lt;p&gt;AGGREGATE can be mean, max, or LSTM over neighborhood. This enables mini-batch training and handles variable-size neighborhoods.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Consider a social network: nodes are people, edges are friendships, node features include age, location, interests. We want to predict which users will like a new product (node classification).&lt;/p&gt;

&lt;p&gt;A 2-layer GNN works as follows. Initially, each user’s representation \(\mathbf{h}_i^{(0)}\) is their raw features. After layer 1, \(\mathbf{h}_i^{(1)}\) incorporates information from immediate friends (1-hop neighbors). User A’s representation now includes “my friends are ages 25-30, mostly in urban areas, interested in tech”—aggregated neighbor information. After layer 2, \(\mathbf{h}_i^{(2)}\) incorporates friends-of-friends (2-hop neighborhood). User A’s representation captures broader social context.&lt;/p&gt;

&lt;p&gt;For prediction, the network learns that users whose neighborhoods have certain patterns (many tech-interested friends, urban clustering) are likely to like tech products. The GNN provides features capturing both individual attributes and social context for classification.&lt;/p&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GCNLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single Graph Convolutional Layer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Parameter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xavier_uniform_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (num_nodes, in_features)
        adj: (num_nodes, num_nodes) adjacency matrix
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Add self-loops
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;adj_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Normalize
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;deg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;deg_inv_sqrt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;deg_inv_sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deg_inv_sqrt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;inf&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;diag&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deg_inv_sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;adj_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;norm&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Apply convolution
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;support&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;support&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GCN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2-layer Graph Convolutional Network&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gc1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GCNLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gc2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GCNLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_nodes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;gcn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GCN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Random graph
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_nodes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Symmetric
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gcn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adj&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GCN output: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (100, 7)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Each node gets class predictions using graph structure!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;GNNs connect to spectral graph theory through their mathematical foundations. Graph Laplacians and eigendecompositions provide theoretical basis for defining convolution on graphs, generalizing CNNs’ convolution from regular grids to arbitrary graphs.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1609.02907&quot;&gt;“Semi-Supervised Classification with Graph Convolutional Networks” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Thomas Kipf, Max Welling&lt;br /&gt;
Introduced GCN, establishing message passing on graphs as effective deep learning approach. Demonstrated semi-supervised node classification using graph structure plus limited labels.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.02216&quot;&gt;“Inductive Representation Learning on Large Graphs” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: William Hamilton, Rex Ying, Jure Leskovec&lt;br /&gt;
GraphSAGE enabled learning on large graphs through neighborhood sampling, allowing mini-batch training. Extended GNNs from transductive (fixed graph) to inductive (generalizing to new nodes/graphs).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1710.10903&quot;&gt;“Graph Attention Networks” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Petar Veličković, Guilermo Cucurull, Arantxa Casanova, Adriana Romero, Pietro Liò, Yoshua Bengio&lt;br /&gt;
GAT used attention mechanisms to weight neighbor contributions, learning importance of different neighbors. More flexible than fixed aggregation.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;Oversmoothing occurs with many GNN layers—node representations become indistinguishable as they aggregate from increasingly large neighborhoods. Use skip connections, batch normalization, or careful depth selection (2-3 layers often sufficient).&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Graph Neural Networks process graph-structured data through message passing, iteratively updating node representations by aggregating information from neighbors through learned, permutation-invariant functions. GCNs use normalized adjacency matrices for spectral graph convolution. GraphSAGE samples neighborhoods for scalability. Graph attention networks learn neighbor importance through attention. Applications span social networks, molecules, knowledge graphs, and recommendation systems. GNNs enable deep learning on irregular, relational data where CNNs and RNNs don’t apply, opening graph-structured domains to modern AI.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=eGoszzMkGfU&quot;&gt;Graph Neural Networks Explained: A Clear Guide to GNN Basics &amp;amp; Models&lt;/a&gt; — IBM Technology, English. Nodes, edges, and a permutation-invariant update.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=1DmNdMUbDkg&quot;&gt;Message Passing: How Graph Neural Networks Actually Work&lt;/a&gt; — The Synthetic Mind, English. The sum-over-neighbors step the lesson’s formula writes.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Linear transformations and matrices&lt;/td&gt;
          &lt;td&gt;Chapter 3, Essence of linear algebra](https://www.youtube.com/watch?v=kYB8IZa5AuE) — 3Blue1Brown, English. The linear map applied after that sum is an ordinary matrix, which is easy to forget.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>22 Graph Neural Networks</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter22/22_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter22/22_00_Introduction</id>
   <content type="html">&lt;p&gt;Images live on neat 2D grids and text lives on 1D lines—so CNNs and RNNs always know which pixel is “above” or which word comes “next.” Now look at a caffeine molecule, a citation network, or a fraud ring: there is no “left” or “right,” every node has a different number of neighbors, and relabeling node 1 as node 7 does not change the object at all. Graph Neural Networks (GNNs) generalize deep learning to arbitrary relational structures by enforcing &lt;strong&gt;permutation equivariance&lt;/strong&gt; through iterative neighborhood message passing.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-foundations-of-deep-learning-on-graphs&quot;&gt;Key ideas: Foundations of Deep Learning on Graphs&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Graph Representations &amp;amp; Adjacency Algebra&lt;/strong&gt;: Encodes structure via adjacency matrix $A \in {0,1}^{N \times N}$, degree matrix $D$, graph Laplacian $L = D - A$, and node feature matrix $X \in \mathbb{R}^{N \times F}$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Permutation Invariance &amp;amp; Equivariance&lt;/strong&gt;: Guarantees that shuffling node indices $P X, P A P^\top$ produces identically shuffled node embeddings $P H$ (node tasks) or unchanged graph predictions (graph tasks).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Message Passing Neural Networks (MPNN)&lt;/strong&gt;: Unifies GCN, GraphSAGE, and GAT into three differentiable steps: compute neighbor messages, aggregate with a permutation-invariant reducer (sum/mean/max/attention), and update node states.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Graph Task Taxonomy&lt;/strong&gt;: Separates node classification (fraud detection), link prediction (recommendations), and graph-level property prediction (molecular toxicity).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-checking-permutation-equivariance-on-a-3-node-path-graph&quot;&gt;Worked example: Checking Permutation Equivariance on a 3-Node Path Graph&lt;/h3&gt;

&lt;p&gt;Consider a 3-node path $1 - 2 - 3$ with adjacency matrix $A = \begin{bmatrix}0&amp;amp;1&amp;amp;0\1&amp;amp;0&amp;amp;1\0&amp;amp;1&amp;amp;0\end{bmatrix}$ and scalar node features $x = \begin{bmatrix}10\20\30\end{bmatrix}$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;One step of raw neighbor-sum message passing $h = Ax$&lt;/strong&gt;:
\(h = \begin{bmatrix}0&amp;amp;1&amp;amp;0\\1&amp;amp;0&amp;amp;1\\0&amp;amp;1&amp;amp;0\end{bmatrix}\begin{bmatrix}10\\20\\30\end{bmatrix} = \begin{bmatrix}20\\40\\20\end{bmatrix}.\)
(Node 2 receives $10 + 30 = 40$; endpoints receive $20$.)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Permute node order by swapping node 1 and node 3&lt;/strong&gt; ($P = \begin{bmatrix}0&amp;amp;0&amp;amp;1\0&amp;amp;1&amp;amp;0\1&amp;amp;0&amp;amp;0\end{bmatrix}$):
$x’ = Px = [30, 20, 10]^\top$, $A’ = PAP^\top = A$.
\(h&apos; = A&apos;x&apos; = \begin{bmatrix}20\\40\\20\end{bmatrix} = Ph.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Graph-level readout via sum pooling&lt;/strong&gt;: $\sum h_i = \sum h’_i = 80$ (strictly permutation &lt;strong&gt;invariant&lt;/strong&gt;!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Matrix multiplication by $A$ paired with symmetric aggregators mathematically guarantees that node-ID ordering can never corrupt a GNN’s predictions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Graph Neural Networks (GNNs) extend deep learning to graph-structured data: social networks, molecules, knowledge graphs, and recommendation systems. This chapter covers graph representations, message passing, Graph Convolutional Networks (GCN), GraphSAGE, Graph Attention Networks (GAT), and applications in node classification, link prediction, and graph generation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After message passing, see &lt;strong&gt;22-99 Modern Applications and Updates&lt;/strong&gt; for graph Transformers and AlphaFold 3.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=eGoszzMkGfU&quot;&gt;Graph Neural Networks Explained: A Clear Guide to GNN Basics &amp;amp; Models&lt;/a&gt; — IBM Technology, English. A graph neural net passes messages along edges, which is this chapter.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=1DmNdMUbDkg&quot;&gt;Message Passing: How Graph Neural Networks Actually Work&lt;/a&gt; — The Synthetic Mind, English. One round of that message passing, in more detail.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>21-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter21/21_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter21/21_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Between 2022 and 2026, Deep RL moved from Atari games to the center of frontier AI: RLHF with PPO aligned ChatGPT, Direct Preference Optimization (DPO) showed you can optimize the exact same KL-regularized reward objective without training a separate reward model, and Group Relative Policy Optimization (GRPO) removed the critic network entirely to train math and coding reasoning models (like DeepSeek-R1) directly from verifiable outcomes.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-post-dqn-deep-rl-for-alignment--reasoning-20222026&quot;&gt;Key ideas: Post-DQN Deep RL for Alignment &amp;amp; Reasoning (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — RLHF with PPO &amp;amp; KL Regularization&lt;/strong&gt;: Maximizes $\mathbb{E}[r_\phi(x, y)] - \beta\, D_{\text{KL}}(\pi_\theta | \pi_{\text{ref}})$ so the policy improves human preference scores without drifting into gibberish reward hacks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Direct Preference Optimization (DPO)&lt;/strong&gt;: Applies the closed-form optimal policy $r(x, y) = \beta \log \frac{\pi^*(y \mid x)}{\pi_{\text{ref}}(y \mid x)} + \beta \log Z(x)$ inside the Bradley–Terry preference model, turning RLHF into a pure supervised binary cross-entropy loss on $(y_w, y_l)$ pairs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Group Relative Policy Optimization (GRPO)&lt;/strong&gt;: Samples a group of $G$ completions ${y_1, \dots, y_G}$ for the same prompt, scores them with a verifier (unit tests / math grader), and normalizes group rewards into advantages $\hat{A}_i = \frac{r_i - \bar{r}}{\text{std}(r)}$—cutting memory by dropping the value critic.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Learned World Models&lt;/strong&gt;: Trains latent dynamics models (DreamerV3, Genie) so agents can imagine rollouts inside a learned simulator before acting in the real world.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-dpo-loss--grpo-group-advantages-by-hand&quot;&gt;Worked example: Computing DPO Loss &amp;amp; GRPO Group Advantages by Hand&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Part A — DPO Loss&lt;/strong&gt;: For prompt $x$, chosen response $y_w$, and rejected response $y_l$ with $\beta = 0.1$, suppose log-probability ratios are $\log\frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} = +2.0$ and $\log\frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)} = -1.0$.&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Implicit reward margin: $\Delta = \beta(2.0 - (-1.0)) = 0.1 \times 3.0 = +0.30$.&lt;/li&gt;
  &lt;li&gt;DPO loss: $\mathcal{L}_{\text{DPO}} = -\ln\sigma(0.30) = -\ln(0.5744) \approx 0.5544\text{ nats}$.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Part B — GRPO Group Advantages&lt;/strong&gt;: Suppose for one math prompt we sample $G = 4$ chains of thought and our verifier awards binary correctness rewards $r = [1, 0, 1, 0]$.&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Mean $\bar{r} = 0.50$, standard deviation $\sigma_r = \sqrt{\frac{4 \times 0.25}{4}} = 0.50$.&lt;/li&gt;
  &lt;li&gt;Group-relative advantages: $\hat{A} = \left[\frac{1-0.5}{0.5}, \frac{0-0.5}{0.5}, \frac{1-0.5}{0.5}, \frac{0-0.5}{0.5}\right] = [+1,\; -1,\; +1,\; -1]$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Both DPO and GRPO eliminate heavy components of classic PPO (reward model in DPO; critic network in GRPO) while keeping the exact mathematical backbone of KL-regularized policy optimization.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-deep-rl-after-dqnppo--rlhf-dpo-and-grpo&quot;&gt;Optional: deep RL after DQN/PPO — RLHF, DPO, and GRPO&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace DQN, replay, or PPO theory (the core notes already mention RLHF in passing). It is the 2022–2026 &lt;strong&gt;alignment&lt;/strong&gt; stack that made deep RL visible outside games.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;PPO still maximizes a clipped surrogate. Language alignment added a &lt;strong&gt;reward model&lt;/strong&gt; and then, quickly, methods that &lt;strong&gt;skip the RL loop&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;1-rlhf-with-ppo&quot;&gt;1. RLHF with PPO&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Ouyang et al., 2022&lt;/a&gt; and &lt;a href=&quot;https://arxiv.org/abs/2204.05862&quot;&gt;Bai et al., 2022&lt;/a&gt; (Anthropic HH):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;SFT on demonstrations,&lt;/li&gt;
  &lt;li&gt;train \(r_\phi\) on pairwise preferences,&lt;/li&gt;
  &lt;li&gt;optimize the policy with PPO against \(r_\phi\) plus a KL to the SFT model.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That is Chapter 21’s actor–critic applied to tokens. It is expensive (value model, sampling, instability).&lt;/p&gt;

&lt;h2 id=&quot;2-dpo-preferences-without-a-reward-model&quot;&gt;2. DPO: preferences without a reward model&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Rafailov et al., 2023&lt;/a&gt; rewrite the RLHF optimum as a &lt;strong&gt;classification&lt;/strong&gt; loss on pairs \((y_w, y_l)\):&lt;/p&gt;

\[\mathcal{L}_{\mathrm{DPO}} = -\log\sigma\Big(\beta\log\frac{\pi_\theta(y_w|x)}{\pi_{\mathrm{ref}}(y_w|x)} - \beta\log\frac{\pi_\theta(y_l|x)}{\pi_{\mathrm{ref}}(y_l|x)}\Big).\]

&lt;p&gt;No sampling loop at train time. DPO and cousins (IPO, KTO, ORPO) became the default open-source alignment recipe in 2024–2025 (&lt;a href=&quot;https://github.com/huggingface/trl&quot;&gt;trl&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;3-concrete-applications&quot;&gt;3. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;grpo-and-reasoning-model-training&quot;&gt;GRPO and reasoning-model training&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2402.03300&quot;&gt;Shao et al., 2024&lt;/a&gt; (DeepSeekMath) introduce &lt;strong&gt;Group Relative Policy Optimization&lt;/strong&gt;: several samples per prompt, advantages from the group’s own rewards — no learned value net. Later reasoning models (DeepSeek-R1-class, 2025) popularized this family.&lt;/p&gt;

&lt;h3 id=&quot;world-models&quot;&gt;World models&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2301.04104&quot;&gt;Hafner et al., 2023&lt;/a&gt; (DreamerV3) learn a latent MDP (VAE-like) and plan inside it. Complementary to LLM-RL: still deep RL, not chat.&lt;/p&gt;

&lt;h3 id=&quot;software&quot;&gt;Software&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/trl&quot;&gt;huggingface/trl&lt;/a&gt; — PPO, DPO, GRPO trainers.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/OpenRLHF/OpenRLHF&quot;&gt;OpenRLHF&lt;/a&gt; / &lt;a href=&quot;https://github.com/volcengine/verl&quot;&gt;verl&lt;/a&gt; — distributed RLHF.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/vwxyzjn/cleanrl&quot;&gt;CleanRL&lt;/a&gt; and &lt;a href=&quot;https://github.com/DLR-RM/stable-baselines3&quot;&gt;Stable-Baselines3&lt;/a&gt; — classic deep RL, not LLMs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;InstructGPT (Ouyang et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.18290&quot;&gt;Direct Preference Optimization (Rafailov et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2402.03300&quot;&gt;DeepSeekMath — GRPO (Shao et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2301.04104&quot;&gt;DreamerV3 (Hafner et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Implement DQN/PPO ideas from the chapter first. This lesson only adds &lt;strong&gt;preference optimization for LMs&lt;/strong&gt; (RLHF/DPO/GRPO) — not a new Bellman backup. The Chapter 26 map (SFT → reward / PPO → DPO, with the same DPO display) is &lt;strong&gt;26-03&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8jtAzxUwDj0&quot;&gt;Proximal Policy Optimization (PPO) for LLMs Explained Intuitively&lt;/a&gt; — Julia Turc, English. PPO is the policy-gradient method this note uses for RLHF.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=k2pD3k1485A&quot;&gt;Direct Preference Optimization (DPO) - How to fine-tune LLMs directly without reinforcement learning&lt;/a&gt; — Luis Serrano Academy, English. DPO, the preference objective the note sets beside PPO.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qPN_XZcJf_s&quot;&gt;Reinforcement Learning with Human Feedback (RLHF), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. The human-feedback loop both algorithms are optimizing.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>21-01 Deep Reinforcement Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter21/21_01_Deep_RL/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter21/21_01_Deep_RL</id>
   <content type="html">&lt;p&gt;Why did naive neural Q-learning diverge so violently before DeepMind’s 2013–2015 DQN breakthrough? Imagine trying to learn to hit a dartboard while someone moves the bullseye every time you throw a dart—and every throw comes from the same corner of the room. Experience Replay shuffles past transitions to restore i.i.d. mini-batches, while a frozen Target Network nails the bullseye in place for thousands of gradient steps; together with policy gradients and actor–critic advantages, they form the complete engine of modern Deep RL.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mathematical--algorithmic-engine-of-deep-rl&quot;&gt;Key ideas: Mathematical &amp;amp; Algorithmic Engine of Deep RL&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — The Deadly Triad &amp;amp; DQN Fixes&lt;/strong&gt;: Explains how Experience Replay decorrelates sequential frames and Target Networks $Q_{\theta^-}$ stabilize Bellman targets $y_i = r_i + \gamma \max_{a’} Q_{\theta^-}(s’_i, a’)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Overestimation Bias &amp;amp; Double DQN&lt;/strong&gt;: Shows why $\max_{a’} Q(s’, a’)$ systematically overestimates noisy Q-values and how decoupling action &lt;em&gt;selection&lt;/em&gt; ($\arg\max Q_\theta$) from &lt;em&gt;evaluation&lt;/em&gt; ($Q_{\theta^-}$) eliminates it.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Policy Gradient Theorem &amp;amp; Baseline Subtraction&lt;/strong&gt;: Proves $\nabla_\theta J(\theta) = \mathbb{E}[\sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)(G_t - b(s_t))]$ remains strictly unbiased for any state-only baseline $b(s_t)$ while slashing gradient variance.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Frame Stacking &amp;amp; Temporal Observability&lt;/strong&gt;: Stacks $4$ consecutive $84 \times 84$ grayscale Atari frames &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 84, 84)&lt;/code&gt; so a single Markov state encodes ball velocity and direction, not just static position.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-dqn-loss--reinforce-gradient-with-a-baseline&quot;&gt;Worked example: Computing DQN Loss &amp;amp; REINFORCE Gradient with a Baseline&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Part A — DQN Huber/MSE Loss&lt;/strong&gt;: Suppose for a transition $(s, a, r=1.0, s’, \text{done}=0)$ with $\gamma = 0.99$, the online network predicts $Q_\theta(s, a) = 5.0$, and the frozen target network outputs $Q_{\theta^-}(s’, \cdot) = [4.0, 10.0, 6.0]$.&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Target: $y = 1.0 + 0.99 \times \max(4.0, 10.0, 6.0) = 1.0 + 9.9 = 10.9$.&lt;/li&gt;
  &lt;li&gt;Squared TD loss: $\mathcal{L}&lt;em&gt;{\text{DQN}} = \frac{1}{2}(y - Q&lt;/em&gt;\theta)^2 = \frac{1}{2}(10.9 - 5.0)^2 = \frac{1}{2}(34.81) = 17.405$.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Part B — REINFORCE Baseline Variance Reduction&lt;/strong&gt;: Suppose in state $s$, action $a_1$ has $\nabla_\theta \log \pi(a_1 \mid s) = +1.0$ with return $G = 102$, and action $a_2$ has $\nabla_\theta \log \pi(a_2 \mid s) = -1.0$ with return $G = 98$.&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Without baseline: gradient samples are $+102$ and $-98$ (huge magnitude, high variance!).&lt;/li&gt;
  &lt;li&gt;With baseline $b(s) = V(s) = 100$: advantages are $A_1 = +2$ and $A_2 = -2$, yielding gradient samples $+2$ and $+2$ (exact same mean $+2$, &lt;strong&gt;zero variance&lt;/strong&gt;!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Subtracting $V(s)$ does not bias the expected policy gradient by a single decimal place, yet collapses gradient noise by orders of magnitude.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;deep-reinforcement-learning-neural-networks-meet-sequential-decision-making&quot;&gt;Deep Reinforcement Learning: Neural Networks Meet Sequential Decision Making&lt;/h1&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Deep Reinforcement Learning combines the representation learning power of deep neural networks with the sequential decision-making framework of reinforcement learning, enabling agents to learn complex behaviors directly from high-dimensional sensory inputs like images or raw sensor data. While classical RL required hand-crafted feature representations and could only handle low-dimensional state spaces, deep RL learns both the representation and the policy end-to-end, scaling to problems previously intractable: playing video games from pixels, controlling robots from camera inputs, mastering chess and Go at superhuman levels, and learning complex manipulation skills through trial and error.&lt;/p&gt;

&lt;p&gt;The key insight making deep RL work is using neural networks as function approximators for value functions or policies. Instead of maintaining explicit tables \(Q(s,a)\) for every state-action pair (impossible for high-dimensional states like 84×84×4 Atari frames with \(256^{84 \times 84 \times 4} \approx 10^{67000}\) possible states), we approximate \(Q(s,a) \approx Q(s,a;\theta)\) with a neural network parameterized by \(\theta\). The network learns to generalize across similar states—having learned to recognize enemies in one game location, it applies this knowledge to other locations—enabling learning from feasible amounts of experience rather than requiring exhaustive exploration.&lt;/p&gt;

&lt;p&gt;However, combining deep learning with RL introduces unique challenges absent in either field individually. RL generates its own training data through interaction, creating correlations between sequential samples that violate the i.i.d. assumption underlying standard neural network training. The target values in Q-learning are non-stationary—they depend on the current Q-network which is constantly updating, creating a moving target that can cause instability. The exploration-exploitation tradeoff becomes more critical when actions affect what data the agent sees, potentially causing the agent to get stuck in sub-optimal behaviors that prevent discovering better alternatives.&lt;/p&gt;

&lt;p&gt;Deep Q-Networks (DQN), introduced by DeepMind in 2013, solved these challenges through two key innovations: experience replay and target networks. Experience replay stores past experiences in a buffer and samples uniformly for training, breaking temporal correlations and allowing reuse of rare experiences. Target networks provide stable targets by updating slowly, preventing the oscillations that occur when chasing a constantly moving target. These techniques, combined with careful architecture design and training procedures, enabled learning to play Atari games directly from pixels at human or superhuman levels—a watershed moment demonstrating deep learning could tackle sequential decision-making at scale.&lt;/p&gt;

&lt;p&gt;The success of deep RL extends far beyond games. AlphaGo combined deep neural networks with Monte Carlo tree search to defeat world champions at Go, a game previously thought to require decades more progress. Robotic systems learn manipulation skills through deep RL, discovering strategies humans never explicitly programmed. Language models are fine-tuned through reinforcement learning from human feedback (RLHF), aligning them with human preferences for helpfulness and safety. Autonomous vehicles learn driving policies through simulation and real-world interaction. Understanding deep RL opens this vast application space while providing insights into how systems can learn complex behaviors through interaction rather than passive observation.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;Deep Q-Networks extend Q-learning to continuous state spaces through neural function approximation. The Q-function is approximated as \(Q(s,a;\theta)\) where \(\theta\) are neural network parameters. Given transition \((s_t, a_t, r_t, s_{t+1})\), standard Q-learning updates:&lt;/p&gt;

\[Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha[r_t + \gamma \max_{a&apos;} Q(s_{t+1}, a&apos;) - Q(s_t, a_t)]\]

&lt;p&gt;With neural networks, this becomes a gradient descent update minimizing squared TD error:&lt;/p&gt;

\[\mathcal{L}(\theta) = \mathbb{E}_{(s,a,r,s&apos;) \sim \mathcal{D}}\left[\left(r + \gamma \max_{a&apos;} Q(s&apos;, a&apos;; \theta^-) - Q(s,a;\theta)\right)^2\right]\]

&lt;p&gt;where \(\mathcal{D}\) is experience replay buffer and \(\theta^-\) are target network parameters (updated periodically from \(\theta\)).&lt;/p&gt;

&lt;p&gt;The gradient with respect to \(\theta\) is:&lt;/p&gt;

\[\nabla_\theta \mathcal{L}(\theta) = \mathbb{E}\left[\left(r + \gamma \max_{a&apos;} Q(s&apos;, a&apos;; \theta^-) - Q(s,a;\theta)\right) \nabla_\theta Q(s,a;\theta)\right]\]

&lt;p&gt;Notice the target \(r + \gamma \max_{a&apos;} Q(s&apos;, a&apos;; \theta^-)\) is treated as constant (no gradient through \(\theta^-\)), preventing unstable feedback loops that would occur if targets depended on parameters being optimized.&lt;/p&gt;

&lt;h3 id=&quot;experience-replay&quot;&gt;Experience Replay&lt;/h3&gt;

&lt;p&gt;The replay buffer \(\mathcal{D}\) stores recent transitions: \(\mathcal{D} = \{(s_i, a_i, r_i, s_i&apos;)\}_{i=1}^N\) with capacity \(N\) (typically 100K-1M). Each training iteration:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Agent takes action, observes transition, adds to \(\mathcal{D}\)&lt;/li&gt;
  &lt;li&gt;Sample mini-batch uniformly from \(\mathcal{D}\)&lt;/li&gt;
  &lt;li&gt;Compute loss and gradient on mini-batch&lt;/li&gt;
  &lt;li&gt;Update \(\theta\) via gradient descent&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Uniform sampling breaks temporal correlations (adjacent experiences are correlated, but random samples from buffer aren’t), stabilizing training. Reusing experiences improves sample efficiency—each experience can be used in multiple updates rather than once.&lt;/p&gt;

&lt;h3 id=&quot;target-network&quot;&gt;Target Network&lt;/h3&gt;

&lt;p&gt;Maintain two networks: online network \(Q(s,a;\theta)\) updated every step, and target network \(Q(s,a;\theta^-)\) updated periodically (every \(C\) steps):&lt;/p&gt;

\[\theta^- \leftarrow \theta \quad \text{every } C \text{ steps}\]

&lt;p&gt;This provides stable targets for \(C\) steps, preventing the moving target problem where both the prediction and target change simultaneously, causing oscillations. Typical \(C = 10,000\) steps.&lt;/p&gt;

&lt;h3 id=&quot;policy-gradient-methods&quot;&gt;Policy Gradient Methods&lt;/h3&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;An alternative to value-based RL directly parameterizes the policy $$\pi(a&lt;/td&gt;
      &lt;td&gt;s;\theta)$$. The objective is expected return:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\left[\sum_{t=0}^T \gamma^t r_t\right]\]

&lt;p&gt;The policy gradient theorem gives:&lt;/p&gt;

\[\nabla_\theta J(\theta) = \mathbb{E}_{\tau \sim \pi_\theta}\left[\sum_{t=0}^T \nabla_\theta \log \pi_\theta(a_t|s_t) \cdot G_t\right]\]

&lt;p&gt;where \(G_t = \sum_{k=t}^T \gamma^{k-t} r_k\) is return from time \(t\). This remarkable result says we can estimate the gradient by sampling trajectories, computing returns, and weighting log-probabilities of actions by returns. High-return actions get positive weight (increase probability), low-return actions get negative weight (decrease probability).&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Actor-Critic methods combine value and policy learning. The actor (policy $$\pi(a&lt;/td&gt;
      &lt;td&gt;s;\theta)\() selects actions, the critic (value function\)V(s;\phi)$$) evaluates them. The actor updates using policy gradient with advantage:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[\nabla_\theta J(\theta) \propto \nabla_\theta \log \pi_\theta(a_t|s_t) \cdot A(s_t, a_t)\]

&lt;p&gt;where \(A(s_t, a_t) = Q(s_t, a_t) - V(s_t)\) is advantage (how much better than average this action is). The critic updates to better estimate values, providing better advantage estimates for the actor.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Imagine teaching an agent to play Pong from pixel inputs. The state is an 84×84 grayscale image showing paddles and ball. Actions are {up, down, stay}. The agent must learn to move the paddle to hit the ball—a simple task for humans but challenging for RL.&lt;/p&gt;

&lt;p&gt;Initially, the agent takes random actions. Occasionally it hits the ball by chance, receiving +1 reward. The DQN updates Q-values for states/actions leading to this reward. For the state “ball approaching my paddle from upper-left,” action “move up” gets higher Q-value. Through thousands of games, patterns emerge:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Ball high, paddle low → move up has high Q-value&lt;/li&gt;
  &lt;li&gt;Ball low, paddle high → move down has high Q-value&lt;/li&gt;
  &lt;li&gt;Ball middle, paddle middle → stay has high Q-value&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The neural network learns these patterns not through explicit rules but by associating visual patterns (ball position relative to paddle) with action values. Crucially, it learns the dynamics: where the ball will be, not just where it is now, enabling anticipatory control.&lt;/p&gt;

&lt;p&gt;The experience replay buffer contains diverse situations: paddle at top with ball approaching, paddle at bottom with ball far away, etc. Uniformly sampling this buffer prevents the network from forgetting how to handle situations it hasn’t seen recently—a problem called catastrophic forgetting that would occur if training only on the current game state.&lt;/p&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Complete DQN implementation:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;collections&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;deque&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DQN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Deep Q-Network for Atari-style games.
    
    Architecture: Conv layers extract features from frames,
    fully connected layers output Q-values for each action.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DQN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Input: (batch, 4, 84, 84) - 4 stacked frames
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Calculate conv output size
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;conv_output_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Fully connected layers
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Q-value per action
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;x: (batch, 4, 84, 84) stacked frames&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ReplayBuffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Experience replay buffer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;buffer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;deque&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;maxlen&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;push&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__len__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DQNAgent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Complete DQN agent with experience replay and target network&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;state_shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Online and target networks
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DQN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DQN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;load_state_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;state_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.00025&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;memory&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ReplayBuffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;capacity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.99&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon_decay&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.995&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_update_freq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;select_action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ε-greedy action selection&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;state_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;q_values&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q_values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single training step on mini-batch from replay buffer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;memory&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Sample mini-batch
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rewards&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dones&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;memory&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Convert to tensors
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LongTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;rewards&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rewards&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;next_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dones&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute current Q-values
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;current_q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gather&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute target Q-values using target network
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;next_q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;target_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;target_q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rewards&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_q&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute loss
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;current_q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Optimize
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Gradient clipping for stability
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip_grad_norm_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Update target network periodically
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_update_freq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;load_state_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;state_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Decay epsilon
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon_decay&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Deep Q-Network (DQN) Agent&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate DQN components
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;84&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;84&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 4 stacked frames
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DQNAgent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state_shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DQN Components:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Policy network: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;policy_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Target network: Same architecture, updated every &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_update_freq&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; steps&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Replay buffer: Capacity &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;memory&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;maxlen&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Batch size: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Discount γ: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Initial ε: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (decays to &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;agent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon_min&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simulate training loop structure
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DQN Training Loop:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  1. Select action using ε-greedy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  2. Execute in environment, observe reward and next state&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  3. Store transition in replay buffer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  4. Sample mini-batch from buffer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  5. Compute Q-learning loss with target network&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  6. Update policy network via gradient descent&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  7. Periodically copy policy → target network&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This combination of techniques enables stable deep RL training!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Deep RL connects to supervised learning through imitation learning. Instead of learning from rewards, agents can learn from expert demonstrations—supervised learning on (state, action) pairs. This often provides better initialization than random policies, with subsequent RL fine-tuning adapting to the specific environment.&lt;/p&gt;

&lt;p&gt;The relationship to evolutionary strategies shows alternative optimization approaches. Instead of gradient-based policy improvement, evolve population of policies through selection and mutation. Deep neuroevolution has achieved competitive results, particularly for tasks where gradients are unreliable.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.5602&quot;&gt;“Playing Atari with Deep Reinforcement Learning” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Volodymyr Mnih et al. (DeepMind)&lt;br /&gt;
DQN paper showed deep networks could learn control policies from pixels, combining Q-learning with deep CNN function approximation, experience replay, and target networks. Achieved human-level performance on multiple Atari games, launching deep RL revolution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.nature.com/articles/nature14236&quot;&gt;“Human-level control through deep reinforcement learning” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Volodymyr Mnih et al. (DeepMind)&lt;br /&gt;
Nature publication demonstrating DQN achieving human-level performance across 49 Atari games with single architecture and hyperparameters. Established deep RL as viable approach for complex control from high-dimensional inputs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1602.01783&quot;&gt;“Asynchronous Methods for Deep Reinforcement Learning” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Volodymyr Mnih et al.&lt;br /&gt;
A3C parallelized RL across multiple agents, removing need for experience replay through asynchronous updates. Achieved better performance with less training time, establishing actor-critic methods as alternative to value-based approaches.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1707.06347&quot;&gt;“Proximal Policy Optimization Algorithms” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, Oleg Klimov&lt;br /&gt;
PPO simplified policy gradient methods while maintaining performance through clipped surrogate objective preventing excessively large policy updates. Became de facto standard for policy gradient RL due to simplicity and robustness.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.nature.com/articles/nature24270&quot;&gt;“Mastering the game of Go without human knowledge” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: David Silver et al. (DeepMind)&lt;br /&gt;
AlphaGo Zero achieved superhuman Go performance through pure self-play without human data, using deep RL with MCTS. Demonstrated RL’s potential for discovering novel strategies surpassing human knowledge.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;Reward shaping can help or hurt. Providing intermediate rewards for subgoals speeds learning but might create unintended behaviors (agent learns to maximize shaped rewards instead of true objective). Use carefully and validate final behavior on true rewards.&lt;/p&gt;

&lt;p&gt;Hyperparameter sensitivity in deep RL exceeds supervised learning. Learning rate, replay buffer size, update frequency, exploration schedule—all significantly affect performance. Extensive tuning often necessary. Start with published hyperparameters for similar tasks.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Deep reinforcement learning combines neural networks with RL, using networks as function approximators for value functions or policies, enabling learning from high-dimensional inputs like images. DQN uses experience replay to break temporal correlations and target networks for stable Q-learning targets, achieving human-level Atari game performance. Policy gradient methods directly optimize policy networks through REINFORCE or actor-critic approaches, often more stable than value methods for continuous actions. Deep RL has achieved remarkable successes including mastering Go, robotic control, and game playing, while remaining challenging due to sample inefficiency, hyperparameter sensitivity, and training instability. Understanding deep RL requires appreciating both RL foundations (MDPs, value functions, exploration) and deep learning techniques (CNNs for vision, gradient descent, architecture design), combining both fields’ insights to create agents that learn complex behaviors through interaction.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 14&lt;/td&gt;
          &lt;td&gt;Deep Reinforcement Learning](https://www.youtube.com/watch?v=lvoHnicueoE) — Stanford University School of Engineering, English. Both DQN and policy gradients in one lecture.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=x83WmvbRa2I&quot;&gt;Deep Q-Networks Explained!&lt;/a&gt; — CodeEmporium, English. The Q-network and the replay buffer, at a slower pace.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KHZVXao4qXs&quot;&gt;RL Course by David Silver - Lecture 7: Policy Gradient Methods&lt;/a&gt; — Google DeepMind, English. David Silver’s policy-gradient lecture, the other half of the lesson.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>21 Deep Reinforcement Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter21/21_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter21/21_00_Introduction</id>
   <content type="html">&lt;p&gt;Atari Breakout has $210 \times 160 \times 3$ RGB pixels—more possible screen states than atoms in the observable universe—making tabular Q-tables completely impossible. Yet simply plugging a neural network into Q-Learning initially blew up in catastrophic divergence. Deep Reinforcement Learning was born when researchers tamed that “deadly triad” (function approximation + bootstrapping + off-policy learning) with experience replay, target networks, and clipped policy gradients—culminating in DQN, PPO, AlphaGo, and LLM reasoning models.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-core-paradigms-of-deep-rl&quot;&gt;Key ideas: Core Paradigms of Deep RL&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Deep Q-Networks (DQN) &amp;amp; Stabilization&lt;/strong&gt;: Combines convolutional Q-function approximators with Experience Replay (breaking temporal correlation) and a periodically frozen Target Network (preventing chasing a moving TD target).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Policy Gradient Methods (REINFORCE)&lt;/strong&gt;: Optimizes a parameterized stochastic policy $\pi_\theta(a \mid s)$ directly via the log-derivative trick $\nabla_\theta J(\theta) = \mathbb{E}[\nabla_\theta \log \pi_\theta(a \mid s)\,A(s, a)]$, naturally handling continuous action spaces.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Actor–Critic &amp;amp; Variance Reduction (A2C / PPO)&lt;/strong&gt;: Pairs a learned policy (&lt;em&gt;Actor&lt;/em&gt;) with a learned value baseline (&lt;em&gt;Critic&lt;/em&gt;) to compute low-variance Advantages $A_t = Q_t - V_t$, and clips policy ratios (PPO) to prevent destructive updates.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Sample Efficiency vs. Wall-Clock Scalability&lt;/strong&gt;: Contrasts off-policy replay methods (DQN, SAC) with on-policy parallelized rollouts (PPO, GRPO).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-a-clipped-ppo-surrogate-objective&quot;&gt;Worked example: Computing a Clipped PPO Surrogate Objective&lt;/h3&gt;

&lt;p&gt;Suppose at a state–action pair $(s, a)$ with positive advantage $\hat{A} = +2.0$, the old policy had probability $\pi_{\text{old}}(a \mid s) = 0.25$ and the updated policy has $\pi_\theta(a \mid s) = 0.40$, with PPO clip parameter $\epsilon = 0.2$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the importance sampling ratio $r(\theta)$&lt;/strong&gt;:
\(r(\theta) = \frac{\pi_\theta(a \mid s)}{\pi_{\text{old}}(a \mid s)} = \frac{0.40}{0.25} = 1.60.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute unclipped and clipped surrogate terms&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Unclipped: $r(\theta)\hat{A} = 1.60 \times 2.0 = 3.20$.&lt;/li&gt;
      &lt;li&gt;Clipped ratio: $\operatorname{clip}(1.60,\; 1 - 0.2,\; 1 + 0.2) = \operatorname{clip}(1.60,\; 0.8,\; 1.2) = 1.20$.&lt;/li&gt;
      &lt;li&gt;Clipped objective: $1.20 \times 2.0 = 2.40$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Take the pessimistic minimum&lt;/strong&gt;:
\(L^{\text{CLIP}} = \min(3.20,\; 2.40) = 2.40.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Because $r(\theta) = 1.60$ already exceeded $1 + \epsilon = 1.20$, the gradient of $L^{\text{CLIP}}$ with respect to $\theta$ drops to &lt;strong&gt;zero&lt;/strong&gt;—automatically stopping the optimizer from over-committing to a single lucky rollout.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Deep Reinforcement Learning combines deep neural networks with RL to handle high-dimensional state spaces. This chapter covers DQN (Deep Q-Network), policy gradient methods (REINFORCE, A3C), actor-critic methods (A2C, PPO), and applications like game playing (AlphaGo) and robotics. We explore how deep learning enables RL to solve complex real-world problems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After DQN/PPO, see &lt;strong&gt;21-99 Modern Applications and Updates&lt;/strong&gt; for RLHF, DPO, and GRPO in language-model alignment.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 14&lt;/td&gt;
          &lt;td&gt;Deep Reinforcement Learning](https://www.youtube.com/watch?v=lvoHnicueoE) — Stanford University School of Engineering, English. CS231n’s deep-RL lecture is this chapter (DQN and policy gradients).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8JVRbHAVCws&quot;&gt;MIT 6.S191 (2024): Reinforcement Learning&lt;/a&gt; — Alexander Amini, English. MIT’s 2024 telling of the same chapter.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=x83WmvbRa2I&quot;&gt;Deep Q-Networks Explained!&lt;/a&gt; — CodeEmporium, English. DQN, the value-based half.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>20-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter20/20_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter20/20_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;You might think tabular MDPs only live in toy GridWorlds—until you realize that every modern recommendation feed, dynamic pricing engine, and RLHF LLM post-training run is literally an MDP. In RLHF, the state is the prompt plus tokens generated so far, the action is the next token from the vocabulary, the policy is the LLM itself, and the reward arrives at the end of the response from a preference model or verifier.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-classical-rl-concepts-in-production-20222026&quot;&gt;Key ideas: Classical RL Concepts in Production (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — RLHF as a Token-Level MDP&lt;/strong&gt;: Maps prompt-to-response generation directly onto $(\mathcal{S}, \mathcal{A}, P, R, \gamma)$ with deterministic string-concatenation transitions and terminal reward plus per-token KL penalty.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Contextual Bandits in Ranking &amp;amp; RecSys&lt;/strong&gt;: Solves 1-step MDPs ($\gamma = 0$) where context $x$ is the user/session, actions $a$ are candidate items, and algorithms like LinUCB or Thompson Sampling balance revenue against exploration.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Offline / Batch RL &amp;amp; Propensity Weighting&lt;/strong&gt;: Learns improved policies strictly from logged historical interactions using Inverse Propensity Scoring (IPS) or Conservative Q-Learning (CQL) when live exploration is risky or expensive.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Sim-to-Real &amp;amp; Reward Hacking Prevention&lt;/strong&gt;: Tests policies in simulators before deployment and guards against Goodhart’s Law (where optimizing a proxy metric like clickbait destroys true user satisfaction).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-inverse-propensity-scoring-ips-for-offline-policy-evaluation&quot;&gt;Worked example: Inverse Propensity Scoring (IPS) for Offline Policy Evaluation&lt;/h3&gt;

&lt;p&gt;Suppose a logged recommendation system showed Item A with probability $\pi_0(A \mid x) = 0.20$ and observed click reward $r = 1.0$, and showed Item B with probability $\pi_0(B \mid x) = 0.80$ and observed reward $r = 0.0$. We want to evaluate a new candidate policy $\pi_{\text{new}}$ that puts probability $\pi_{\text{new}}(A \mid x) = 0.70$ and $\pi_{\text{new}}(B \mid x) = 0.30$—without deploying it live yet!&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute importance weights $w(a) = \frac{\pi_{\text{new}}(a \mid x)}{\pi_0(a \mid x)}$&lt;/strong&gt;:
\(w(A) = \frac{0.70}{0.20} = 3.50, \qquad w(B) = \frac{0.30}{0.80} = 0.375.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the IPS-estimated expected reward across these 2 logged impressions&lt;/strong&gt;:
\(\hat{V}_{\text{IPS}}(\pi_{\text{new}}) = \frac{1}{2}\big[w(A)\cdot 1.0 + w(B)\cdot 0.0\big] = \frac{3.50 + 0}{2} = 1.75\text{ (unclipped!)}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Self-Normalized IPS (SNIPS) to control variance&lt;/strong&gt;:
\(\hat{V}_{\text{SNIPS}} = \frac{w(A)\cdot 1.0 + w(B)\cdot 0.0}{w(A) + w(B)} = \frac{3.50}{3.50 + 0.375} = \frac{3.50}{3.875} \approx 0.903.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Notice how raw IPS can even exceed the maximum possible reward $1.0$ when logging propensities are small ($0.20$), which is why production offline RL systems rely on Self-Normalized IPS or clipped importance ratios.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-rl-fundamentals-in-production--bandits-recsys-and-rlhfs-mdp&quot;&gt;Optional: RL fundamentals in production — bandits, recsys, and RLHF’s MDP&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace MDPs, returns, or policy/value definitions. It shows where those objects showed up in 2022–2026 &lt;em&gt;data-science&lt;/em&gt; systems — especially preference-based language training.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;An MDP \((S,A,P,R,\gamma)\) is still the model. The surprising application: &lt;strong&gt;chat alignment&lt;/strong&gt; is an MDP whose “environment” is a human (or a reward model) scoring a whole transcript.&lt;/p&gt;

&lt;h2 id=&quot;1-rlhf-as-an-mdp-you-already-know&quot;&gt;1. RLHF as an MDP you already know&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Ouyang et al., 2022&lt;/a&gt; (InstructGPT) treat each prompt as a start state, tokens as actions, and a learned reward \(r_\phi\) as \(R\). PPO (Chapter 21) then maximizes&lt;/p&gt;

\[J(\theta) = \mathbb{E}_{\pi_\theta}[r_\phi] - \beta\, D_{\mathrm{KL}}(\pi_\theta \,\|\, \pi_{\mathrm{ref}}).\]

&lt;p&gt;The KL term is the same “don’t leave the behavior policy” idea as in conservative RL. Details of PPO/DPO wait for Chapter 21’s optional lesson; here the point is that &lt;strong&gt;Chapter 20’s vocabulary is what industry used&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;contextual-bandits-in-ranking&quot;&gt;Contextual bandits in ranking&lt;/h3&gt;

&lt;p&gt;News feeds and notifications are often &lt;strong&gt;bandits&lt;/strong&gt;, not full MDPs: one action, immediate reward (click). Libraries: &lt;a href=&quot;https://github.com/VowpalWabbit/vowpal_wabbit&quot;&gt;Vowpal Wabbit&lt;/a&gt;, &lt;a href=&quot;https://github.com/ray-project/ray&quot;&gt;Ray RLlib&lt;/a&gt;. The exploration–exploitation section of this chapter is the theory.&lt;/p&gt;

&lt;h3 id=&quot;offline--batch-rl-for-logs&quot;&gt;Offline / batch RL for logs&lt;/h3&gt;

&lt;p&gt;When you cannot reset a factory or a market, you learn from logged \((s,a,r,s&apos;)\). &lt;a href=&quot;https://arxiv.org/abs/2005.01643&quot;&gt;Levine et al., 2020&lt;/a&gt; survey offline RL; 2022–2025 applied work uses conservative Q-learning and fitted policies on recommender logs.&lt;/p&gt;

&lt;h3 id=&quot;simulation-before-the-real-reward&quot;&gt;Simulation before the real reward&lt;/h3&gt;

&lt;p&gt;Robotics and ads still build a simulator so the MDP is cheap. The definition of \(P\) and \(R\) in this chapter is the checklist for “is my simulator lying?”&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/Farama-Foundation/Gymnasium&quot;&gt;openai/gymnasium&lt;/a&gt; — the 2023+ fork of Gym.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/trl&quot;&gt;huggingface/trl&lt;/a&gt; — RLHF trainers (see Chapter 21).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/VowpalWabbit/vowpal_wabbit&quot;&gt;vw&lt;/a&gt; — production bandits.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.02155&quot;&gt;Training language models to follow instructions with human feedback — InstructGPT (Ouyang et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://gymnasium.farama.org/&quot;&gt;Gymnasium&lt;/a&gt; — maintained MDP API used in 2023–2026 courses.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2005.01643&quot;&gt;Offline Reinforcement Learning: Tutorial, Review, and Perspectives (Levine et al., 2020)&lt;/a&gt; — still the map for log-based DS work.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Learn states, returns, and Bellman equations first. This lesson only names the &lt;strong&gt;MDPs that shipped&lt;/strong&gt; (bandits, offline logs, RLHF) — not a new definition of a value function.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qPN_XZcJf_s&quot;&gt;Reinforcement Learning with Human Feedback (RLHF), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. RLHF is an MDP whose reward comes from human preferences, which is this note’s claim.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=T_X4XFwKX8k&quot;&gt;Reinforcement Learning from Human Feedback (RLHF) Explained&lt;/a&gt; — IBM Technology, English. A shorter corporate-lecture cut of the same loop.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=lfHX2hHRMVQ&quot;&gt;RL Course by David Silver - Lecture 2: Markov Decision Process&lt;/a&gt; — Google DeepMind, English. The MDP vocabulary the note says you already have.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>20-01 Reinforcement Learning Fundamentals</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter20/20_01_RL_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter20/20_01_RL_Fundamentals</id>
   <content type="html">&lt;p&gt;How does an agent learn the optimal route through a maze without ever seeing a map of the transition probabilities $P(s’ \mid s, a)$? In 1989, Chris Watkins proved that &lt;strong&gt;Q-Learning&lt;/strong&gt;—updating a simple lookup table $Q(s, a)$ by nudging it toward $r + \gamma \max_{a’} Q(s’, a’)$—is guaranteed to converge to the globally optimal action-value function $Q^*$ even while the agent follows an exploratory $\epsilon$-greedy policy. That off-policy bootstrapping trick is the ancestor of every value-based deep RL algorithm.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-bellman-equations-td-learning-and-q-learning&quot;&gt;Key ideas: Bellman Equations, TD Learning, and Q-Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Bellman Expectation vs. Bellman Optimality&lt;/strong&gt;: Distinguishes evaluating a fixed policy ($V^\pi$) from solving for the optimal policy ($V^&lt;em&gt;, Q^&lt;/em&gt;$) via the $\max_a$ operator.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Temporal-Difference (TD) Bootstrapping&lt;/strong&gt;: Updates value estimates after &lt;em&gt;every single step&lt;/em&gt; using the TD error $\delta_t = r + \gamma \max_{a’} Q(s’, a’) - Q(s, a)$ rather than waiting for episode termination (Monte Carlo).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — On-Policy (SARSA) vs. Off-Policy (Q-Learning)&lt;/strong&gt;: Contrasts learning the value of the exploratory policy actually executed (SARSA, safer near cliffs) against learning the greedy optimal policy from exploratory trajectories (Q-Learning).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Exploration Scheduling ($\epsilon$-Greedy)&lt;/strong&gt;: Guarantees infinite visitation of all state–action pairs early in training while annealing $\epsilon \to 0$ so the deployed policy exploits what it learned.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-one-exact-q-learning-update-step&quot;&gt;Worked example: One Exact Q-Learning Update Step&lt;/h3&gt;

&lt;p&gt;Suppose an agent is in state $s_1$, takes action $a = \text{Right}$, receives reward $r = -1$, and lands in state $s_2$. Current table values are:
\(Q(s_1, \text{Right}) = 4.0, \qquad Q(s_2, \text{Left}) = 2.0, \qquad Q(s_2, \text{Right}) = 8.0,\)
with learning rate $\alpha = 0.25$ and discount factor $\gamma = 0.9$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the TD target $y = r + \gamma \max_{a’} Q(s_2, a’)$&lt;/strong&gt;:
\(y = -1 + 0.9 \times \max(2.0, 8.0) = -1 + 7.2 = 6.2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Temporal-Difference (TD) error $\delta$&lt;/strong&gt;:
\(\delta = y - Q(s_1, \text{Right}) = 6.2 - 4.0 = +2.2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Update $Q(s_1, \text{Right})$&lt;/strong&gt;:
\(Q_{\text{new}}(s_1, \text{Right}) = 4.0 + 0.25(2.2) = 4.0 + 0.55 = 4.55.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Because the next state $s_2$ has a high value ($8.0$), Q-Learning pulls $Q(s_1, \text{Right})$ upward by $+0.55$ even though the immediate step cost $-1$—propagating future reward backward one step at a time.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;reinforcement-learning-learning-from-interaction&quot;&gt;Reinforcement Learning: Learning from Interaction&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Reinforcement_learning_diagram.svg/800px-Reinforcement_learning_diagram.svg.png&quot; alt=&quot;Reinforcement Learning Diagram&quot; /&gt;
&lt;em&gt;Hình ảnh: Sơ đồ Reinforcement Learning với agent, environment, actions và rewards. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Reinforcement learning represents a fundamentally different learning paradigm than the supervised and unsupervised learning we’ve studied. Instead of learning from labeled examples or discovering patterns in unlabeled data, RL agents learn by interacting with an environment, taking actions, observing outcomes, and receiving rewards. The agent’s goal is to discover a policy—a strategy for choosing actions—that maximizes cumulative reward over time. This trial-and-error learning with delayed rewards mirrors how humans and animals learn many skills: we try actions, experience consequences, and gradually improve our behavior to achieve desired outcomes.&lt;/p&gt;

&lt;p&gt;Understanding RL requires appreciating what makes it challenging compared to supervised learning. In supervised learning, we have correct answers for every input—the model learns from examples of optimal behavior. In RL, we only have rewards indicating how good outcomes were, not which specific actions were optimal. The agent must explore different actions to discover which lead to high rewards, creating an exploration-exploitation tradeoff: should we exploit known good actions or explore potentially better alternatives? Moreover, rewards are often delayed—an action’s consequences might not be apparent until many steps later (in chess, moves early in the game affect victory or defeat much later). Credit assignment becomes challenging: which of the many actions taken contributed to the final reward?&lt;/p&gt;

&lt;p&gt;The mathematical framework of Markov Decision Processes provides elegant formalization of sequential decision-making under uncertainty. States represent the environment’s configuration, actions are choices available to the agent, transitions describe how actions change states (potentially stochastically), and rewards provide learning signal. The Markov property—that the future depends only on the present state, not the full history—simplifies analysis while being approximately true for many real-world problems when states are chosen appropriately. Value functions quantify the expected future reward from states or state-action pairs, providing targets for learning. Policies map states to actions, with the optimal policy selecting actions maximizing expected cumulative reward.&lt;/p&gt;

&lt;p&gt;The connection to deep learning through Deep Reinforcement Learning enables RL to scale to high-dimensional state spaces like images and large action spaces. Neural networks approximate value functions or policies, learning from experience through gradient descent. This combination has achieved remarkable success: AlphaGo mastering Go through self-play, Atari game playing from pixels, robotic manipulation learning from trial and error, and sophisticated language model alignment through reinforcement learning from human feedback (RLHF). Understanding RL fundamentals provides foundation for these deep RL methods covered in the next chapter.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;A Markov Decision Process (MDP) is defined by the tuple \((\mathcal{S}, \mathcal{A}, \mathcal{P}, \mathcal{R}, \gamma)\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathcal{S}\): State space (all possible environment configurations)&lt;/li&gt;
  &lt;li&gt;\(\mathcal{A}\): Action space (choices available to agent)&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;\(\mathcal{P}\): Transition function $$P(s_{t+1}&lt;/td&gt;
          &lt;td&gt;s_t, a_t)$$ (dynamics)&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;\(\mathcal{R}\): Reward function \(R(s_t, a_t, s_{t+1})\) (feedback)&lt;/li&gt;
  &lt;li&gt;\(\gamma \in [0,1)\): Discount factor (balancing immediate vs future rewards)&lt;/li&gt;
&lt;/ul&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The agent follows a policy $$\pi(a&lt;/td&gt;
      &lt;td&gt;s)\(—probability of action\)a\(in state\)s\(. The goal is finding optimal policy\)\pi^*$$ maximizing expected return:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[J(\pi) = \mathbb{E}_{\tau \sim \pi}\left[\sum_{t=0}^\infty \gamma^t r_t\right]\]

&lt;p&gt;where \(\tau = (s_0, a_0, r_0, s_1, a_1, r_1, \ldots)\) is a trajectory.&lt;/p&gt;

&lt;h3 id=&quot;value-functions&quot;&gt;Value Functions&lt;/h3&gt;

&lt;p&gt;The state value function quantifies expected return starting from state \(s\):&lt;/p&gt;

\[V^\pi(s) = \mathbb{E}_{\pi}\left[\sum_{t=0}^\infty \gamma^t r_t \mid s_0 = s\right]\]

&lt;p&gt;The action-value function (Q-function) includes the first action:&lt;/p&gt;

\[Q^\pi(s,a) = \mathbb{E}_{\pi}\left[\sum_{t=0}^\infty \gamma^t r_t \mid s_0 = s, a_0 = a\right]\]

&lt;p&gt;These satisfy Bellman equations expressing recursive relationships:&lt;/p&gt;

\[V^\pi(s) = \sum_a \pi(a|s) \sum_{s&apos;} P(s&apos;|s,a)[R(s,a,s&apos;) + \gamma V^\pi(s&apos;)]\]

\[Q^\pi(s,a) = \sum_{s&apos;} P(s&apos;|s,a)[R(s,a,s&apos;) + \gamma \sum_{a&apos;} \pi(a&apos;|s&apos;) Q^\pi(s&apos;, a&apos;)]\]

&lt;p&gt;The optimal value functions satisfy Bellman optimality equations:&lt;/p&gt;

\[V^*(s) = \max_a \sum_{s&apos;} P(s&apos;|s,a)[R(s,a,s&apos;) + \gamma V^*(s&apos;)]\]

\[Q^*(s,a) = \sum_{s&apos;} P(s&apos;|s,a)[R(s,a,s&apos;) + \gamma \max_{a&apos;} Q^*(s&apos;, a&apos;)]\]

&lt;p&gt;The optimal policy is greedy with respect to \(Q^*\): \(\pi^*(s) = \arg\max_a Q^*(s,a)\).&lt;/p&gt;

&lt;h3 id=&quot;q-learning&quot;&gt;Q-Learning&lt;/h3&gt;

&lt;p&gt;Q-learning learns \(Q^*\) without knowing transition probabilities through temporal difference learning:&lt;/p&gt;

\[Q(s_t, a_t) \leftarrow Q(s_t, a_t) + \alpha[r_t + \gamma \max_{a&apos;} Q(s_{t+1}, a&apos;) - Q(s_t, a_t)]\]

&lt;p&gt;The update uses observed reward \(r_t\) and estimated future value \(\max_{a&apos;} Q(s_{t+1}, a&apos;)\) to improve current estimate \(Q(s_t, a_t)\). This bootstrapping—using one estimate to improve another—enables learning from experience without environment model.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Consider training an agent to play a simple game: navigate a 5×5 grid to reach a goal. States are positions (25 states), actions are {up, down, left, right}, reward is +10 at goal, -1 elsewhere (encouraging reaching goal quickly).&lt;/p&gt;

&lt;p&gt;Initially, Q-values are random. The agent starts at (0,0), takes random actions. After wandering, it accidentally reaches goal at (4,4), receiving +10 reward. Q-learning updates:&lt;/p&gt;

\[Q((4,3), \text{right}) \leftarrow Q((4,3), \text{right}) + \alpha[10 + 0 - Q((4,3), \text{right})]\]

&lt;p&gt;The Q-value for “go right from position next to goal” increases. Next time the agent reaches (4,3), it’s more likely to go right (if using ε-greedy policy based on Q-values).&lt;/p&gt;

&lt;p&gt;After more episodes, values propagate backward. Q((4,2), right) increases because it leads to (4,3) which now has high Q-value. Eventually, optimal Q-values form gradient pointing toward goal from every state, and the agent learns to navigate directly to goal from any starting position.&lt;/p&gt;

&lt;h3 id=&quot;application-ε-greedy-in-recommendation-feeds&quot;&gt;Application: ε-greedy in recommendation feeds&lt;/h3&gt;

&lt;p&gt;Video/product feeds also face &lt;strong&gt;exploration–exploitation&lt;/strong&gt;: always showing “safe” content locks users in a preference bubble (&lt;em&gt;filter bubble&lt;/em&gt;); you sometimes need to &lt;strong&gt;explore&lt;/strong&gt; new topics.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ε-greedy&lt;/strong&gt; is common: with probability \(1-\varepsilon\) pick the model’s best action/item (exploit); with probability \(\varepsilon\) pick at random (explore). Example \(\varepsilon=0.1\) → ~90% optimal, ~10% random.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter20/recsys_epsilon_greedy.jpg&quot; alt=&quot;ε-greedy 90% / 10%&quot; /&gt;
&lt;em&gt;Figure: ε-greedy — mostly follow the optimal choice, occasionally try at random. (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter20/recsys_epsilon_greedy_detail.jpg&quot; alt=&quot;ε-greedy detail in ranking&quot; /&gt;
&lt;em&gt;Figure: Deliberate exploration can surface new topics (e.g. “tech”) even when the model is confident in older interests. (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In recsys the “reward” may be watch-time, likes, or a multi-objective blend — still the familiar MDP/bandit tradeoff between exploration and exploitation.&lt;/p&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GridWorld&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Simple grid environment for RL demonstration&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;goal&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;reset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Execute action, return (next_state, reward, done)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# up,down,left,right
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;actions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;new_x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;new_y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;new_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;new_y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;goal&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;goal&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Q-Learning
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;env&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GridWorld&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Q(state, action)
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Learning rate
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Discount
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Exploration
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Q-Learning agent...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;episode&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;env&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;total_reward&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# ε-greedy action selection
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;action&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;env&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total_reward&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Q-learning update
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;best_next_action&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reward&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_next_action&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;action&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)])&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_state&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;done&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;episode&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Episode &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;episode&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Reward = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_reward&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Learned optimal policy!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;RL connects to control theory, operations research, and economics through optimal decision-making under uncertainty. Dynamic programming provides algorithms for computing optimal policies when environment dynamics are known. RL extends this to unknown dynamics, learning through interaction.&lt;/p&gt;

&lt;p&gt;RL relates to supervised learning through imitation learning and inverse RL. Rather than learning from rewards, agents can learn from demonstrations (supervised), or infer reward functions from expert behavior (inverse RL).&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://incompleteideas.net/book/the-book-2nd.html&quot;&gt;“Reinforcement Learning: An Introduction” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Richard Sutton, Andrew Barto&lt;br /&gt;
The definitive RL textbook, establishing mathematical foundations and core algorithms. Essential reading for anyone studying RL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.5602&quot;&gt;“Playing Atari with Deep Reinforcement Learning” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Volodymyr Mnih et al.&lt;br /&gt;
DQN showed deep learning + RL could learn to play Atari games from pixels, launching deep RL revolution. Combined Q-learning with deep neural networks, experience replay, and target networks.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;Exploration-exploitation tradeoff is crucial. Pure exploitation (always best known action) never discovers better alternatives. Pure exploration (random actions) doesn’t use learned knowledge. ε-greedy, softmax policies, or UCB-based methods balance both.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Reinforcement learning trains agents through interaction with environments, learning policies that maximize cumulative rewards through trial and error. MDPs formalize sequential decision-making with states, actions, transitions, and rewards. Value functions estimate expected future returns, providing targets for learning. Q-learning learns optimal action-values through temporal difference updates, enabling learning without environment model. The exploration-exploitation tradeoff requires balancing discovering new strategies versus using known good ones. RL’s delayed reward and credit assignment challenges make it harder than supervised learning but enable applications where supervision is unavailable or expensive.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1444915507374636&quot;&gt;Recommendation algorithms (TikTok-style)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=2pWv7GOvuf0&quot;&gt;RL Course by David Silver - Lecture 1: Introduction to Reinforcement Learning&lt;/a&gt; — Google DeepMind, English. Reward, policy, and value.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=lfHX2hHRMVQ&quot;&gt;RL Course by David Silver - Lecture 2: Markov Decision Process&lt;/a&gt; — Google DeepMind, English. States, actions, and the Bellman equation are this lesson’s mathematics.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=9hbQieQh7-o&quot;&gt;Reinforcement Learning with Neural Networks: Essential Concepts&lt;/a&gt; — StatQuest with Josh Starmer, English. The same objects once a neural net is allowed to represent them, which the lesson previews.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>20 Reinforcement Learning Basics</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter20/20_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter20/20_00_Introduction</id>
   <content type="html">&lt;p&gt;Supervised learning hands a model an answer key on every single example; Reinforcement Learning throws an agent into an unfamiliar world with no answer key at all—only delayed scalar rewards that might arrive 50 moves after the decision that actually won or lost the game. That &lt;strong&gt;credit assignment problem&lt;/strong&gt; and the tension between &lt;strong&gt;exploring&lt;/strong&gt; unknown actions versus &lt;strong&gt;exploiting&lt;/strong&gt; known rewards form the mathematical core of sequential decision making.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-architecture-of-reinforcement-learning&quot;&gt;Key ideas: The Architecture of Reinforcement Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Markov Decision Processes (MDPs)&lt;/strong&gt;: Formalizes sequential environments as the tuple $(\mathcal{S}, \mathcal{A}, P, R, \gamma)$, where the Markov property states that future transitions depend only on the current state and action.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Discounted Return &amp;amp; Value Functions&lt;/strong&gt;: Measures long-term success via $G_t = \sum_{k=0}^\infty \gamma^k R_{t+k+1}$ and summarizes expected future returns from states ($V^\pi(s)$) or state–action pairs ($Q^\pi(s, a)$).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Bellman Optimality Equations&lt;/strong&gt;: Expresses optimal long-term value recursively as immediate reward plus discounted optimal next-state value, turning infinite-horizon planning into local fixed-point updates.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Exploration vs. Exploitation&lt;/strong&gt;: Balances gathering new information ($\epsilon$-greedy, UCB, Boltzmann exploration) against greedily maximizing current estimates.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-discounted-returns-g_t-backward-in-time&quot;&gt;Worked example: Computing Discounted Returns $G_t$ Backward in Time&lt;/h3&gt;

&lt;p&gt;Suppose an episode lasts 3 steps with rewards $R_1 = 0,\; R_2 = 2,\; R_3 = 10$ and discount factor $\gamma = 0.9$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute returns recursively backward using $G_t = R_{t+1} + \gamma G_{t+1}$&lt;/strong&gt; (with $G_3 = 0$):
    &lt;ul&gt;
      &lt;li&gt;$G_2 = R_3 + 0.9(0) = 10.00$.&lt;/li&gt;
      &lt;li&gt;$G_1 = R_2 + 0.9 G_2 = 2 + 0.9(10.00) = 11.00$.&lt;/li&gt;
      &lt;li&gt;$G_0 = R_1 + 0.9 G_1 = 0 + 0.9(11.00) = 9.90$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify directly from $t = 0$&lt;/strong&gt;:
\(G_0 = 0 + 0.9(2) + 0.9^2(10) = 0 + 1.8 + 8.1 = 9.90.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare with a myopic discount $\gamma = 0.5$&lt;/strong&gt;:
\(G_0(\gamma=0.5) = 0 + 0.5(2) + 0.25(10) = 1.0 + 2.5 = 3.50.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: The discount factor $\gamma$ controls the agent’s effective planning horizon $\approx \frac{1}{1-\gamma}$ ($10$ steps for $\gamma=0.9$ vs. $2$ steps for $\gamma=0.5$), directly deciding whether delayed rewards outweigh short-term bribes.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Reinforcement Learning (RL) trains agents to make sequential decisions by maximizing cumulative rewards. This chapter introduces the RL framework: agents, environments, states, actions, rewards, and policies. We cover Markov Decision Processes, value functions, Q-learning, and policy gradient methods. These fundamentals prepare you for deep RL in the next chapter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After MDP basics, see &lt;strong&gt;20-99 Modern Applications and Updates&lt;/strong&gt; for bandits, offline RL on logs, and the RLHF MDP.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LLM hub:&lt;/strong&gt; High-level RLHF / PPO / DPO objectives for language models are in &lt;strong&gt;26-03&lt;/strong&gt;; the RL derivations stay here and in Chapter 21.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=2pWv7GOvuf0&quot;&gt;RL Course by David Silver - Lecture 1: Introduction to Reinforcement Learning&lt;/a&gt; — Google DeepMind, English. David Silver’s opening lecture is this chapter’s definition of an agent.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=lfHX2hHRMVQ&quot;&gt;RL Course by David Silver - Lecture 2: Markov Decision Process&lt;/a&gt; — Google DeepMind, English. The Markov decision process the next lesson writes in full.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8JVRbHAVCws&quot;&gt;MIT 6.S191 (2024): Reinforcement Learning&lt;/a&gt; — Alexander Amini, English. MIT’s 2024 RL lecture, for the same ideas with modern examples.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>19-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter19/19_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter19/19_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Until 2022, building a production speech stack meant wiring together fragile acoustic models, pronunciation lexicons, and language-model decoders tuned separately for each language. OpenAI’s Whisper blew up that pipeline by training a single encoder–decoder Transformer on 680,000 hours of weakly supervised multilingual audio—and by 2024–2026, neural audio codecs and full-duplex speech-to-speech models turned spoken conversation into native token-stream modeling.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-modern-speech--audio-stacks-20222026&quot;&gt;Key ideas: Modern Speech &amp;amp; Audio Stacks (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Weakly Supervised Multilingual ASR (Whisper)&lt;/strong&gt;: Pads/chunks audio into 30-second 80/128-bin log-Mel windows, downsamples $2\times$ via strided convs into 1500 encoder frames, and uses special task tokens (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;|transcribe|&amp;gt;&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;|translate|&amp;gt;&lt;/code&gt;, timestamps) for multitask decoding.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Neural Audio Codecs &amp;amp; Discrete Speech Tokens&lt;/strong&gt;: Quantizes continuous speech into semantic + acoustic RVQ token streams (EnCodec, Mimi, DAC) so LLMs can read and speak audio end-to-end without an intermediate text bottleneck.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Full-Duplex Speech &amp;amp; Low-Latency Streaming&lt;/strong&gt;: Handles simultaneous listening and speaking (interruptions, backchannels) by predicting overlapping user/assistant token streams at fixed frame rates (e.g., 12.5 Hz).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Speaker Diarization &amp;amp; Meeting Pipelines&lt;/strong&gt;: Combines Voice Activity Detection (VAD), speaker embeddings (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pyannote&lt;/code&gt;), and Whisper ASR to answer &lt;em&gt;“who spoke what and when?”&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-whispers-encoder-frame-budget-and-real-time-factor-rtf&quot;&gt;Worked example: Computing Whisper’s Encoder Frame Budget and Real-Time Factor (RTF)&lt;/h3&gt;

&lt;p&gt;Whisper processes $30\text{ s}$ of $16\text{ kHz}$ audio using a $10\text{ ms}$ hop length ($3{,}000$ Mel frames) followed by two 1D convolutions where the second has &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=2&lt;/code&gt;.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Encoder token length per 30-second chunk&lt;/strong&gt;:
\(L_{\text{enc}} = \frac{3{,}000}{2} = 1{,}500\text{ frames} \implies \frac{30\text{ s}}{1{,}500} = 20\text{ ms per encoder token (50 Hz)}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Real-Time Factor (RTF) for streaming vs. batch&lt;/strong&gt;:
Suppose &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;faster-whisper&lt;/code&gt; (CTranslate2 INT8) transcribes a $600\text{ s}$ (10-minute) podcast in $12.0\text{ s}$ of GPU compute.
\(\text{RTF} = \frac{T_{\text{compute}}}{T_{\text{audio}}} = \frac{12.0}{600.0} = 0.02 \quad (50\times\text{ faster than real time!}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Every Whisper encoder token spans exactly $20\text{ ms}$ of speech, and tracking $\text{RTF} \ll 1$ tells you immediately whether a model can run comfortably in live production.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-speech-and-audio-after-whisper--multilingual-asr-codecs-tts&quot;&gt;Optional: speech and audio after Whisper — multilingual ASR, codecs, TTS&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. The chapter intro already names Whisper and WaveNet. This note goes to the &lt;strong&gt;2022–2026 software&lt;/strong&gt; actually used: Whisper-scale ASR, neural codecs, and multilingual speech translation — without rewriting spectrogram / MFCC theory (the chapter body is still thin; do not treat this as a theory replacement).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;1-whisper-as-the-asr-default&quot;&gt;1. Whisper as the ASR default&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2212.04356&quot;&gt;Radford et al., 2022&lt;/a&gt; train an encoder–decoder Transformer on weakly supervised multilingual speech. The decoder factorizes&lt;/p&gt;

\[p(y\mid x) = \prod_t p(y_t \mid y_{&amp;lt;t}, x),\]

&lt;p&gt;where \(x\) is a log-mel spectrogram. Later &lt;strong&gt;large-v2 / large-v3&lt;/strong&gt; checkpoints and &lt;a href=&quot;https://github.com/SYSTRAN/faster-whisper&quot;&gt;faster-whisper&lt;/a&gt; (CTranslate2) are what data teams call from Python. The architecture is Chapter 08; the application is robust ASR without a language-specific HMM.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;speech-translation-and-full-duplex-stacks&quot;&gt;Speech translation and full-duplex stacks&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2308.11596&quot;&gt;Communication et al., 2023&lt;/a&gt; (SeamlessM4T) unify ASR, translation, and TTS. OpenAI’s realtime / omni-class APIs (2024–2025) are the product form: stream audio in, stream tokens or audio out.&lt;/p&gt;

&lt;h3 id=&quot;neural-codecs-under-generative-audio&quot;&gt;Neural codecs under generative audio&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.13438&quot;&gt;EnCodec&lt;/a&gt; and &lt;a href=&quot;https://arxiv.org/abs/2306.06546&quot;&gt;DAC&lt;/a&gt; (also in Chapter 12 optional) turn waveforms into discrete tokens for MusicGen / AudioLM-style models. TTS moved from WaveNet samples toward &lt;strong&gt;codec-LM + vocoder&lt;/strong&gt; (CosyVoice, XTTS, OpenVoice).&lt;/p&gt;

&lt;h3 id=&quot;diarization-and-meeting-ds&quot;&gt;Diarization and meeting DS&lt;/h3&gt;

&lt;p&gt;Whisper + &lt;a href=&quot;https://github.com/pyannote/pyannote-audio&quot;&gt;pyannote&lt;/a&gt; is the 2023–2026 meeting-notes pipeline: ASR, then speaker labels, then an LLM summary (Chapter 18 optional).&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/openai/whisper&quot;&gt;openai/whisper&lt;/a&gt; and &lt;a href=&quot;https://github.com/SYSTRAN/faster-whisper&quot;&gt;SYSTRAN/faster-whisper&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/seamless_communication&quot;&gt;facebookresearch/seamless_communication&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/audiocraft&quot;&gt;facebookresearch/audiocraft&lt;/a&gt; (MusicGen) and &lt;a href=&quot;https://github.com/coqui-ai/TTS&quot;&gt;coqui-ai/TTS&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2212.04356&quot;&gt;Robust Speech Recognition via Large-Scale Weak Supervision — Whisper (Radford et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2308.11596&quot;&gt;SeamlessM4T (Communication et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.13438&quot;&gt;EnCodec (Défossez et al., 2022)&lt;/a&gt; and &lt;a href=&quot;https://arxiv.org/abs/2306.06546&quot;&gt;DAC (Kumar et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Use this chapter’s intro as the map (spectrograms, DeepSpeech, WaveNet). This lesson only updates the &lt;strong&gt;checkpoints and codecs&lt;/strong&gt; you would install in 2026.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=uFOkMme19Zs&quot;&gt;OpenAI’s Whisper Model Explained&lt;/a&gt; — What’s AI by Louis-François Bouchard, English. Whisper as the default ASR system this note describes.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=SJo7vPgRlBQ&quot;&gt;Mel Frequency Cepstral Coefficients (MFCC) Explained&lt;/a&gt; — DataMListic, English. The mel features that kind of model still starts from.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=4_SH2nfbQZ8&quot;&gt;Mel-Frequency Cepstral Coefficients Explained Easily&lt;/a&gt; — Valerio Velardo - The Sound of AI, English. How those features are built, so the Whisper input is not a black box.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>19 Speech and Audio Processing</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter19/19_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter19/19_00_Introduction</id>
   <content type="html">&lt;p&gt;A single 10-second voice memo sampled at 16 kHz is a raw sequence of 160,000 floating-point air-pressure measurements—way too long for a vanilla Transformer and completely opaque if you stare at individual samples. Speech and audio deep learning solved this by borrowing a century of signal processing: slicing waveforms into overlapping frames via the Short-Time Fourier Transform (STFT), warping frequencies onto the human-ear Mel scale, and feeding the resulting 2D log-Mel spectrogram into convolutional and attention architectures.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-foundations-of-deep-speech--audio-processing&quot;&gt;Key ideas: Foundations of Deep Speech &amp;amp; Audio Processing&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Time–Frequency Representations (STFT &amp;amp; Mel Scale)&lt;/strong&gt;: Converts 1D waveforms into 2D time–frequency images using windowed FFTs and perceptually spaced triangular Mel filterbanks, compressing $16{,}000$ samples/sec into $\sim 100$ frames/sec.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Alignment-Free Sequence Recognition (CTC &amp;amp; Attention)&lt;/strong&gt;: Solves the mismatch between hundreds of acoustic frames and dozens of output characters using Connectionist Temporal Classification (CTC) blank tokens or encoder–decoder cross-attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Neural Vocoders &amp;amp; Waveform Synthesis&lt;/strong&gt;: Reconstructs phase-coherent high-sample-rate audio from spectrograms or discrete tokens using dilated causal convolutions (WaveNet), adversarial vocoders (HiFi-GAN), or flow matching.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Acoustic Evaluation Metrics&lt;/strong&gt;: Measures speech recognition via Word Error Rate (WER) and synthesis quality via Mel-Cepstral Distortion (MCD) and Mean Opinion Score (MOS).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-stft-frame-count-mel-conversion-and-wer&quot;&gt;Worked example: Computing STFT Frame Count, Mel Conversion, and WER&lt;/h3&gt;

&lt;p&gt;Suppose we record a $T = 3.0\text{ s}$ audio clip at sample rate $f_s = 16{,}000\text{ Hz}$ ($N = 48{,}000$ samples), using a $25\text{ ms}$ FFT window ($400$ samples) and a $10\text{ ms}$ hop length ($160$ samples).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Number of spectrogram time frames&lt;/strong&gt;:
\(L = \left\lfloor \frac{48{,}000 - 400}{160} \right\rfloor + 1 = \lfloor 297.5 \rfloor + 1 = 298\text{ frames}.\)
With $80$ Mel bins, the raw $48{,}000$-length waveform becomes a compact $(80 \times 298)$ 2D tensor!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convert $f = 1{,}000\text{ Hz}$ and $f = 4{,}000\text{ Hz}$ to the Mel scale&lt;/strong&gt; ($m(f) = 2595\log_{10}(1 + f/700)$):
    &lt;ul&gt;
      &lt;li&gt;$m(1000) = 2595\log_{10}(2.4286) = 2595(0.3854) \approx 1{,}000\text{ Mel}$.&lt;/li&gt;
      &lt;li&gt;$m(4000) = 2595\log_{10}(6.7143) = 2595(0.8270) \approx 2{,}146\text{ Mel}$.
Notice that quadrupling frequency ($+3000\text{ Hz}$) only slightly more than doubles perceptual Mel pitch—matching human cochlear sensitivity.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Word Error Rate (WER)&lt;/strong&gt;:
Reference: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;the cat sat on the mat&quot;&lt;/code&gt; ($6$ words). Hypothesis: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;the bat sat on mat&quot;&lt;/code&gt; ($1$ substitution &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cat-&amp;gt;bat&lt;/code&gt;, $1$ deletion &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;the&lt;/code&gt;, $0$ insertions).
\(\text{WER} = \frac{S + D + I}{N_{\text{ref}}} = \frac{1 + 1 + 0}{6} = 33.3\%.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Spectrogram framing gives a $160\times$ temporal compression right at the front door, while WER rigorously tracks insertions, deletions, and substitutions.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Deep learning has transformed audio processing, enabling speech recognition, speaker identification, music generation, and audio synthesis. This chapter covers audio representation (spectrograms, MFCCs), speech recognition architectures (DeepSpeech, Whisper), text-to-speech (WaveNet, Tacotron), and music generation models.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After the audio map in this intro, see &lt;strong&gt;19-99 Modern Applications and Updates&lt;/strong&gt; for Whisper-scale ASR, SeamlessM4T, and neural codecs.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=SJo7vPgRlBQ&quot;&gt;Mel Frequency Cepstral Coefficients (MFCC) Explained&lt;/a&gt; — DataMListic, English. MFCCs are the speech features this introduction says a model consumes.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=4_SH2nfbQZ8&quot;&gt;Mel-Frequency Cepstral Coefficients Explained Easily&lt;/a&gt; — Valerio Velardo - The Sound of AI, English. A longer construction of the mel scale and the cepstrum, if the short version is too compressed.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=uFOkMme19Zs&quot;&gt;OpenAI’s Whisper Model Explained&lt;/a&gt; — What’s AI by Louis-François Bouchard, English. Whisper, which this introduction names as the recognition system to know.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>18-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter18/18_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter18/18_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Today’s NLP pipelines rarely train static Word2Vec embeddings from scratch, yet dense vector geometry is more central than ever: Retrieval-Augmented Generation (RAG) embeds entire documents into dense vectors to ground LLM answers in private facts, while structured JSON extraction and BPE tokenization determine whether an applied system stays accurate, fast, and within context budgets.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-applied-modern-nlp-20222026&quot;&gt;Key ideas: Applied Modern NLP (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Dense Bi-Encoder Retrieval &amp;amp; RAG&lt;/strong&gt;: Encodes queries and document chunks into normalized vectors via contrastive embedding models, retrieves top-$k$ passages via Approximate Nearest Neighbors (HNSW/FAISS), and injects them into an LLM prompt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Hybrid Search &amp;amp; Cross-Encoder Reranking&lt;/strong&gt;: Combines lexical BM25 (exact IDs, rare jargon) with dense semantic search via Reciprocal Rank Fusion (RRF), then reranks top candidates with a cross-encoder.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Structured Extraction &amp;amp; Constrained Decoding&lt;/strong&gt;: Uses JSON schemas and grammar-constrained sampling so generative LLMs reliably emit typed records for downstream databases.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Applied Tokenization Economics&lt;/strong&gt;: Tracks token-to-word ratios across languages and code, directly controlling API latency, context-window utilization, and billing cost.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-reciprocal-rank-fusion-rrf-for-hybrid-rag-search&quot;&gt;Worked example: Reciprocal Rank Fusion (RRF) for Hybrid RAG Search&lt;/h3&gt;

&lt;p&gt;Suppose a user queries &lt;em&gt;“Error E402 timeout”&lt;/em&gt;. Lexical BM25 returns ranks &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{Doc A: 1, Doc B: 3, Doc C: 2}&lt;/code&gt; while dense vector search returns ranks &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{Doc A: 4, Doc B: 1, Doc C: 2}&lt;/code&gt;. Using the standard RRF formula $\text{RRF}(d) = \sum_{r} \frac{1}{k + \text{rank}_r(d)}$ with $k = 60$:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute RRF score for each document&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Doc A&lt;/strong&gt;: $\frac{1}{61} + \frac{1}{64} = 0.01639 + 0.01563 = 0.03202$.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Doc B&lt;/strong&gt;: $\frac{1}{63} + \frac{1}{61} = 0.01587 + 0.01639 = 0.03226$.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Doc C&lt;/strong&gt;: $\frac{1}{62} + \frac{1}{62} = 0.01613 + 0.01613 = 0.03226$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare with pure dense search&lt;/strong&gt;:
Pure dense search ranked &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Doc A&lt;/code&gt; 4th because &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;E402&quot;&lt;/code&gt; is an opaque error code, whereas RRF promotes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Doc A&lt;/code&gt; right alongside &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Doc B&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Doc C&lt;/code&gt; without needing to calibrate incompatible BM25 and cosine score scales!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: RRF’s rank-based formula makes hybrid retrieval robust, scale-free, and dramatically better at queries mixing exact codes with natural language.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-nlp-after-static-embeddings--llms-rag-and-tokenizers&quot;&gt;Optional: NLP after static embeddings — LLMs, RAG, and tokenizers&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace Word2Vec / GloVe geometry. The existing lesson already points at contextual BERT vectors; this note covers the &lt;strong&gt;application stack&lt;/strong&gt; that took over NLP products in 2022–2026.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Static embeddings are still the right first model of “nearby = similar.” Almost no new product &lt;em&gt;stops&lt;/em&gt; there: they use a &lt;strong&gt;decoder LM&lt;/strong&gt; plus retrieval, tools, or structured extraction.&lt;/p&gt;

&lt;h2 id=&quot;1-from-one-vector-per-type-to-a-generated-answer&quot;&gt;1. From one vector per type to a generated answer&lt;/h2&gt;

&lt;p&gt;A 2024–2026 NLP service is usually:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Tokenizer (BPE / Unigram: &lt;a href=&quot;https://github.com/openai/tiktoken&quot;&gt;tiktoken&lt;/a&gt;, SentencePiece).&lt;/li&gt;
  &lt;li&gt;Instruction-tuned Transformer (Chapter 08 optional).&lt;/li&gt;
  &lt;li&gt;Optional &lt;strong&gt;RAG&lt;/strong&gt;: embed the query, fetch chunks, condition the LM.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The embedding table \(E\in\mathbb{R}^{V\times d}\) from this chapter is still layer 0 of that LM. What you ship is the rest of the stack.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;retrieval-augmented-generation&quot;&gt;Retrieval-augmented generation&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2005.11401&quot;&gt;Lewis et al., 2020&lt;/a&gt; (RAG; ubiquitous after 2022) and later Dense Passage / &lt;a href=&quot;https://arxiv.org/abs/2212.03533&quot;&gt;E5&lt;/a&gt; / &lt;a href=&quot;https://arxiv.org/abs/2308.03281&quot;&gt;GTE&lt;/a&gt; embedders turn “search + generate” into the default enterprise NLP pattern. Evaluate with groundedness, not only BLEU.&lt;/p&gt;

&lt;h3 id=&quot;structured-extraction-and-classification&quot;&gt;Structured extraction and classification&lt;/h3&gt;

&lt;p&gt;Instead of a custom BiLSTM-CRF, teams prompt or LoRA-tune an LM to emit JSON (NER, sentiment, ticket routing). Keep a small encoder (BERT/DeBERTa) when latency and calibration beat a 7B decoder.&lt;/p&gt;

&lt;h3 id=&quot;tokenization-as-an-applied-skill&quot;&gt;Tokenization as an applied skill&lt;/h3&gt;

&lt;p&gt;Subword vocabularies decide cost and multilingual quality. &lt;a href=&quot;https://arxiv.org/abs/1508.07909&quot;&gt;Sennrich et al., BPE&lt;/a&gt; is old; &lt;strong&gt;using&lt;/strong&gt; tiktoken / Llama tokenizers on messy DS text is the 2022–2026 skill (off-by-one context limits, undocumented special tokens).&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/transformers&quot;&gt;huggingface/transformers&lt;/a&gt; + &lt;a href=&quot;https://github.com/huggingface/datasets&quot;&gt;datasets&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/langchain-ai/langchain&quot;&gt;langchain&lt;/a&gt; / &lt;a href=&quot;https://github.com/run-llama/llama_index&quot;&gt;llama_index&lt;/a&gt; — RAG glue (use carefully; the algorithm is still embed–retrieve–generate).&lt;/li&gt;
  &lt;li&gt;Sentence-Transformers / &lt;a href=&quot;https://huggingface.co/intfloat&quot;&gt;intfloat/e5&lt;/a&gt; — retrieval embeddings.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2212.03533&quot;&gt;Text Embeddings by Weakly-Supervised Contrastive Pre-training — E5 (Wang et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2005.11401&quot;&gt;Retrieval-Augmented Generation for Knowledge-Intensive NLP (Lewis et al., 2020)&lt;/a&gt; — the RAG template every 2023–2026 stack reimplements.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2307.09288&quot;&gt;Llama 2 (Touvron et al., 2023)&lt;/a&gt; — instruction-tuned open LM used as the generator.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Finish the Word2Vec arithmetic and the “static vs contextual” note first. This lesson only adds &lt;strong&gt;RAG, instruction-tuned generators, and modern tokenizers&lt;/strong&gt; — not a new skip-gram derivation.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=LPZh9BOjkQs&quot;&gt;Large Language Models explained briefly&lt;/a&gt; — 3Blue1Brown, English. A static word vector is no longer the whole model; this short video is the generated-answer stack the note describes.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. Contextual embeddings inside a transformer, the replacement for one vector per word type.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, English. What you do with those contextual states once the model can answer.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>18-01 Word Embeddings and Language Representation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter18/18_01_Word_Embeddings/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter18/18_01_Word_Embeddings</id>
   <content type="html">&lt;p&gt;When Mikolov et al. published Word2Vec in 2013, the machine learning world was mesmerized by a single vector equation: $\mathbf{v}&lt;em&gt;{\text{king}} - \mathbf{v}&lt;/em&gt;{\text{man}} + \mathbf{v}&lt;em&gt;{\text{woman}} \approx \mathbf{v}&lt;/em&gt;{\text{queen}}$. Nobody explicitly taught the network gender or royalty; that linear parallelogram emerged automatically because Skip-gram with Negative Sampling implicitly factorizes the shifted Pointwise Mutual Information (PMI) matrix of the entire corpus.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mathematical-foundations-of-word-embeddings&quot;&gt;Key ideas: Mathematical Foundations of Word Embeddings&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Pillar 1 — Skip-Gram &amp;amp; Negative Sampling (SGNS)&lt;/strong&gt;: Replaces an expensive $O(&lt;/td&gt;
          &lt;td&gt;V&lt;/td&gt;
          &lt;td&gt;)$ vocabulary softmax with $k + 1$ binary logistic classifications (1 true context word vs. $k$ noise words drawn from $P_n(w) \propto f(w)^{3/4}$).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Implicit Matrix Factorization &amp;amp; PMI&lt;/strong&gt;: Proves (Levy &amp;amp; Goldberg, 2014) that optimal SGNS dot products satisfy $u_w^\top v_c = \text{PMI}(w, c) - \log k$, unifying neural Word2Vec with classical count-based distributional semantics.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — GloVe (Global Vectors)&lt;/strong&gt;: Explicitly regresses $w_i^\top \tilde{w}&lt;em&gt;j + b_i + \tilde{b}_j \approx \log X&lt;/em&gt;{ij}$ with a bounded weighting function $f(X_{ij})$ so global co-occurrence ratios map directly to vector differences.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Dual Embedding Matrices &amp;amp; Polysemy Limits&lt;/strong&gt;: Explains why Skip-gram keeps separate target (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;in&lt;/code&gt;) and context (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;out&lt;/code&gt;) embedding tables, and why static embeddings still cannot separate homonyms like &lt;em&gt;“bat”&lt;/em&gt; (animal vs. baseball).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-one-skip-gram-negative-sampling-loss--gradient-step&quot;&gt;Worked example: One Skip-Gram Negative Sampling Loss &amp;amp; Gradient Step&lt;/h3&gt;

&lt;p&gt;Suppose target word &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;king&quot;&lt;/code&gt; has input vector $v_c = [1.0,\; 0.5]$, true context word &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;crown&quot;&lt;/code&gt; has output vector $u_o = [0.8,\; 0.4]$, and one negative sample &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;banana&quot;&lt;/code&gt; has output vector $u_n = [-0.5,\; 1.0]$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute dot products&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Positive pair: $s_+ = v_c^\top u_o = (1.0)(0.8) + (0.5)(0.4) = 1.00$.&lt;/li&gt;
      &lt;li&gt;Negative pair: $s_- = v_c^\top u_n = (1.0)(-0.5) + (0.5)(1.0) = 0.00$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate SGNS loss $\mathcal{L} = -\ln\sigma(s_+) - \ln\sigma(-s_-)$&lt;/strong&gt;:
Using $\sigma(1.0) \approx 0.7311$ and $\sigma(0.0) = 0.5000$:
\(\mathcal{L} = -\ln(0.7311) - \ln(0.5000) = 0.3133 + 0.6931 = 1.0064\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute exact gradient with respect to target vector $v_c$&lt;/strong&gt;:
\(\nabla_{v_c}\mathcal{L} = (\sigma(s_+) - 1)u_o + \sigma(s_-)u_n = (-0.2689)[0.8, 0.4] + (0.5000)[-0.5, 1.0]\)
\(= [-0.2151, -0.1076] + [-0.2500, +0.5000] = [-0.4651,\; +0.3924].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Take one SGD step with $\eta = 0.1$&lt;/strong&gt;:
\(v_c^{\text{new}} = [1.0, 0.5] - 0.1[-0.4651, 0.3924] = [1.0465,\; 0.4608].\)
Check new dot products: $s_+^{\text{new}} = 1.0215$ (increased!) and $s_-^{\text{new}} = -0.0625$ (decreased!).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Every SGNS update geometrically pulls the target word toward its true neighbor and pushes it away from noise words in $O(k \cdot d)$ time instead of $O(&lt;/td&gt;
          &lt;td&gt;V&lt;/td&gt;
          &lt;td&gt;\cdot d)$.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;word-embeddings-representing-language-in-vector-space&quot;&gt;Word Embeddings: Representing Language in Vector Space&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/7/78/Word2vec.png/800px-Word2vec.png&quot; alt=&quot;Word2Vec Visualization&quot; /&gt;
&lt;em&gt;Hình ảnh: Minh họa Word2Vec embeddings trong không gian vector. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Word embeddings represent one of the most fundamental innovations in natural language processing, transforming how we represent and process text in machine learning systems. The core idea is elegantly simple yet profoundly impactful: represent each word as a dense vector of real numbers (typically 100-300 dimensions) such that semantically similar words have similar vectors. This continuous vector representation replaces older sparse representations like one-hot encoding (vectors with thousands of dimensions, all zeros except one) with compact, meaningful embeddings that capture semantic relationships through geometric properties in vector space.&lt;/p&gt;

&lt;p&gt;Understanding why embeddings revolutionized NLP requires appreciating the limitations of discrete word representations. Traditional approaches treated words as atomic symbols—”king,” “queen,” and “car” were equally distant from each other, sharing no structure. One-hot encoding represents a 50,000-word vocabulary with 50,000-dimensional vectors that are all orthogonal, providing no notion of similarity. This makes learning difficult because the model cannot generalize from seeing “king lives in palace” to understanding “queen lives in palace”—it must learn facts about “queen” independently despite semantic similarity to “king.”&lt;/p&gt;

&lt;h3 id=&quot;from-text--tokens--one-hot--bag-of-words&quot;&gt;From text → tokens → one-hot / bag-of-words&lt;/h3&gt;

&lt;p&gt;The first step is always &lt;strong&gt;tokenization&lt;/strong&gt;, then a numeric representation.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_tokenization.jpg&quot; alt=&quot;Tokenization&quot; /&gt;
&lt;em&gt;Figure: Sentences are split into tokens before encoding. (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_one_hot_table.jpg&quot; alt=&quot;One-hot table&quot; /&gt;
&lt;em&gt;Figure: Each word is a one-hot vector — orthogonal, sparse, no meaning. (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_bag_of_words.jpg&quot; alt=&quot;Bag-of-words&quot; /&gt;
&lt;em&gt;Figure: Bag-of-words aggregates one-hots per sentence — word order is lost. (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_onehot_limitations.jpg&quot; alt=&quot;One-hot / BoW limitations&quot; /&gt;
&lt;em&gt;Figure: Three main limits — no order, sparsity + dimension explosion, no semantic relations. (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Word embeddings solve this by learning continuous representations where similar words cluster together. The distance between “king” and “queen” vectors is small (they’re both royalty), while “king” and “car” are distant (semantically unrelated). More remarkably, embedding spaces exhibit analogical relationships through vector arithmetic: the vector from “man” to “woman” is similar to the vector from “king” to “queen,” capturing the gender relationship. We can solve analogies through simple vector math: king - man + woman ≈ queen. This emergent structure wasn’t explicitly programmed but arose from training on text, demonstrating that embeddings capture deep semantic regularities.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_semantic_space_2d.jpg&quot; alt=&quot;2D embedding space&quot; /&gt;
&lt;em&gt;Figure: Semantically related words cluster (king/queen/man/woman…); distance reflects relations. (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_vector_arithmetic_benefits.jpg&quot; alt=&quot;Benefits of vectorization&quot; /&gt;
&lt;em&gt;Figure: Embeddings enable semantic relations, lexical analogies, and automatic feature learning. (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The training objective for learning embeddings is elegantly formulated through the distributional hypothesis from linguistics: words appearing in similar contexts have similar meanings. This simple principle enables unsupervised learning from massive text corpora.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_distributional_context.jpg&quot; alt=&quot;Distributional context around “king”&quot; /&gt;
&lt;em&gt;Figure: “King” co-occurs with fight/man/strong… — co-occurrence → nearby embeddings. (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Models like Word2Vec and GloVe learn embeddings by predicting context words from target words or vice versa, or by factorizing co-occurrence statistics. The resulting vectors encode lexical semantics, syntactic patterns, and even some world knowledge, all discovered purely from word co-occurrence patterns in text without any labeled data.&lt;/p&gt;

&lt;p&gt;The impact of word embeddings on NLP cannot be overstated. They provided the foundation for the deep learning revolution in language processing, enabling neural networks to leverage vast unlabeled text for learning representations that then transfer to downstream tasks. Pre-trained embeddings like Word2Vec and GloVe became standard components in virtually all NLP systems from 2013-2018. While modern contextual embeddings from BERT and GPT have largely superseded static word embeddings for many tasks, understanding static embeddings remains crucial for appreciating how representation learning in NLP evolved and for applications where their simplicity and efficiency remain advantages.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Word embeddings map discrete symbols (words) to continuous vectors in a way that captures semantic similarity. Formally, we have a vocabulary \(V\) of size $$&lt;/td&gt;
      &lt;td&gt;V&lt;/td&gt;
      &lt;td&gt;\(and learn an embedding matrix\)\mathbf{E} \in \mathbb{R}^{d \times&lt;/td&gt;
      &lt;td&gt;V&lt;/td&gt;
      &lt;td&gt;}\(where column\)\mathbf{e}_w \in \mathbb{R}^d\(is the embedding for word\)w\(. Typical embedding dimension\)d = 100\text{-}300$$, much smaller than vocabulary size (10,000-100,000).&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;word2vec-skip-gram-model&quot;&gt;Word2Vec: Skip-gram Model&lt;/h3&gt;

&lt;p&gt;The skip-gram model predicts context words given a target word, based on the distributional hypothesis. For a corpus with words \(w_1, w_2, \ldots, w_T\), the objective is:&lt;/p&gt;

\[\max_\theta \frac{1}{T}\sum_{t=1}^T \sum_{-c \leq j \leq c, j \neq 0} \log p(w_{t+j} | w_t; \theta)\]

&lt;p&gt;where \(c\) is context window size (typically 5), and \(\theta\) includes the embedding matrix and output weights.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_context_window.jpg&quot; alt=&quot;Context window&quot; /&gt;
&lt;em&gt;Figure: Window size = 1 — the center word learns from neighbors (and vice versa in skip-gram/CBOW). (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_cbow_predict_word.jpg&quot; alt=&quot;CBOW-style: predict the middle word&quot; /&gt;
&lt;em&gt;Figure: Two context words (one-hot) → small hidden layer → predict the target word. (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_onehot_to_hidden.jpg&quot; alt=&quot;One-hot → hidden projection&quot; /&gt;
&lt;em&gt;Figure: Vocab dimension (e.g. 5) compressed to embedding dim (e.g. 3). (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_w1_w2_training.jpg&quot; alt=&quot;W1 / W2 training diagram&quot; /&gt;
&lt;em&gt;Figure: Full pipeline: one-hot × W1 → hidden → × W2 → word logits; compare to true label and update. (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/emb_embedding_matrix.jpg&quot; alt=&quot;Embedding matrix&quot; /&gt;
&lt;em&gt;Figure: Embedding matrix \(|V|\times d\) (e.g. \(5\times 3\)) — each row/column is one word vector. (Illustration from a Word Embedding / Transformer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The conditional probability uses softmax:&lt;/p&gt;

\[p(w_O | w_I) = \frac{\exp(\mathbf{v}_{w_O}^T \mathbf{v}_{w_I})}{\sum_{w=1}^{|V|} \exp(\mathbf{v}_w^T \mathbf{v}_{w_I})}\]

&lt;p&gt;where \(\mathbf{v}_{w_I}\) is the input embedding of word \(w_I\) and \(\mathbf{v}_{w_O}\) is the output embedding of \(w_O\). Computing this softmax requires summing over the entire vocabulary (expensive!), motivating approximations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Negative sampling&lt;/strong&gt; approximates the softmax by sampling a few negative examples instead of summing over all words:&lt;/p&gt;

\[\log \sigma(\mathbf{v}_{w_O}^T \mathbf{v}_{w_I}) + \sum_{i=1}^k \mathbb{E}_{w_i \sim P_n(w)}[\log \sigma(-\mathbf{v}_{w_i}^T \mathbf{v}_{w_I})]\]

&lt;p&gt;where \(\sigma\) is sigmoid, \(k\) is number of negative samples (typically 5-20), and \(P_n(w)\) is noise distribution (often unigram raised to 3/4 power to oversample rare words). This transforms the multi-class problem into \(k+1\) binary classifications, tractable even for large vocabularies.&lt;/p&gt;

&lt;p&gt;The remarkable property of Word2Vec embeddings is that semantic relationships are encoded as linear translations in vector space:&lt;/p&gt;

\[\mathbf{e}_{\text{queen}} \approx \mathbf{e}_{\text{king}} - \mathbf{e}_{\text{man}} + \mathbf{e}_{\text{woman}}\]

\[\mathbf{e}_{\text{Paris}} \approx \mathbf{e}_{\text{France}} - \mathbf{e}_{\text{Germany}} + \mathbf{e}_{\text{Berlin}}\]

&lt;p&gt;These analogies weren’t explicitly trained but emerge from the distributional hypothesis: “king” and “queen” appear in similar contexts (royal, throne, palace), as do “king” and “man” (gendered contexts), creating vector geometry that reflects these semantic patterns.&lt;/p&gt;

&lt;h3 id=&quot;glove-global-vectors&quot;&gt;GloVe: Global Vectors&lt;/h3&gt;

&lt;p&gt;GloVe takes a different approach, directly factorizing word co-occurrence statistics. Let \(X_{ij}\) be the number of times word \(j\) appears in word \(i\)’s context. GloVe minimizes:&lt;/p&gt;

\[J = \sum_{i,j=1}^{|V|} f(X_{ij})(\mathbf{w}_i^T \tilde{\mathbf{w}}_j + b_i + \tilde{b}_j - \log X_{ij})^2\]

&lt;p&gt;where \(\mathbf{w}_i\) and \(\tilde{\mathbf{w}}_j\) are word and context embeddings, \(b_i, \tilde{b}_j\) are biases, and \(f(X_{ij})\) is a weighting function:&lt;/p&gt;

\[f(x) = \begin{cases} (x/x_{\max})^\alpha &amp;amp; \text{if } x &amp;lt; x_{\max} \\ 1 &amp;amp; \text{otherwise} \end{cases}\]

&lt;p&gt;This weights frequent co-occurrences less heavily (they’re already well-represented) and caps influence of very frequent pairs. GloVe combines the benefits of global matrix factorization methods (leveraging entire corpus statistics) with local context window methods (Word2Vec), often producing embeddings competitive or superior to Word2Vec.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Imagine learning embeddings for a small vocabulary: {cat, dog, car, truck, animal, vehicle}. Initially, vectors are random. As we process text:&lt;/p&gt;

&lt;p&gt;“The cat is an animal” → “cat” and “animal” co-occur&lt;br /&gt;
“The dog is an animal” → “dog” and “animal” co-occur&lt;br /&gt;
“The car is a vehicle” → “car” and “vehicle” co-occur&lt;br /&gt;
“The truck is a vehicle” → “truck” and “vehicle” co-occur&lt;/p&gt;

&lt;p&gt;The model adjusts vectors so:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;“cat” and “dog” become close (both appear with “animal”)&lt;/li&gt;
  &lt;li&gt;“car” and “truck” become close (both appear with “vehicle”)&lt;/li&gt;
  &lt;li&gt;“cat” and “car” stay distant (appear in different contexts)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After seeing enough text, the 2D embedding space might organize as:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;     animal
        ↑
    dog • cat
        |
    ----+---- 
        |
  truck • car
        ↓
     vehicle
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Semantic categories (animals vs vehicles) cluster, and within categories, similar items are nearby. We can compute:&lt;/p&gt;

&lt;p&gt;“cat” - “animal” ≈ “dog” - “animal” (both point from category to instance)&lt;br /&gt;
“car” + “vehicle” ≈ “truck” (category + similarity gives similar item)&lt;/p&gt;

&lt;p&gt;This geometric structure enables generalization: if the model learns facts about “cat,” it can transfer to “dog” through their vector similarity.&lt;/p&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Complete Word2Vec implementation:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;collections&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Counter&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Word2VecSkipGram&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Skip-gram Word2Vec with negative sampling.
    
    Learns word embeddings by predicting context words from target words.
    Uses negative sampling to make training efficient.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Input and output embeddings
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Input: embeddings used when word is target
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Output: embeddings used when word is context
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initialize with small random values
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                                   &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;negative_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        target_words: (batch,) target word indices
        context_words: (batch,) context word indices (positive examples)
        negative_words: (batch, k) negative samples
        
        Returns negative log-likelihood
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Get embeddings
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;target_embeds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;input_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch, emb_dim)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;context_embeds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;output_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;context_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch, emb_dim)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;neg_embeds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;output_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;negative_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch, k, emb_dim)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Positive scores (target-context similarity)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;pos_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_embeds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context_embeds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch,)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;pos_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Negative scores (target-negative dissimilarity)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;neg_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bmm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neg_embeds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_embeds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch, k)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;neg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neg_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pos_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;neg_loss&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Prepare training data
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Word2Vec Embeddings&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simple corpus for demonstration
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
the cat sat on the mat .
the dog sat on the rug .
the cat and the dog are animals .
the car is a vehicle .
the truck is a vehicle .
cats and dogs are pets .
cars and trucks are vehicles .
&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;lower&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Build vocabulary
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;idx_to_word&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Corpus: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; words&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vocabulary: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; unique words&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample vocab: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate training pairs
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_training_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;window_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generate (target, context) pairs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Get context (words within window)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;context_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;window_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;context_end&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;window_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;context_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Don&apos;t pair with self
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;context_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_training_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;corpus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;window_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; training pairs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample pairs: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train Word2Vec
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Word2VecSkipGram&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embedding_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Small dim for demo
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training embeddings...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context_idx&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Sample negatives
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;neg_indices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;replace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# To tensors
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LongTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LongTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;context_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;negatives&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LongTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neg_indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;negatives&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Analyze learned embeddings
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Analyzing Learned Embeddings&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Find nearest neighbors
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;find_nearest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx_to_word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Find k nearest words to query word&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;word_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;word_vec&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Compute cosine similarities
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;similarities&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_vec&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word_vec&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-10&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Get top k (excluding self)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;top_k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;similarities&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argsort&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][::&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx_to_word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;similarities&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;top_k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test semantic similarity
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_words&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;dog&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;car&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_words&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;neighbors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;find_nearest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;embeddings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;word_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx_to_word&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Nearest to &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;word&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;neighbors&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Embeddings learned semantic relationships from co-occurrence patterns!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Similar words (cat/dog, car/truck) have similar embeddings.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-beyond-words-embeddings-in-recommendation-two-tower&quot;&gt;5. Beyond words: embeddings in recommendation (two-tower)&lt;/h2&gt;

&lt;p&gt;The same idea—“nearby vectors = similar”—is not limited to words. In &lt;strong&gt;recommendation systems&lt;/strong&gt; (video feeds, e-commerce) we learn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;User embedding&lt;/strong&gt; \(\mathbf{u} \in \mathbb{R}^d\) — a snapshot of preferences&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Item embedding&lt;/strong&gt; \(\mathbf{v} \in \mathbb{R}^d\) — a snapshot of content/product&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Matching scores are usually a dot product or cosine: \(s(u,i) = \mathbf{u}^\top \mathbf{v}\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/recsys_deep_ranking_nn.jpg&quot; alt=&quot;Deep net producing embeddings&quot; /&gt;
&lt;em&gt;Figure: A feedforward network used to learn representations / rank candidates. (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/recsys_embedding_128d.jpg&quot; alt=&quot;128-d embedding vector&quot; /&gt;
&lt;em&gt;Figure: Network output compressed to a dense vector (e.g. \(1\times 128\)) — a “snapshot” of preference or item. (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Two-tower models&lt;/strong&gt;: one tower encodes the user, one encodes the item; training pulls engaged (user, item) pairs close in embedding space and pushes negatives apart. At scale you precompute all item embeddings and, at serve time, encode the user once then run &lt;strong&gt;nearest-neighbor&lt;/strong&gt; (ANN) over billions of items.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/recsys_two_tower_matching.jpg&quot; alt=&quot;Two-tower: matching two 128-d vectors&quot; /&gt;
&lt;em&gt;Figure: Matching two same-dimension embeddings (user vs item) — the core of two-tower retrieval. (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Compared with Word2Vec: instead of word context, the training signal is &lt;strong&gt;behavior&lt;/strong&gt; (click, finish watching, purchase). The distributional hypothesis becomes: “users/items that appear in similar interaction ‘contexts’ get nearby embeddings.”&lt;/p&gt;

&lt;h2 id=&quot;6-related-concepts&quot;&gt;6. Related Concepts&lt;/h2&gt;

&lt;p&gt;Word embeddings connect to distributional semantics, the linguistic theory that word meaning is determined by context. The computational implementation—learning vectors such that words in similar contexts have similar representations—directly operationalizes this theory. Understanding this connection helps appreciate why embeddings work: they’re not arbitrary feature engineering but implementations of fundamental linguistic principles.&lt;/p&gt;

&lt;p&gt;Embeddings relate to dimensionality reduction techniques like PCA or autoencoders. We’re compressing high-dimensional one-hot vectors (vocab size) to low-dimensional dense vectors (embedding size) while preserving semantic information. The learned compression discovers that semantic relationships can be captured in far fewer dimensions than explicit symbol identity, revealing the intrinsic dimensionality of word semantics is much lower than vocabulary size.&lt;/p&gt;

&lt;p&gt;The evolution from static embeddings (Word2Vec, GloVe) to contextual embeddings (ELMo, BERT) reflects increasing sophistication. Static embeddings assign one vector per word type, so “bank” (financial) and “bank” (river) have identical representations despite different meanings. Contextual embeddings produce different vectors based on context, resolving polysemy.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/sa_vector_space_fruit_vs_companies.jpg&quot; alt=&quot;Vector space: fruit vs companies&quot; /&gt;
&lt;em&gt;Figure: Fruit cluster (apple/banana/orange…) separated from companies (Google/Microsoft/DeepSeek…). (Illustration from an intro Transformer / Self-Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter18/sa_contextual_apple_company_vector.jpg&quot; alt=&quot;After self-attention: “Apple” as a company&quot; /&gt;
&lt;em&gt;Figure: When the sentence talks about phones/color, the “Apple” vector shifts toward the company sense (logo). (Illustration from an intro Transformer / Self-Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This evolution shows the field progressing from learning word-level representations to modeling language’s context-dependent nature.&lt;/p&gt;

&lt;h2 id=&quot;7-fundamental-papers&quot;&gt;7. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1301.3781&quot;&gt;“Efficient Estimation of Word Representations in Vector Space” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Tomas Mikolov, Kai Chen, Greg Corrado, Jeffrey Dean&lt;br /&gt;
Word2Vec introduced efficient methods (skip-gram and CBOW) for learning word embeddings at scale. The negative sampling training procedure enabled processing billions of words, making embeddings practical for large vocabularies. The paper demonstrated remarkable semantic properties—analogies solved through vector arithmetic—showing embeddings capture sophisticated language patterns. Word2Vec’s simplicity, efficiency, and quality made it widely adopted, establishing embeddings as fundamental to NLP.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://aclanthology.org/D14-1162/&quot;&gt;“GloVe: Global Vectors for Word Representation” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Jeffrey Pennington, Richard Socher, Christopher Manning&lt;br /&gt;
GloVe combined global matrix factorization with local context, factorizing word co-occurrence matrices to learn embeddings. The method achieved competitive or superior performance to Word2Vec while providing intuitive interpretation through co-occurrence statistics. GloVe demonstrated that different training objectives could produce similar high-quality embeddings, suggesting the representation itself matters more than specific training procedure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1802.05365&quot;&gt;“Deep contextualized word representations” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Matthew Peters, Mark Neumann, Mohit Iyyer, Matt Gardner, Christopher Clark, Kenton Lee, Luke Zettlemoyer&lt;br /&gt;
ELMo introduced contextual embeddings from deep bidirectional LSTMs, representing each word differently based on sentence context. This addressed static embeddings’ inability to handle polysemy and context-dependent meaning. ELMo showed that deep language models learn different types of information at different layers (syntax in lower, semantics in higher), and combining layers improves downstream tasks. ELMo represented transition from static to contextual representations, paving way for BERT and Transformers.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;Using pre-trained embeddings without proper vocabulary alignment causes out-of-vocabulary issues. If your task vocabulary contains words not in the pre-trained embeddings, you need strategies: use subword embeddings (BPE, WordPiece), initialize missing words from similar words (if embeddings for “coronavirus” missing, average “virus” and “corona”), or fine-tune embeddings on domain-specific text.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Word embeddings represent words as dense continuous vectors where semantic similarity corresponds to geometric proximity, enabling neural networks to generalize across semantically related words through shared vector representations. Skip-gram Word2Vec predicts context from targets using negative sampling for efficiency, while GloVe factorizes co-occurrence matrices, both learning from unlabeled text through distributional hypothesis. The resulting embeddings exhibit remarkable properties including analogical reasoning through vector arithmetic (king - man + woman ≈ queen) and semantic clustering (synonyms have similar vectors), all emerging from co-occurrence patterns without explicit supervision. The same vector geometry powers &lt;strong&gt;recommendations&lt;/strong&gt;: user/item embeddings and two-tower models match preferences to content at massive scale. Pre-trained embeddings like Word2Vec and GloVe transfer to downstream tasks, providing semantic representations that improve performance across NLP applications from sentiment analysis to machine translation. Modern contextual embeddings from BERT provide context-dependent representations addressing polysemy, though static embeddings remain useful for efficiency and interpretability. Understanding word embeddings provides foundation for representation learning in NLP and beyond, demonstrating how neural networks can discover structure purely from data patterns.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/930207546288223&quot;&gt;What is a Transformer? Self-Attention for beginners (Part 1)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1501843101324752&quot;&gt;Word embeddings and how Transformers understand language&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1444915507374636&quot;&gt;Recommendation algorithms (TikTok-style)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=viZrOnJclY0&quot;&gt;Word Embedding and Word2Vec, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Skip-gram and the distributional hypothesis are this lesson’s core.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ISPId9Lhc1g&quot;&gt;The Illustrated Word2vec - A Gentle Intro to Word Embeddings in Machine Learning&lt;/a&gt; — Jay Alammar, English. A visual pass over the same vectors, useful for the analogy examples.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 2&lt;/td&gt;
          &lt;td&gt;Word Vector Representations: word2vec](https://www.youtube.com/watch?v=ERibwqs9p38) — Stanford University School of Engineering, English. The softmax objective and the negative-sampling shortcut the math section writes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>18 Natural Language Processing</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter18/18_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter18/18_00_Introduction</id>
   <content type="html">&lt;p&gt;Words are discrete symbols: as raw integer IDs, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;cat&quot;&lt;/code&gt; (ID 412), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;dog&quot;&lt;/code&gt; (ID 9817), and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;carburetor&quot;&lt;/code&gt; (ID 413) are completely equidistant, giving a neural network zero geometric clue that cats and dogs share meaning. Natural Language Processing took off the moment researchers turned discrete tokens into dense continuous vectors—first static embeddings like Word2Vec and GloVe, then contextual Transformer representations like BERT and GPT—turning syntax and semantics into linear algebra.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-trajectory-of-deep-nlp&quot;&gt;Key ideas: The Trajectory of Deep NLP&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Distributional Semantics &amp;amp; Vector Geometry&lt;/strong&gt;: Operationalizes J. R. Firth’s dictum (&lt;em&gt;“You shall know a word by the company it keeps”&lt;/em&gt;) by encoding co-occurrence patterns into dense vectors where cosine similarity tracks semantic relatedness.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Subword Tokenization (BPE / WordPiece / Unigram)&lt;/strong&gt;: Splits rare and morphological words into reusable subword pieces so vocabularies stay compact ($\sim 32\text{k}$–$128\text{k}$) with zero out-of-vocabulary &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;UNK&amp;gt;&lt;/code&gt; failures.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Static vs. Contextual Representations&lt;/strong&gt;: Contrasts one-vector-per-word-type models (where &lt;em&gt;“river bank”&lt;/em&gt; and &lt;em&gt;“bank account”&lt;/em&gt; share one vector) with Transformer contextual states that dynamically disambiguate every token from its surrounding sentence.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Transfer from Pretrained Language Models&lt;/strong&gt;: Connects masked and autoregressive language modeling directly to downstream classification, NER, QA, translation, and modern LLM prompting.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-one-hot-vectors-fail-where-dense-embeddings-succeed&quot;&gt;Worked example: Why One-Hot Vectors Fail Where Dense Embeddings Succeed&lt;/h3&gt;

&lt;p&gt;Consider a 4-word vocabulary &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{&quot;cat&quot;: 0, &quot;dog&quot;: 1, &quot;kitten&quot;: 2, &quot;truck&quot;: 3}&lt;/code&gt;.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;One-hot representation&lt;/strong&gt;: $e_{\text{cat}} = [1,0,0,0]$, $e_{\text{dog}} = [0,1,0,0]$, $e_{\text{truck}} = [0,0,0,1]$.
\(\cos(e_{\text{cat}}, e_{\text{dog}}) = 0, \qquad \cos(e_{\text{cat}}, e_{\text{truck}}) = 0.\)
Every distinct pair is strictly orthogonal ($90^\circ$ apart)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dense 2D learned embeddings&lt;/strong&gt; (axis 1: animacy, axis 2: domestic/small):
\(v_{\text{cat}} = [0.9, 0.8], \quad v_{\text{dog}} = [0.9, 0.7], \quad v_{\text{truck}} = [-0.8, -0.6].\)
    &lt;ul&gt;
      &lt;li&gt;Norms: $|v_{\text{cat}}| = \sqrt{0.81 + 0.64} = 1.204$, $|v_{\text{dog}}| = \sqrt{0.81 + 0.49} = 1.140$, $|v_{\text{truck}}| = 1.000$.&lt;/li&gt;
      &lt;li&gt;$\cos(v_{\text{cat}}, v_{\text{dog}}) = \frac{0.81 + 0.56}{1.204 \times 1.140} = \frac{1.37}{1.373} \approx +0.998$ (nearly parallel!).&lt;/li&gt;
      &lt;li&gt;$\cos(v_{\text{cat}}, v_{\text{truck}}) = \frac{-0.72 - 0.48}{1.204 \times 1.000} = -0.997$ (nearly opposite!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Dense embeddings compress a $50{,}000$-dimensional sparse one-hot space into a few hundred continuous dimensions where semantic similarity becomes a single dot product.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;NLP applies deep learning to understand and generate human language. This chapter covers word embeddings (Word2Vec, GloVe), language models (GPT, BERT), sequence tasks (NER, POS tagging), text classification, machine translation, question answering, and text generation. We explore modern NLP architectures and their practical applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Quick note:&lt;/strong&gt; The “nearby vectors = similar” idea behind word embeddings also underpins recommendation systems (user/item embeddings, two-tower models) — see the extended section in the word-embeddings lesson.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Visual path (word-embeddings lesson):&lt;/strong&gt; tokenization → one-hot / bag-of-words (and why they fail) → 2D embedding space + vector arithmetic → Word2Vec/CBOW context windows → embedding matrices W1·W2. Transformers/BERT lift &lt;strong&gt;static&lt;/strong&gt; embeddings to &lt;strong&gt;contextual&lt;/strong&gt; ones (the same word “Apple” gets different vectors by meaning) — continued in Chapter 08. The decoder-only LM hub (token table as layer 0, next-token CE, serving) is &lt;strong&gt;Chapter 26&lt;/strong&gt;.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/930207546288223&quot;&gt;What is a Transformer? Self-Attention for beginners (Part 1)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1501843101324752&quot;&gt;Word embeddings and how Transformers understand language&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1444915507374636&quot;&gt;Recommendation algorithms (TikTok-style)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After word embeddings, see &lt;strong&gt;18-99 Modern Applications and Updates&lt;/strong&gt; for RAG, instruction-tuned LMs, and modern tokenizers.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=viZrOnJclY0&quot;&gt;Word Embedding and Word2Vec, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. A word as a vector is this chapter.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=ISPId9Lhc1g&quot;&gt;The Illustrated Word2vec - A Gentle Intro to Word Embeddings in Machine Learning&lt;/a&gt; — Jay Alammar, English. The illustrated word2vec story, including the analogy arithmetic.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 2&lt;/td&gt;
          &lt;td&gt;Word Vector Representations: word2vec](https://www.youtube.com/watch?v=ERibwqs9p38) — Stanford University School of Engineering, English. Stanford’s word-vector lecture for the same objective at course length.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>17-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter17/17_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter17/17_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Between 2023 and 2026, computer vision broke free of fixed 80-class COCO label lists. With Segment Anything (SAM / SAM 2), you click a single point on &lt;em&gt;any&lt;/em&gt; object in an image or video and get a crisp mask zero-shot; with Grounding DINO and RT-DETR, you type an arbitrary text phrase like &lt;em&gt;“the cracked red mug on the left”&lt;/em&gt; and get end-to-end Transformer bounding boxes without ever running NMS.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-post-yolo--post-mask-r-cnn-vision-20222026&quot;&gt;Key ideas: Post-YOLO &amp;amp; Post-Mask-R-CNN Vision (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Promptable Segmentation (SAM &amp;amp; SAM 2)&lt;/strong&gt;: Decouples heavy image encoding from a lightweight prompt decoder (points, boxes, masks, and video memory banks), enabling real-time interactive segmentation across unseen categories.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — NMS-Free End-to-End Detection (DETR &amp;amp; RT-DETR)&lt;/strong&gt;: Uses bipartite Hungarian matching between learned object queries and ground-truth boxes so the Transformer predicts unique objects directly without heuristic NMS.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Open-Vocabulary Detection (Grounding DINO)&lt;/strong&gt;: Fuses text-encoder phrase embeddings with visual multi-scale features via cross-attention, turning fixed-class classification into phrase–region similarity matching.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Production Edge Detectors (YOLOv8–v11 / YOLO-World)&lt;/strong&gt;: Continues to dominate latency-critical industrial inspection, drones, and edge cameras where TensorRT/ONNX throughput is paramount.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-bipartite-hungarian-matching-cost-in-detr&quot;&gt;Worked example: Bipartite Hungarian Matching Cost in DETR&lt;/h3&gt;

&lt;p&gt;Suppose an image has 2 ground-truth objects ($G_1, G_2$) and a DETR decoder emits 2 object queries ($Q_1, Q_2$) with pairwise matching cost matrix $C_{ij} = \mathcal{L}&lt;em&gt;{\text{cls}}(Q_i, G_j) + \mathcal{L}&lt;/em&gt;{\text{box}}(Q_i, G_j)$:
\(C = \begin{bmatrix} 0.9 &amp;amp; 0.2 \\ 0.3 &amp;amp; 0.8 \end{bmatrix}.\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate both possible one-to-one assignments&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Assignment 1 ($Q_1 \to G_1,\; Q_2 \to G_2$): total cost $= 0.9 + 0.8 = 1.7$.&lt;/li&gt;
      &lt;li&gt;Assignment 2 ($Q_1 \to G_2,\; Q_2 \to G_1$): total cost $= 0.2 + 0.3 = 0.5$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Optimal Hungarian match&lt;/strong&gt;: Assignment 2 ($Q_1 \to G_2,\; Q_2 \to G_1$) with minimum cost $0.5$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why this eliminates NMS&lt;/strong&gt;: Because each ground-truth object is matched to &lt;em&gt;strictly one&lt;/em&gt; query, every other overlapping query is trained to predict &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;no-object&lt;/code&gt; ($\varnothing$), teaching the Transformer itself to suppress duplicates during training.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Hungarian bipartite matching replaces hand-tuned anchor matching and NMS with a clean, global combinatorial assignment.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-detection-and-segmentation-after-yolo--mask-r-cnn&quot;&gt;Optional: detection and segmentation after YOLO / Mask R-CNN&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace two-stage vs one-stage detection theory or the YOLO / Faster R-CNN notes. It covers the 2023–2025 models used in products: &lt;strong&gt;SAM/SAM 2&lt;/strong&gt;, &lt;strong&gt;RT-DETR&lt;/strong&gt;, &lt;strong&gt;Grounding DINO&lt;/strong&gt;, and current YOLO lines.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The matching / IoU / NMS ideas in this chapter still decide whether a box is correct:&lt;/p&gt;

\[\mathrm{IoU}(A,B) = \frac{|A\cap B|}{|A\cup B|}.\]

&lt;p&gt;The architectures around those metrics changed.&lt;/p&gt;

&lt;h2 id=&quot;1-promptable-segmentation-sam-and-sam-2&quot;&gt;1. Promptable segmentation: SAM and SAM 2&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.02643&quot;&gt;Kirillov et al., 2023&lt;/a&gt; (Segment Anything) treat segmentation as a &lt;strong&gt;promptable&lt;/strong&gt; foundation task: points, boxes, or masks in; instance masks out. &lt;a href=&quot;https://arxiv.org/abs/2408.00714&quot;&gt;Ravi et al., 2024&lt;/a&gt; (SAM 2) add a streaming memory for &lt;strong&gt;video&lt;/strong&gt;. Data-science use: label a few points, export masks, train a smaller specialist — not a replacement for U-Net when you already have a pixel-labeled medical set.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;real-time-detr-style-detectors&quot;&gt;Real-time DETR-style detectors&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.08069&quot;&gt;Zhao et al., 2024&lt;/a&gt; (RT-DETR) make transformer detectors fast enough to displace some YOLO deployments. You still evaluate mAP the way the theory lesson teaches.&lt;/p&gt;

&lt;h3 id=&quot;open-vocabulary-grounding-dino--sam&quot;&gt;Open-vocabulary: Grounding DINO + SAM&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.05499&quot;&gt;Liu et al., 2023&lt;/a&gt; (Grounding DINO) take a &lt;strong&gt;text&lt;/strong&gt; query (“red helmet”) and return boxes. Combined with SAM (“Grounded SAM”) this is the 2024–2026 annotation and robotics perception pattern. Classic closed-set COCO heads remain for factory SKUs.&lt;/p&gt;

&lt;h3 id=&quot;yolo-in-production&quot;&gt;YOLO in production&lt;/h3&gt;

&lt;p&gt;Ultralytics &lt;strong&gt;YOLOv8 / YOLO11&lt;/strong&gt; keep the convolutional one-stage recipe. Use them when latency and export (ONNX, TensorRT, CoreML) matter more than open vocabulary.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/sam2&quot;&gt;facebookresearch/sam2&lt;/a&gt; and &lt;a href=&quot;https://github.com/facebookresearch/segment-anything&quot;&gt;facebookresearch/segment-anything&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/IDEA-Research/GroundingDINO&quot;&gt;IDEA-Research/GroundingDINO&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ultralytics/ultralytics&quot;&gt;ultralytics/ultralytics&lt;/a&gt; and &lt;a href=&quot;https://github.com/lyuwenyu/RT-DETR&quot;&gt;lyuwenyu/RT-DETR&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.02643&quot;&gt;Segment Anything (Kirillov et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2408.00714&quot;&gt;SAM 2 (Ravi et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.05499&quot;&gt;Grounding DINO (Liu et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.08069&quot;&gt;DETRs Beat YOLOs on Real-time Object Detection — RT-DETR (Zhao et al., 2024)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Implement the detector matching and the chapter’s R-CNN/YOLO path first. This lesson only adds &lt;strong&gt;promptable and open-vocabulary&lt;/strong&gt; heads used in 2023–2026 pipelines.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=OhxJkqD1vuE&quot;&gt;Explaining the Segment Anything Model - Network architecture, Dataset, Training&lt;/a&gt; — Neural Breakdown with AVB, English. The Segment Anything model is the promptable segmenter this note describes.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 11&lt;/td&gt;
          &lt;td&gt;Detection and Segmentation](https://www.youtube.com/watch?v=nDPWywWRIRo) — Stanford University School of Engineering, English. The classical detection and segmentation problem SAM generalizes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, English. The vision backbone underneath that promptable head.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>17-01 Object Detection Fundamentals</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter17/17_01_Object_Detection/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter17/17_01_Object_Detection</id>
   <content type="html">&lt;p&gt;Object detection is where deep learning leaves tidy single-label benchmarks and enters the messy visual world—multiple overlapping objects, dramatic scale changes, and strict real-time latency budgets. Connecting geometric theory (IoU, anchor offsets, RPNs) with torchvision’s end-to-end training contract prepares you to read, debug, and customize both two-stage and one-stage detectors.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-object-detection-theory-to-code-bridge&quot;&gt;Key ideas: Object Detection Theory-to-Code Bridge&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Two-Stage vs. One-Stage Architectures&lt;/strong&gt;: Contrasts proposal-then-refine pipelines (Faster R-CNN) with dense single-shot grids (YOLO, RetinaNet) across accuracy–latency curves.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Geometric Overlap &amp;amp; Anchor Assignment&lt;/strong&gt;: Uses IoU thresholds to match dense anchors to ground-truth objects and regress scale-invariant deltas.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Post-Processing &amp;amp; Evaluation&lt;/strong&gt;: Applies NMS to deduplicate boxes and measures detector quality with precision–recall Area Under Curve (AP / mAP).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — PyTorch Detection Engineering&lt;/strong&gt;: Handles ragged multi-box batches, background class indexing, and pretrained FPN backbone fine-tuning.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-precision-recall-and-ap-from-4-ranked-detections&quot;&gt;Worked example: Computing Precision, Recall, and AP from 4 Ranked Detections&lt;/h3&gt;

&lt;p&gt;Suppose an image contains $M = 2$ ground-truth dogs, and our detector outputs 4 ranked detections (highest score first) labeled True Positive (TP) or False Positive (FP) at IoU $\ge 0.50$:
\([\text{TP},\; \text{FP},\; \text{TP},\; \text{FP}].\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cumulative Precision &amp;amp; Recall at each rank $k$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Rank 1 (TP): $\text{Prec} = 1/1 = 1.00,\quad \text{Rec} = 1/2 = 0.50$.&lt;/li&gt;
      &lt;li&gt;Rank 2 (FP): $\text{Prec} = 1/2 = 0.50,\quad \text{Rec} = 1/2 = 0.50$.&lt;/li&gt;
      &lt;li&gt;Rank 3 (TP): $\text{Prec} = 2/3 = 0.667,\quad \text{Rec} = 2/2 = 1.00$.&lt;/li&gt;
      &lt;li&gt;Rank 4 (FP): $\text{Prec} = 2/4 = 0.50,\quad \text{Rec} = 2/2 = 1.00$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;All-point interpolated Average Precision (taking max precision to the right of each recall step)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Over recall interval $[0.0, 0.5]$: max precision $= 1.00 \implies \text{area} = 0.5 \times 1.00 = 0.500$.&lt;/li&gt;
      &lt;li&gt;Over recall interval $(0.5, 1.0]$: max precision $= 0.667 \implies \text{area} = 0.5 \times 0.667 = 0.333$.
\(\text{AP@50} = 0.500 + 0.333 = 0.833.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: A single high-confidence false positive at rank 2 costs $0.167$ AP points—showing why ranking calibration matters just as much as finding all objects.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Object detection:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Theory&lt;/strong&gt; — IoU, boxes, RPN, intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implementation&lt;/strong&gt; — code path, papers, pitfalls&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=svn9-xV7wjk&quot;&gt;How YOLO Object Detection Works&lt;/a&gt; — DeepBean, English. The grid, the boxes, and the objectness score.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 11&lt;/td&gt;
          &lt;td&gt;Detection and Segmentation](https://www.youtube.com/watch?v=nDPWywWRIRo) — Stanford University School of Engineering, English. The family YOLO belongs to, including the two-stage detectors the lesson compares.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, English. What the backbone must already see before a detection head is worth adding.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>17-01-02 Object Detection Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter17/17_01_02_Object_Detection_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter17/17_01_02_Object_Detection_Implementation</id>
   <content type="html">&lt;p&gt;Implementing a Faster R-CNN training loop in PyTorch feels completely different from image classification: images can have different resolutions, each image carries a variable number of bounding boxes (from 0 to 50+), and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torchvision&lt;/code&gt;’s detection models expect a list of tensors plus a list of dictionaries—returning a &lt;em&gt;loss dictionary&lt;/em&gt; during &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.train()&lt;/code&gt; and a &lt;em&gt;prediction dictionary&lt;/em&gt; during &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.eval()&lt;/code&gt;. Mastering that data contract and collate function eliminates 90% of detection pipeline bugs.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-engineering-object-detectors-in-pytorch&quot;&gt;Key ideas: Engineering Object Detectors in PyTorch&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Custom Collate &amp;amp; Ragged Target Dictionaries&lt;/strong&gt;: Uses &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;collate_fn = lambda batch: tuple(zip(*batch))&lt;/code&gt; because standard &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DataLoader&lt;/code&gt; stacking crashes when image 1 has 2 boxes and image 2 has 7 boxes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Head Replacement &amp;amp; Background Class Indexing&lt;/strong&gt;: Reserves class index &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; strictly for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;__background__&lt;/code&gt;, setting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;num_classes = K + 1&lt;/code&gt; when swapping &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FastRCNNPredictor&lt;/code&gt; on a pretrained backbone.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Dual-Mode Forward Contract&lt;/strong&gt;: Understands that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model(images, targets)&lt;/code&gt; returns &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;{&apos;loss_classifier&apos;, &apos;loss_box_reg&apos;, &apos;loss_objectness&apos;, &apos;loss_rpn_box_reg&apos;}&lt;/code&gt; in training mode, while &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model(images)&lt;/code&gt; returns &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;boxes, labels, scores&lt;/code&gt; in eval mode.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Confidence Thresholding &amp;amp; NMS Post-Processing&lt;/strong&gt;: Filters raw proposals by score threshold and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torchvision.ops.nms&lt;/code&gt; before computing COCO-style mAP or visualizing boxes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-walking-through-greedy-nms-on-3-overlapping-detections&quot;&gt;Worked example: Walking Through Greedy NMS on 3 Overlapping Detections&lt;/h3&gt;

&lt;p&gt;Suppose for class “car,” our detector outputs three boxes with confidence scores:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Box 1: score $= 0.92$&lt;/li&gt;
  &lt;li&gt;Box 2: score $= 0.85$, with $\text{IoU}(B_1, B_2) = 0.72$&lt;/li&gt;
  &lt;li&gt;Box 3: score $= 0.78$, with $\text{IoU}(B_1, B_3) = 0.15$ and $\text{IoU}(B_2, B_3) = 0.60$&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let the NMS IoU threshold be $\tau_{\text{NMS}} = 0.50$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sort by descending score&lt;/strong&gt;: $[B_1 (0.92),\; B_2 (0.85),\; B_3 (0.78)]$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pop highest-scoring box $B_1$ and keep it&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Check $B_2$: $\text{IoU}(B_1, B_2) = 0.72 &amp;gt; 0.50 \implies$ &lt;strong&gt;suppress $B_2$&lt;/strong&gt; (duplicate of car 1).&lt;/li&gt;
      &lt;li&gt;Check $B_3$: $\text{IoU}(B_1, B_3) = 0.15 \le 0.50 \implies$ keep $B_3$ in candidate pool.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pop next remaining box $B_3$ and keep it&lt;/strong&gt; (pool is now empty).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Final kept detections&lt;/strong&gt;: ${B_1, B_3}$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Notice that $B_3$ survived even though $\text{IoU}(B_2, B_3) = 0.60$, because $B_2$ was already eliminated by $B_1$—showing why sorting order and threshold choice critically affect crowded scenes.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Complete Faster R-CNN style implementation:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision.models.detection&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fasterrcnn_resnet50_fpn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision.models.detection.faster_rcnn&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;FastRCNNPredictor&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision.transforms&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Object Detection with Faster R-CNN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Load pre-trained Faster R-CNN
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Loading Pre-trained Faster R-CNN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fasterrcnn_resnet50_fpn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;DEFAULT&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Faster R-CNN architecture:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Backbone: ResNet-50 + Feature Pyramid Network&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Region Proposal Network (RPN): Generates object proposals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  RoI Pooling: Extracts features from proposals&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Detection Head: Classifies and refines boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Adapt for custom dataset (e.g., 10 classes + background)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 10 object classes + background
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Replace the classifier
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;roi_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;box_predictor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cls_score&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;roi_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;box_predictor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;FastRCNNPredictor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adapted for &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; object classes + background&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 2. Prepare custom dataset format
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Dataset Format for Object Detection&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CustomDetectionDataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Object detection dataset format.
    
    Each sample returns:
    - image: (3, H, W) tensor
    - target: dictionary with:
        - boxes: (N, 4) tensor of [x1, y1, x2, y2] coordinates
        - labels: (N,) tensor of class indices
        - (optional) masks, keypoints, etc.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;annotations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;annotations&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__len__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__getitem__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Load image (simulated here)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Get annotations for this image
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [[x1,y1,x2,y2], ...]
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# [class1, class2, ...]
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Convert to tensors
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;as_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;as_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;int64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create dummy data for demonstration
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Creating simulated detection dataset...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simulate 100 images with random objects
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;dummy_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;600&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;800&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simulate annotations (random boxes and classes)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dummy_annotations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n_objects&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 1-4 objects per image
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Random boxes (x1, y1, x2, y2)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_objects&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;700&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;800&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;600&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Classes 1-10
&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;dummy_annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;({&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CustomDetectionDataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dummy_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dummy_annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                         &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;collate_fn&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dataset: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; images&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample annotation: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dummy_annotations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 3. Training
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;3. Training Object Detector&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Move model to device
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;cuda&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cuda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;is_available&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Optimizer
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.005&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0005&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training for &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; epochs...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Using dummy data - in practice, use real annotated images)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()}&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward pass returns loss dict during training
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss_dict&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Combine losses
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss_dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training complete!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 4. Inference
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;4. Running Inference&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test on one image
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_img&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;600&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;800&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions for test image:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Boxes shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Labels shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Scores shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Filter by confidence threshold
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;confidence_threshold&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;confidence_threshold&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Detections with confidence &amp;gt; &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;confidence_threshold&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; objects detected&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;box&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;boxes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;score&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;keep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;    Class &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: box=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;box&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, confidence=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;score&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Implement YOLO-style single-stage detector:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single-Stage Detection (YOLO-style)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSingleStageDetector&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Simplified YOLO-style detector for educational purposes.
    
    Architecture:
    - Backbone CNN extracts features
    - Detection head predicts boxes + classes for grid cells
    - Each cell predicts B boxes with (x, y, w, h, confidence, class_probs)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backbone (simplified - use any CNN)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;backbone&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Detection head
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Each grid cell outputs: B boxes × (5 + num_classes)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# 5 = (x, y, w, h, confidence)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;output_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;detection_head&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (B, 3, H, W) images
        
        Returns: (B, grid_size, grid_size, num_boxes, 5+num_classes)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Extract features
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backbone&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, 512, grid_size, grid_size)
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Predict detections
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detection_head&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Reshape to (B, grid, grid, boxes, 5+classes)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;permute&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, grid, grid, boxes, ...)
&lt;/span&gt;        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;detections&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;detector&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSingleStageDetector&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_boxes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grid_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single-stage detector architecture:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Grid size: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Boxes per cell: 3&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Classes: 10&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Total predictions: 13×13×3 = 507 boxes per image&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;416&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;416&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Batch of 2, 416×416 images
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;detector&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Output shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 13, 13, 3, 15)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dimensions: (batch, grid_y, grid_x, boxes, 5+classes)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Each box prediction has:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - 4 coordinates (x, y, w, h)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - 1 confidence score&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - 10 class probabilities&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single forward pass produces all detections - very fast!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Object detection connects to image classification through its foundation in convolutional feature extraction. The backbone networks (ResNet, VGG, MobileNet) are typically classification networks adapted for detection by removing final classification layers and adding detection heads. The features learned for classification—edges, textures, object parts—transfer naturally to detection because recognizing “this is a car” (classification) and “there’s a car at this location” (detection) both require understanding car appearance. However, detection requires additional capabilities: localizing precisely where objects are, handling multiple objects and scales, and distinguishing object from background. Understanding this connection helps appreciate why ImageNet pre-trained classifiers provide good starting points for detection but require architectural extensions (FPN for multi-scale, RPN for proposals) to reach full detection capability.&lt;/p&gt;

&lt;p&gt;The relationship to semantic segmentation illuminates different granularities of visual understanding. Classification assigns one label per image. Detection assigns labels and boxes to multiple objects per image. Semantic segmentation assigns labels to every pixel, delineating object boundaries exactly. Instance segmentation combines detection and segmentation, providing pixel-perfect masks for each object instance. This progression from coarse (image-level) to fine (pixel-level) understanding reflects different application requirements and computational tradeoffs. Detection provides a balance: more informative than classification (where are objects?) without the computational cost of pixel-level segmentation.&lt;/p&gt;

&lt;p&gt;Object detection’s connection to attention mechanisms is increasingly important in modern architectures. Transformers are replacing traditional detection heads through DETR (Detection Transformer), which treats object detection as set prediction using attention to directly predict all objects in parallel without anchors or NMS. The attention mechanism learns to attend to object locations and extents, providing an elegant end-to-end trainable alternative to the complex pipelines of traditional detectors. Understanding how attention can replace hand-crafted components like anchors and NMS helps appreciate Transformers’ generality beyond NLP.&lt;/p&gt;

&lt;p&gt;The evolution from R-CNN to Fast R-CNN to Faster R-CNN demonstrates systematic optimization of computational bottlenecks. R-CNN ran CNN feature extraction separately for each proposal (2000 forward passes per image—very slow). Fast R-CNN extracted features once for the whole image, then used RoI pooling to get proposal features (single forward pass—much faster). Faster R-CNN made proposal generation part of the network through RPN (fully differentiable, end-to-end trainable). Each innovation addressed a specific inefficiency while maintaining accuracy, showing how systems evolve through targeted improvements rather than complete redesigns.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1311.2524&quot;&gt;“Rich feature hierarchies for accurate object detection and semantic segmentation” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ross Girshick, Jeff Donahue, Trevor Darrell, Jitendra Malik&lt;br /&gt;
R-CNN revolutionized object detection by applying CNNs, previously successful for classification, to detection through region proposals. The approach was conceptually simple: use selective search to propose ~2000 regions per image, extract CNN features from each (forward passing each through AlexNet), then classify regions with SVMs and refine boxes with regression. While computationally expensive (2000 forward passes per image), R-CNN achieved dramatic improvements over traditional methods, demonstrating that learned features vastly outperform hand-crafted features for detection. The paper established the region-based detection paradigm and showed transfer learning (ImageNet pre-training for detection) was highly effective. R-CNN’s success sparked the deep learning revolution in object detection, leading to numerous improvements addressing its computational limitations while maintaining its core insight: detection can be solved through region classification with learned features.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1504.08083&quot;&gt;“Fast R-CNN” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Author&lt;/em&gt;: Ross Girshick&lt;br /&gt;
Fast R-CNN addressed R-CNN’s computational bottleneck by sharing CNN computation across proposals through RoI (Region of Interest) pooling. Instead of running CNN separately for each proposal, extract features once for the whole image, then use RoI pooling to extract fixed-size feature vectors for each proposal from the shared feature map. This reduced forward passes from 2000 per image to 1, achieving ~10× speedup while improving accuracy through joint training of feature extraction, classification, and bounding box regression. The paper introduced multi-task loss combining classification and localization, showing that joint training improves both tasks compared to training separately. Fast R-CNN demonstrated that systematic analysis of computational bottlenecks and clever architectural innovations could dramatically improve efficiency without sacrificing accuracy, establishing principles for designing practical detection systems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1506.01497&quot;&gt;“Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Shaoqing Ren, Kaiming He, Ross Girshick, Jian Sun&lt;br /&gt;
Faster R-CNN completed the evolution to fully differentiable detection by replacing selective search with Region Proposal Networks, making the entire detection pipeline trainable end-to-end. RPN uses learned convolutional filters to predict objectness and box coordinates at every position in the feature map, generating proposals through learned mechanisms rather than hand-crafted algorithms. This innovation enabled sharing computation between proposal generation and detection, improved proposal quality through supervised training, and achieved near real-time speeds (5 FPS). The anchor box mechanism—predicting offsets from predefined boxes of different aspect ratios and scales—became standard in subsequent detectors. Faster R-CNN set the template for two-stage detection and remained state-of-the-art for years, demonstrating that careful end-to-end design outperforms pipelined approaches with non-differentiable components.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1506.02640&quot;&gt;“You Only Look Once: Unified, Real-Time Object Detection” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi&lt;br /&gt;
YOLO fundamentally changed object detection by framing it as regression from image pixels directly to bounding box coordinates and class probabilities, enabling real-time detection (45 FPS) through a single forward pass. By dividing images into grids and having each cell predict boxes, YOLO eliminated region proposals and their associated computational cost. While initial accuracy was lower than Faster R-CNN (particularly for small objects), YOLO’s speed enabled real-time applications like autonomous driving and robotics. The paper showed that detection need not follow the two-stage paradigm, inspiring numerous single-stage detectors. YOLO’s end-to-end design philosophy—predicting everything in one shot—demonstrated that simple, unified approaches could compete with complex pipelines when properly designed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1612.03144&quot;&gt;“Feature Pyramid Networks for Object Detection” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Tsung-Yi Lin, Piotr Dollár, Ross Girshick, Kaiming He, Bharath Hariharan, Serge Belongie&lt;br /&gt;
FPN addressed multi-scale detection by building feature pyramids with strong semantics at all scales, combining high-resolution but semantically weak low-level features with low-resolution but semantically strong high-level features through top-down pathways and lateral connections. This enables detecting large objects using high-level features and small objects using low-level features enriched with semantic information from higher layers. FPN dramatically improved detection of objects at different scales, particularly small objects which previous methods struggled with. The architectural pattern—building pyramids with both bottom-up (standard CNN) and top-down pathways—has been widely adopted beyond detection to segmentation and other dense prediction tasks. FPN demonstrated that careful multi-scale architecture design addresses fundamental challenges in visual recognition.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;Anchor box design significantly affects detection performance but is often overlooked. Anchors should match typical object aspect ratios and sizes in your dataset. For pedestrian detection (tall, narrow objects), use anchors like 1:3 and 1:4 aspect ratios. For cars (wider), use 2:1 or 3:2. The k-means clustering on training set bounding boxes can discover good anchor dimensions automatically. Having too many anchors wastes computation without improving accuracy, while too few miss important object types. Typical YOLO uses 9 anchors (3 scales × 3 aspect ratios), Faster R-CNN uses 9 (3 scales × 3 ratios) per position.&lt;/p&gt;

&lt;p&gt;Non-maximum suppression threshold selection involves precision-recall tradeoffs. Lower IoU threshold (0.3) suppresses more boxes, reducing duplicates but potentially eliminating valid detections of nearby objects. Higher threshold (0.7) keeps more boxes, detecting nearby objects well but producing duplicates. For crowded scenes (many nearby objects), use higher threshold. For sparse scenes, lower threshold. Understanding that NMS threshold controls this tradeoff allows tuning for specific applications.&lt;/p&gt;

&lt;p&gt;Class imbalance in object detection is severe and requires careful handling. Most anchor boxes are background (no object), creating extreme imbalance between background and object classes (often 1000:1 or more). Without handling, the detector learns to predict background for everything (trivial solution achieving 99.9% accuracy). Solutions include hard negative mining (train on hard background examples, ignore easy ones), focal loss (weight loss by difficulty, downweighting easy classifications), and balanced sampling (ensure batches contain similar numbers of object and background examples).&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Object detection extends classification to localizing and recognizing multiple objects per image, requiring simultaneous region proposal, classification, and bounding box regression. Two-stage detectors separate proposal generation from detection, using Region Proposal Networks to generate candidates and detection heads to classify and refine, achieving high accuracy through focused computation on object regions. Single-stage detectors directly predict boxes and classes from grid cells, enabling real-time performance through single forward pass at slight accuracy cost. Intersection over Union measures localization quality, with detections considered correct when IoU with ground-truth exceeds threshold (typically 0.5) and class matches. Anchor boxes provide reference boxes at different scales and aspect ratios, with networks predicting offsets rather than absolute coordinates, improving training stability. Feature pyramids enable multi-scale detection by combining high-level semantic features with high-resolution spatial features. Non-maximum suppression eliminates duplicate detections by keeping highest-confidence boxes and suppressing overlapping boxes. Multi-task training jointly optimizes classification and localization, with losses balanced to achieve both accurate recognition and precise localization. Understanding object detection requires appreciating how these components coordinate to handle variable numbers of objects at different scales, positions, and classes while maintaining real-time or near-real-time performance for practical applications.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=svn9-xV7wjk&quot;&gt;How YOLO Object Detection Works&lt;/a&gt; — DeepBean, English. So the tensors you allocate match a real detector’s outputs.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 11&lt;/td&gt;
          &lt;td&gt;Detection and Segmentation](https://www.youtube.com/watch?v=nDPWywWRIRo) — Stanford University School of Engineering, English. The loss terms (classification, box, objectness) an implementation has to sum.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pDdP0TFzsoQ&quot;&gt;PyTorch Tutorial 14 - Convolutional Neural Network (CNN)&lt;/a&gt; — Patrick Loeber, English. The conv backbone the detection head attaches to.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>17-01-01 Object Detection Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter17/17_01_01_Object_Detection_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter17/17_01_01_Object_Detection_Theory</id>
   <content type="html">&lt;p&gt;Object detection asks a single network to answer two fundamentally different questions at once: &lt;em&gt;“What is it?”&lt;/em&gt; (a discrete, translation-invariant classification problem) and &lt;em&gt;“Where is it?”&lt;/em&gt; (a continuous, translation-equivariant geometry problem). The breakthrough of modern detectors—from Faster R-CNN’s anchor-based Region Proposal Networks to YOLO’s dense grid predictions—was reframing raw coordinate prediction as predicting small, scale-invariant &lt;em&gt;offsets&lt;/em&gt; relative to reference anchors, then pruning duplicates with Non-Maximum Suppression (NMS).&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mathematical-core-of-object-detection&quot;&gt;Key ideas: Mathematical Core of Object Detection&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Intersection over Union (IoU &amp;amp; GIoU)&lt;/strong&gt;: Defines geometric overlap between predicted and ground-truth boxes to assign positive/negative training anchors and evaluate detection quality.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Scale-Invariant Box Parameterization&lt;/strong&gt;: Regresses normalized center offsets $(t_x, t_y)$ and log-scale ratios $(t_w, t_h)$ relative to an anchor $(x_a, y_a, w_a, h_a)$ so small and large objects contribute balanced gradients.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Multi-Task Loss &amp;amp; Class Imbalance&lt;/strong&gt;: Combines classification loss (Cross-Entropy or Focal Loss to suppress easy background anchors) with Smooth-L1 or IoU-based box regression loss.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Non-Maximum Suppression (NMS) &amp;amp; mAP&lt;/strong&gt;: Removes redundant overlapping detections per class via greedy IoU thresholding and integrates precision–recall curves across IoU thresholds (AP@50, AP@[.50:.95]).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-exact-box-iou-and-anchor-regression-targets&quot;&gt;Worked example: Computing Exact Box IoU and Anchor Regression Targets&lt;/h3&gt;

&lt;p&gt;Suppose an anchor box is $A = (x_1=10, y_1=10, x_2=50, y_2=50)$ (center $(30, 30)$, width $w_a = 40$, height $h_a = 40$), and a ground-truth box is $G = (x_1=20, y_1=20, x_2=60, y_2=60)$ (center $(40, 40)$, width $w_g = 40$, height $h_g = 40$).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Intersection box&lt;/strong&gt;:
\(x_{\text{left}} = \max(10, 20) = 20, \quad y_{\text{top}} = \max(10, 20) = 20,\)
\(x_{\text{right}} = \min(50, 60) = 50, \quad y_{\text{bottom}} = \min(50, 60) = 50.\)
\(\text{Area}_{\text{inter}} = (50 - 20) \times (50 - 20) = 30 \times 30 = 900.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Union and IoU&lt;/strong&gt;:
\(\text{Area}_A = 40 \times 40 = 1600, \quad \text{Area}_G = 1600, \quad \text{Area}_{\text{union}} = 1600 + 1600 - 900 = 2300.\)
\(\text{IoU}(A, G) = \frac{900}{2300} \approx 0.3913.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Faster R-CNN regression targets $(t_x^&lt;em&gt;, t_y^&lt;/em&gt;, t_w^&lt;em&gt;, t_h^&lt;/em&gt;)$&lt;/strong&gt;:
\(t_x^* = \frac{40 - 30}{40} = +0.25, \quad t_y^* = \frac{40 - 30}{40} = +0.25, \quad t_w^* = \ln\frac{40}{40} = 0, \quad t_h^* = \ln\frac{40}{40} = 0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Even shifting a box by just $25\%$ of its width drops IoU from $1.0$ to $0.3913$ (below the standard $0.50$ positive threshold), while log-normalized targets keep regression values neatly bounded near $[-1, 1]$.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;object-detection-localization-and-recognition&quot;&gt;Object Detection: Localization and Recognition&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Detected-with-YOLO--Schreibtisch-mit-Objekten.jpg/800px-Detected-with-YOLO--Schreibtisch-mit-Objekten.jpg&quot; alt=&quot;Object Detection Example&quot; /&gt;
&lt;em&gt;Hình ảnh: Object Detection với YOLO - phát hiện và định vị nhiều vật thể. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Object detection extends image classification from answering “what objects are in this image?” to “what objects are present and where are they located?” This seemingly small extension from classification to detection actually requires solving multiple interconnected problems simultaneously: proposing regions that might contain objects (region proposal), classifying what’s in each region (recognition), refining the boundaries of detections (localization), and handling multiple objects of different classes at different scales (multi-scale, multi-class detection). The complexity of coordinating these components while maintaining real-time performance has made object detection one of the most challenging and actively researched areas in computer vision.&lt;/p&gt;

&lt;p&gt;The evolution of object detection methods reveals a fascinating progression from traditional computer vision to modern deep learning approaches. Classical methods used hand-crafted features (SIFT, HOG) with sliding windows exhaustively searching every possible location and scale, then applying classifiers like SVMs. This was computationally expensive (evaluating millions of windows per image) and limited by feature quality. The deep learning revolution transformed object detection through learned features and end-to-end trainable systems, enabling dramatic improvements in both accuracy and speed.&lt;/p&gt;

&lt;p&gt;Modern object detection has branched into two major paradigms. Two-stage detectors like R-CNN, Fast R-CNN, and Faster R-CNN first propose regions likely to contain objects, then classify and refine these proposals. This explicit separation of region proposal and recognition enables high accuracy through focused computation on promising regions. Single-stage detectors like YOLO and SSD directly predict bounding boxes and class probabilities from regular grid positions, enabling real-time performance by avoiding the proposal stage at the cost of slightly lower accuracy on small objects.&lt;/p&gt;

&lt;p&gt;Understanding object detection deeply requires grasping several technical innovations that make modern systems work. Region Proposal Networks learn to generate object proposals rather than using hand-crafted rules, making the entire pipeline differentiable. Anchor boxes provide a way to handle objects of different aspect ratios and sizes through predefined box templates. Non-maximum suppression eliminates duplicate detections, addressing the fact that good detectors typically generate multiple overlapping boxes for each object. Feature pyramid networks enable detecting objects at multiple scales by building feature pyramies with rich semantics at all levels. These components, each solving a specific sub-problem, combine into systems that can detect and localize dozens of objects across multiple categories in milliseconds, enabling applications from autonomous driving to medical image analysis to augmented reality.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;Object detection requires formalizing what we’re predicting and how we measure success. An object detection is a tuple \((\text{class}, x, y, w, h)\) specifying the object’s category and bounding box (center coordinates \(x,y\) and dimensions \(w,h\)). For an image with \(N\) objects, the ground truth is a set of such tuples: \(\{(\text{class}_i, x_i, y_i, w_i, h_i)\}_{i=1}^N\). Our detector must predict this set, which is challenging because \(N\) varies across images.&lt;/p&gt;

&lt;h3 id=&quot;intersection-over-union-iou&quot;&gt;Intersection over Union (IoU)&lt;/h3&gt;

&lt;p&gt;To measure localization quality, we use Intersection over Union between predicted and ground-truth boxes:&lt;/p&gt;

\[\text{IoU}(\text{box}_{\text{pred}}, \text{box}_{\text{gt}}) = \frac{\text{Area}(\text{box}_{\text{pred}} \cap \text{box}_{\text{gt}})}{\text{Area}(\text{box}_{\text{pred}} \cup \text{box}_{\text{gt}})}\]

&lt;p&gt;IoU ranges from 0 (no overlap) to 1 (perfect overlap). Typically, we consider a detection correct if IoU \(\geq 0.5\) and the predicted class matches ground truth. This threshold balances between requiring precise localization and allowing reasonable bounding box variations.&lt;/p&gt;

&lt;h3 id=&quot;bounding-box-regression&quot;&gt;Bounding Box Regression&lt;/h3&gt;

&lt;p&gt;Rather than directly predicting box coordinates, modern detectors predict offsets from anchor boxes (predefined reference boxes). Given anchor box \((\hat{x}, \hat{y}, \hat{w}, \hat{h})\) and ground truth \((\bar{x}, \bar{y}, \bar{w}, \bar{h})\), we parameterize targets as:&lt;/p&gt;

\[t_x = \frac{\bar{x} - \hat{x}}{\hat{w}}, \quad t_y = \frac{\bar{y} - \hat{y}}{\hat{h}}\]

\[t_w = \log\frac{\bar{w}}{\hat{w}}, \quad t_h = \log\frac{\bar{h}}{\hat{h}}\]

&lt;p&gt;The network predicts \((t_x, t_y, t_w, t_h)\), and we decode to absolute coordinates:&lt;/p&gt;

\[x = \hat{x} + \hat{w} \cdot t_x, \quad y = \hat{y} + \hat{h} \cdot t_y\]

\[w = \hat{w} \cdot \exp(t_w), \quad h = \hat{h} \cdot \exp(t_h)\]

&lt;p&gt;This parameterization is more learnable than direct coordinate prediction because offsets are typically small numbers with similar scales, while absolute coordinates span the entire image with very different scales for small versus large objects.&lt;/p&gt;

&lt;h3 id=&quot;multi-task-loss&quot;&gt;Multi-Task Loss&lt;/h3&gt;

&lt;p&gt;Object detectors optimize combined losses for classification and localization:&lt;/p&gt;

\[\mathcal{L} = \mathcal{L}_{\text{cls}} + \lambda \mathcal{L}_{\text{box}}\]

&lt;p&gt;where \(\mathcal{L}_{\text{cls}}\) is classification loss (cross-entropy) and \(\mathcal{L}_{\text{box}}\) is bounding box regression loss (smooth L1 or IoU loss). The weight \(\lambda\) balances these objectives—too high and the detector focuses on precise localization at the expense of correct classification; too low and classifications are accurate but boxes are poorly localized.&lt;/p&gt;

&lt;p&gt;For Faster R-CNN, the classification loss uses cross-entropy over classes plus background:&lt;/p&gt;

\[\mathcal{L}_{\text{cls}} = -\log p_{\text{class}}\]

&lt;p&gt;where \(\text{class}\) is the ground-truth class (or background if IoU &amp;lt; 0.5 with all ground-truth boxes).&lt;/p&gt;

&lt;p&gt;The box loss is smooth L1:&lt;/p&gt;

\[\mathcal{L}_{\text{box}} = \sum_{i \in \{x,y,w,h\}} \text{smooth}_{L1}(t_i - \hat{t}_i)\]

\[\text{smooth}_{L1}(x) = \begin{cases} 0.5x^2 &amp;amp; \text{if } |x| &amp;lt; 1 \\ |x| - 0.5 &amp;amp; \text{otherwise} \end{cases}\]

&lt;p&gt;Smooth L1 is less sensitive to outliers than L2 (quadratic becomes linear for large errors) while being differentiable everywhere (unlike pure L1).&lt;/p&gt;

&lt;h3 id=&quot;region-proposal-networks-rpn&quot;&gt;Region Proposal Networks (RPN)&lt;/h3&gt;

&lt;p&gt;Faster R-CNN introduced RPN, a fully convolutional network that predicts object proposals. At each position in the feature map, RPN predicts:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Objectness scores: \(k\) anchors × 2 values (object vs background)&lt;/li&gt;
  &lt;li&gt;Box refinements: \(k\) anchors × 4 coordinates&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For a \(H \times W\) feature map with \(k=9\) anchors per position, RPN outputs:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Objectness: \(H \times W \times 9 \times 2\) scores&lt;/li&gt;
  &lt;li&gt;Box deltas: \(H \times W \times 9 \times 4\) values&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Total: \(HW \times 9\) proposals. Non-maximum suppression filters these to top \(\sim\)2000 based on objectness scores, which then go to the detection head.&lt;/p&gt;

&lt;p&gt;The RPN loss combines classification (objectness) and regression:&lt;/p&gt;

\[\mathcal{L}_{\text{RPN}} = \frac{1}{N_{\text{cls}}}\sum_i \mathcal{L}_{\text{cls}}(p_i, p_i^*) + \frac{\lambda}{N_{\text{box}}}\sum_i p_i^* \mathcal{L}_{\text{box}}(t_i, t_i^*)\]

&lt;p&gt;where \(p_i^* = 1\) if anchor \(i\) overlaps ground-truth with IoU &amp;gt; 0.7 (positive), \(p_i^* = 0\) if IoU &amp;lt; 0.3 (negative), and ignored if in between (to handle ambiguous cases).&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Imagine you’re trying to find and identify all people in a crowded photograph. Your strategy might be:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Quick scan&lt;/strong&gt; for regions likely to contain people (look for head shapes, body outlines)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Closer examination&lt;/strong&gt; of promising regions (is this actually a person or a statue? Which person is it?)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Refinement&lt;/strong&gt; of boundaries (exactly where does this person’s bounding box start/end?)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This three-stage process mirrors two-stage object detection. The Region Proposal Network does the quick scan, proposing ~2000 regions that might contain objects (people, cars, dogs, anything). The detection head examines each proposal, classifying what’s there and refining the bounding box. Non-maximum suppression eliminates duplicates (multiple overlapping boxes for the same person).&lt;/p&gt;

&lt;p&gt;Consider detecting cars in a street scene. The image might contain:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;3 cars at different distances (different sizes)&lt;/li&gt;
  &lt;li&gt;2 pedestrians&lt;/li&gt;
  &lt;li&gt;1 traffic sign&lt;/li&gt;
  &lt;li&gt;Complex background (buildings, trees)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A single-stage detector like YOLO divides the image into a grid (say 13×13). Each grid cell predicts:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Multiple bounding boxes (say 3, with different aspect ratios: tall, wide, square)&lt;/li&gt;
  &lt;li&gt;Class probabilities for each box&lt;/li&gt;
  &lt;li&gt;Confidence scores (is there an object here?)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For a grid cell at position (5, 8) near a car, it might predict:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Box 1: class=car, confidence=0.95, coordinates offset from cell center&lt;/li&gt;
  &lt;li&gt;Box 2: class=background, confidence=0.05&lt;/li&gt;
  &lt;li&gt;Box 3: class=background, confidence=0.02&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After processing all 13×13 cells, we have 13×13×3 = 507 predictions. Most are background (confidence near 0). NMS keeps only high-confidence, non-overlapping boxes:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Car 1: confidence=0.95, box=[120, 200, 60, 40]&lt;/li&gt;
  &lt;li&gt;Car 2: confidence=0.89, box=[300, 180, 80, 50]&lt;/li&gt;
  &lt;li&gt;Car 3: confidence=0.76, box=[450, 220, 40, 25] (far car, smaller)&lt;/li&gt;
  &lt;li&gt;Person 1: confidence=0.92, box=[200, 150, 30, 80]&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The detector has identified all objects, classified them, and localized them with bounding boxes—exactly what object detection requires.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=svn9-xV7wjk&quot;&gt;How YOLO Object Detection Works&lt;/a&gt; — DeepBean, English. One forward pass predicts boxes, which is the theory’s main design.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 11&lt;/td&gt;
          &lt;td&gt;Detection and Segmentation](https://www.youtube.com/watch?v=nDPWywWRIRo) — Stanford University School of Engineering, English. IoU and the assignment of predictions to ground truth, the math the short video skips.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. The convolutional features both videos assume.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>17 Computer Vision Applications</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter17/17_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter17/17_00_Introduction</id>
   <content type="html">&lt;p&gt;Knowing that a photograph contains a “pedestrian” is useless to a self-driving car unless it also knows &lt;em&gt;where&lt;/em&gt; the pedestrian is to the nearest pixel, &lt;em&gt;how many&lt;/em&gt; there are, and &lt;em&gt;which&lt;/em&gt; silhouette belongs to whom. Computer vision applications ascend a clear hierarchy of spatial granularity—from whole-image classification, to bounding-box object detection, to pixel-wise semantic and instance segmentation—each requiring specialized architectural heads and geometric loss functions.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-spatial-hierarchy-of-computer-vision-tasks&quot;&gt;Key ideas: The Spatial Hierarchy of Computer Vision Tasks&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Spatial Localization &amp;amp; Object Detection&lt;/strong&gt;: Combines class prediction with continuous coordinate regression $(x, y, w, h)$ across variable numbers of objects using one-stage (YOLO) or two-stage (Faster R-CNN) pipelines.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Dense Pixel Prediction (Semantic Segmentation)&lt;/strong&gt;: Preserves fine spatial resolution via encoder–decoder skip connections (U-Net) or dilated/atrous convolutions (DeepLab) to assign a class label to every pixel.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Instance-Level Separation (Mask R-CNN &amp;amp; Panoptic)&lt;/strong&gt;: Disentangles overlapping objects of the &lt;em&gt;same&lt;/em&gt; class by pairing box proposals with per-instance binary mask heads and RoIAlign.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Multi-Scale Feature Pyramids (FPN)&lt;/strong&gt;: Fuses high-resolution shallow maps (for tiny distant objects) with semantically rich deep maps (for large objects) so detectors work seamlessly across scales.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-pixel-iou-miou-for-a-2-times-2-semantic-segmentation-mask&quot;&gt;Worked example: Computing Pixel IoU (mIoU) for a $2 \times 2$ Semantic Segmentation Mask&lt;/h3&gt;

&lt;p&gt;Suppose a 2-class segmentation model (Class 0: background, Class 1: road) predicts mask $\hat{Y} = \begin{bmatrix}1 &amp;amp; 1\ 0 &amp;amp; 1\end{bmatrix}$ against ground truth $Y = \begin{bmatrix}1 &amp;amp; 0\ 0 &amp;amp; 1\end{bmatrix}$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Class 1 (road) IoU&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;True Positives (both 1): 2 pixels (top-left, bottom-right).&lt;/li&gt;
      &lt;li&gt;Union (either 1): 3 pixels (top-left, top-right, bottom-right).
\(\text{IoU}_1 = \frac{2}{3} \approx 0.6667.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Class 0 (background) IoU&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;True Positives (both 0): 1 pixel (bottom-left).&lt;/li&gt;
      &lt;li&gt;Union (either 0): 2 pixels (top-right, bottom-left).
\(\text{IoU}_0 = \frac{1}{2} = 0.5000.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mean IoU (mIoU) vs. Pixel Accuracy&lt;/strong&gt;:
\(\text{Pixel Accuracy} = \frac{3}{4} = 75.0\%, \qquad \text{mIoU} = \frac{0.6667 + 0.5000}{2} = 58.33\%.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Pixel accuracy ($75\%$) flatters imbalanced masks, whereas mIoU ($58.3\%$) strictly penalizes both false positives and false negatives on every class equally.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This chapter applies deep learning to practical computer vision tasks: image classification, object detection (YOLO, Faster R-CNN), semantic segmentation (U-Net, DeepLab), instance segmentation (Mask R-CNN), pose estimation, and image generation. We cover architectures, datasets, metrics, and implementation details for real-world applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After classic detectors, see &lt;strong&gt;17-99 Modern Applications and Updates&lt;/strong&gt; for SAM/SAM 2, RT-DETR, and open-vocabulary Grounding DINO.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 11&lt;/td&gt;
          &lt;td&gt;Detection and Segmentation](https://www.youtube.com/watch?v=nDPWywWRIRo) — Stanford University School of Engineering, English. Detection and segmentation are this chapter, in the CS231n lecture.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=svn9-xV7wjk&quot;&gt;How YOLO Object Detection Works&lt;/a&gt; — DeepBean, English. YOLO, the one-shot detector the lessons then specialize.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, English. The conv-net backbone those detectors sit on.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>16-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter16/16_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter16/16_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;If SimCLR proved self-supervised vision was possible, the 2023–2026 wave—DINOv2, SigLIP, and I-JEPA—made it the default vision backbone of modern AI. Today you rarely train a vision encoder from scratch: you drop in a frozen DINOv2 ViT for dense geometry (depth, correspondence, segmentation) or a SigLIP encoder for vision-language alignment, and build directly on top of representations learned without a single ImageNet label.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-frontier-self-supervised-learning-20222026&quot;&gt;Key ideas: Frontier Self-Supervised Learning (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Self-Distillation Without Negatives (DINOv2)&lt;/strong&gt;: Trains a student ViT to match an exponential-moving-average (EMA) teacher across global and local crops plus masked patches (iBOT), yielding emergent object-part segmentation with zero labels.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Pairwise Sigmoid Contrastive Alignment (SigLIP)&lt;/strong&gt;: Replaces CLIP’s global batch softmax with independent pairwise binary sigmoid losses, decoupling performance from massive synchronized batch sizes across GPUs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Joint-Embedding Predictive Architectures (I-JEPA / V-JEPA)&lt;/strong&gt;: Predicts masked target &lt;em&gt;embeddings&lt;/em&gt; rather than raw pixels, avoiding wasted capacity on unpredictable fine-grained noise like waving leaves.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Frozen Universal Backbones&lt;/strong&gt;: Uses curated, deduplicated self-supervised pretraining so a single frozen backbone powers depth estimation, robotics, and multimodal LLMs simultaneously.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-clip-softmax-vs-siglip-pairwise-sigmoid-loss-on-a-2-times-2-image-text-batch&quot;&gt;Worked example: CLIP Softmax vs. SigLIP Pairwise Sigmoid Loss on a $2 \times 2$ Image-Text Batch&lt;/h3&gt;

&lt;p&gt;Suppose we have 2 image-text pairs with cosine similarity matrix $S = \begin{bmatrix}0.8 &amp;amp; 0.2\ 0.1 &amp;amp; 0.7\end{bmatrix}$, temperature scale $t = 10$ (so $tS = \begin{bmatrix}8 &amp;amp; 2\ 1 &amp;amp; 7\end{bmatrix}$), and SigLIP learnable bias $b = -5$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;SigLIP pairwise logits $z_{ij} = t S_{ij} + b$&lt;/strong&gt;:
\(Z = \begin{bmatrix}3 &amp;amp; -3\\ -4 &amp;amp; 2\end{bmatrix}, \qquad \text{labels } Y = \begin{bmatrix}+1 &amp;amp; -1\\ -1 &amp;amp; +1\end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SigLIP binary logistic loss $\ell_{ij} = \ln(1 + e^{-y_{ij} z_{ij}})$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Positive $(1,1)$: $\ln(1 + e^{-3}) = \ln(1.0498) = 0.0486$.&lt;/li&gt;
      &lt;li&gt;Negative $(1,2)$: $\ln(1 + e^{-3}) = 0.0486$.&lt;/li&gt;
      &lt;li&gt;Negative $(2,1)$: $\ln(1 + e^{-4}) = \ln(1.0183) = 0.0181$.&lt;/li&gt;
      &lt;li&gt;Positive $(2,2)$: $\ln(1 + e^{-2}) = \ln(1.1353) = 0.1269$.&lt;/li&gt;
      &lt;li&gt;Mean loss per pair: $\frac{0.0486 + 0.0486 + 0.0181 + 0.1269}{4} = 0.0606$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Every entry $(i, j)$ in SigLIP computes its own independent sigmoid loss without an all-reduce softmax denominator across GPUs—enabling clean scaling from small batches up to 32k+ pairs.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-self-supervised-learning-after-simclr--dinov2-siglip-jepa&quot;&gt;Optional: self-supervised learning after SimCLR — DINOv2, SigLIP, JEPA&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace contrastive / MLM theory or the SimCLR sketch already in the chapter. It updates the &lt;strong&gt;vision and multimodal&lt;/strong&gt; SSL methods that became defaults after 2022.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The chapter already covers SimCLR, CLIP, and MAE. The 2023–2025 production stack moved to &lt;strong&gt;stronger teachers&lt;/strong&gt;, &lt;strong&gt;sigmoid language–image losses&lt;/strong&gt;, and &lt;strong&gt;predict-in-latent-space&lt;/strong&gt; (JEPA) objectives.&lt;/p&gt;

&lt;h2 id=&quot;1-dinov2-a-frozen-backbone-that-just-works&quot;&gt;1. DINOv2: a frozen backbone that just works&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.07193&quot;&gt;Oquab et al., 2023&lt;/a&gt; combine a DINO/iBOT-style student–teacher with a huge curated data pipeline. The released ViT-g features transfer to retrieval, depth, and segmentation &lt;strong&gt;without&lt;/strong&gt; task-specific fine-tune in many demos. That is SSL as a &lt;strong&gt;foundation encoder&lt;/strong&gt;, not a pretext homework.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;siglip--siglip-2&quot;&gt;SigLIP / SigLIP 2&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.15343&quot;&gt;Zhai et al., 2023&lt;/a&gt; replace CLIP’s softmax (which needs a large batch of negatives) with a &lt;strong&gt;sigmoid&lt;/strong&gt; pairwise loss&lt;/p&gt;

\[\mathcal{L} = -\frac{1}{B}\sum_{i,j}\log\sigma\big(y_{ij}\, t\, x_i^\top y_j\big),\]

&lt;p&gt;where \(y_{ij}=\pm 1\) marks matched pairs. Open-VLM stacks (PaliGemma, many 2024–2025 VLMs) start from SigLIP vision towers.&lt;/p&gt;

&lt;h3 id=&quot;i-jepa-and-predict-in-representation&quot;&gt;I-JEPA and predict-in-representation&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2301.08243&quot;&gt;Assran et al., 2023&lt;/a&gt; (I-JEPA) predict masked patch &lt;strong&gt;embeddings&lt;/strong&gt;, not pixels (unlike MAE in Chapter 12’s optional note). &lt;a href=&quot;https://openreview.net/forum?id=BZ5a1r-kVsf&quot;&gt;LeCun’s JEPA&lt;/a&gt; line is the research bet that SSL should model latent dynamics, not decode RGB.&lt;/p&gt;

&lt;h3 id=&quot;what-stayed&quot;&gt;What stayed&lt;/h3&gt;

&lt;p&gt;Masked language modeling and CLIP-style pairing are still the NLP/multimodal workhorses. SimCLR remains the right first contrastive derivation.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/dinov2&quot;&gt;facebookresearch/dinov2&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google-research/big_vision&quot;&gt;google-research/big_vision&lt;/a&gt; / OpenCLIP SigLIP weights on the Hub.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/jepa&quot;&gt;facebookresearch/jepa&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.07193&quot;&gt;DINOv2 (Oquab et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.15343&quot;&gt;Sigmoid Loss for Language Image Pre-Training — SigLIP (Zhai et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2301.08243&quot;&gt;Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture — I-JEPA (Assran et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Keep the NT-Xent derivation and the BERT MLM formula. This lesson only names the &lt;strong&gt;2023–2025 checkpoints&lt;/strong&gt; (DINOv2, SigLIP, JEPA) you will load instead of training SimCLR from scratch.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=csEgtSh7jV4&quot;&gt;DINOv2 from Meta AI - Finally a Foundational Model in Computer Vision?&lt;/a&gt; — AI Papers Academy, English. DINOv2 is the frozen vision backbone this note says you can use without fine-tuning everything.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=h3ij3F3cPIk&quot;&gt;DINO: Emerging Properties in Self-Supervised Vision Transformers (Facebook AI Research Explained)&lt;/a&gt; — Yannic Kilcher, English. DINO, the predecessor the note’s method extends.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Contrastive Learning with SimCLR&lt;/td&gt;
          &lt;td&gt;Deep Learning Animated](https://www.youtube.com/watch?v=UqJauYELn6c) — Deepia, English. The contrastive objective those self-supervised vision models grew out of.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>16-01 Self-Supervised Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter16/16_01_Self_Supervised_Learning/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter16/16_01_Self_Supervised_Learning</id>
   <content type="html">&lt;p&gt;In 2020, SimCLR startled the computer vision community by showing that a simple ResNet trained with &lt;em&gt;zero&lt;/em&gt; class labels—just matching two random crops and color jitters of the same photo—could nearly match fully supervised ImageNet accuracy on a linear probe. Beneath that apparent simplicity lies a rich mathematical interplay between mutual information lower bounds, hyperspherical alignment and uniformity, and why throwing away the projection head after pretraining boosts downstream accuracy by over 10%.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mathematical--architectural-mechanics-of-ssl&quot;&gt;Key ideas: Mathematical &amp;amp; Architectural Mechanics of SSL&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Mutual Information &amp;amp; InfoNCE Bounds&lt;/strong&gt;: Proves that minimizing InfoNCE maximizes a lower bound $I(X; Y) \ge \log(N) - \mathcal{L}_{\text{InfoNCE}}$, explaining why larger batch sizes $N$ tighten the bound.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Alignment &amp;amp; Uniformity on the Hypersphere&lt;/strong&gt;: Decomposes contrastive learning into two geometric forces: &lt;em&gt;alignment&lt;/em&gt; (positive views map to nearby unit vectors) and &lt;em&gt;uniformity&lt;/em&gt; (all embeddings spread evenly across $\mathbb{S}^{d-1}$).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Role of the Nonlinear Projection Head $g(\cdot)$&lt;/strong&gt;: Absorbs augmentation-specific invariance (like color distortion) inside $z = g(h)$, keeping the upstream representation $h = f(x)$ rich in color and pose information for downstream tasks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Masked Modeling vs. Joint-Embedding Architectures&lt;/strong&gt;: Contrasts pixel/token reconstruction (BERT, MAE) with representation-space prediction (BYOL, DINO, SimCLR), clarifying their inductive biases.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-how-temperature-tau-reweights-hard-vs-easy-negatives&quot;&gt;Worked example: How Temperature $\tau$ Reweights Hard vs. Easy Negatives&lt;/h3&gt;

&lt;p&gt;Using the cosine similarities $s_+ = 0.80$, $s_{\text{hard}} = 0.60$, $s_{\text{easy}} = 0.00$, compare the softmax negative weights $w_k = \frac{e^{s_k/\tau}}{\sum e^{s_m/\tau}}$ at $\tau = 0.5$ versus $\tau = 0.1$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;At warm temperature $\tau = 0.5$&lt;/strong&gt; (logits: $1.6, 1.2, 0.0$):
\(e^{1.6} = 4.953, \quad e^{1.2} = 3.320, \quad e^{0.0} = 1.000 \implies Z = 9.273.\)
    &lt;ul&gt;
      &lt;li&gt;Hard-negative weight: $w_{\text{hard}} = 3.320 / 9.273 = 35.8\%$.&lt;/li&gt;
      &lt;li&gt;Easy-negative weight: $w_{\text{easy}} = 1.000 / 9.273 = 10.8\%$ (ratio hard/easy $= 3.3\times$).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;At sharp temperature $\tau = 0.1$&lt;/strong&gt; (logits: $8.0, 6.0, 0.0$):
\(e^8 = 2981.0, \quad e^6 = 403.4, \quad e^0 = 1.0 \implies Z = 3385.4.\)
    &lt;ul&gt;
      &lt;li&gt;Hard-negative weight: $w_{\text{hard}} = 403.4 / 3385.4 = 11.9\%$.&lt;/li&gt;
      &lt;li&gt;Easy-negative weight: $w_{\text{easy}} = 1.0 / 3385.4 = 0.03\%$ (ratio hard/easy $= 403\times$!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Temperature $\tau$ acts as an automatic hard-negative miner—at $\tau = 0.1$, gradients concentrate $403\times$ more strongly on the confusing negative ($0.60$) than on the already-separated one ($0.00$).&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;self-supervised-learning-learning-from-data-itself&quot;&gt;Self-Supervised Learning: Learning from Data Itself&lt;/h1&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Self-supervised learning represents a paradigm shift in how we leverage unlabeled data, creating supervision signals automatically from the data itself rather than requiring expensive human annotations. The key insight is that data contains inherent structure and relationships that can serve as learning signals: images have spatial structure allowing us to predict one part from others, text has sequential structure enabling prediction of masked words from context, videos have temporal coherence making frame ordering predictable. By formulating prediction tasks that exploit these structures, we can train neural networks on massive unlabeled datasets, learning representations that transfer effectively to downstream supervised tasks.&lt;/p&gt;

&lt;p&gt;The distinction between self-supervised and unsupervised learning is subtle but important. Traditional unsupervised learning (clustering, PCA) discovers structure without using it for prediction. Self-supervised learning formulates supervised prediction tasks using automatically generated labels from data structure, essentially converting unsupervised data into supervised learning problems through clever task design. Masked language modeling in BERT—predicting masked words from context—is supervised learning where labels (the original words) come from the data itself rather than human annotators.&lt;/p&gt;

&lt;p&gt;Modern self-supervised learning has achieved remarkable success, particularly in NLP where pre-training on massive text through self-supervised objectives (masked language modeling, next sentence prediction) followed by fine-tuning on supervised tasks has become standard. BERT, GPT, and similar models learn rich language understanding from unlabeled text that transfers to diverse tasks. In computer vision, contrastive learning methods like SimCLR and MoCo learn visual representations by distinguishing augmented versions of the same image from different images, achieving representations competitive with supervised pre-training.&lt;/p&gt;

&lt;p&gt;Understanding self-supervised learning deeply requires appreciating the pretext tasks—the automatically supervised objectives used during pre-training—and what representations they encourage. Good pretext tasks should be: (1) solvable from data alone without labels, (2) require understanding semantic structure to solve effectively, (3) produce representations useful for downstream tasks. The art is designing tasks where solving them necessitates learning general useful features rather than exploiting data shortcuts.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;h3 id=&quot;contrastive-learning&quot;&gt;Contrastive Learning&lt;/h3&gt;

&lt;p&gt;Contrastive methods learn by distinguishing similar (positive) pairs from dissimilar (negative) pairs. Given anchor \(\mathbf{x}\), positive \(\mathbf{x}^+\) (augmented version of same image), and negatives \(\{\mathbf{x}_i^-\}\) (different images):&lt;/p&gt;

\[\mathcal{L}_{\text{contrastive}} = -\log \frac{\exp(\text{sim}(f(\mathbf{x}), f(\mathbf{x}^+))/\tau)}{\exp(\text{sim}(f(\mathbf{x}), f(\mathbf{x}^+))/\tau) + \sum_i \exp(\text{sim}(f(\mathbf{x}), f(\mathbf{x}_i^-))/\tau)}\]

&lt;p&gt;where \(f\) is encoder network, \(\text{sim}\) is similarity (typically cosine), \(\tau\) is temperature. This NT-Xent (normalized temperature-scaled cross-entropy) loss encourages representations where augmentations of same image are close while different images are far.&lt;/p&gt;

&lt;h3 id=&quot;masked-prediction&quot;&gt;Masked Prediction&lt;/h3&gt;

&lt;p&gt;BERT masks 15% of tokens and predicts them from context:&lt;/p&gt;

\[\mathcal{L}_{\text{MLM}} = -\mathbb{E}_{\mathbf{x}}\left[\sum_{i \in \mathcal{M}} \log p(x_i | \mathbf{x}_{\backslash \mathcal{M}})\right]\]

&lt;p&gt;where \(\mathcal{M}\) is set of masked positions. The model must use bidirectional context to predict masked words, learning deep language understanding.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Consider learning visual representations from unlabeled images. Take a photo of a cat. Create two augmented versions: one with random cropping and color jittering, another with different cropping and rotation. These are positive pairs—different views of the same cat, should have similar representations.&lt;/p&gt;

&lt;p&gt;Sample photos of dogs, cars, trees as negatives. Contrastive learning pushes cat augmentations together in representation space while pushing cat apart from dogs/cars/trees. After training on millions of images, representations cluster by semantic content: all cats nearby, all dogs nearby, cats and dogs closer to each other (both animals) than to cars.&lt;/p&gt;

&lt;p&gt;These learned representations transfer to classification—even though we never used labels during pre-training, the encoder learned to extract features distinguishing objects, which directly helps supervised classification with limited labels.&lt;/p&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimCLR&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Simplified SimCLR for contrastive learning&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;base_encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;projection_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Encoder (e.g., ResNet)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;base_encoder&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Projection head
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Maps encoder output to space where contrastive loss is computed
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;projection&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;projection_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;projection&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normalize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# L2 normalize
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;nt_xent_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temperature&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    NT-Xent loss for contrastive learning
    
    z1, z2: (batch, dim) representations of augmented pairs
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Concatenate augmentations
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2*batch, dim)
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Compute similarity matrix
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;temperature&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2*batch, 2*batch)
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Mask out self-similarity
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Positive pairs: (i, i+batch) and (i+batch, i)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;pos_sim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)],&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# NT-Xent loss
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos_sim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sim_matrix&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Self-supervised learning enables learning from unlabeled data!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Self-supervised learning connects to transfer learning as pre-training strategy. Instead of ImageNet supervised pre-training, use self-supervised pre-training on unlabeled images, often learning representations that transfer even better.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1911.05722&quot;&gt;“Momentum Contrast for Unsupervised Visual Representation Learning” (2020)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Kaiming He, Haoqi Fan, Yuxin Wu, Saining Xie, Ross Girshick&lt;br /&gt;
MoCo maintained large dictionary of negative examples through momentum encoder, enabling effective contrastive learning. Achieved representations competitive with supervised pre-training.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2002.05709&quot;&gt;“A Simple Framework for Contrastive Learning of Visual Representations” (2020)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ting Chen, Simon Kornblith, Mohammad Norouzi, Geoffrey Hinton&lt;br /&gt;
SimCLR showed that simple contrastive learning with strong augmentations and large batches achieves excellent representations, outperforming many supervised pre-training approaches.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;“BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
BERT’s masked language modeling is self-supervised learning, creating supervision from text itself.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Self-supervised learning creates supervision automatically from data structure, enabling learning from massive unlabeled datasets through pretext tasks like masked prediction or contrastive learning. Contrastive methods learn by distinguishing augmented views of same example from different examples, learning invariances to augmentations while capturing semantic content. Masked prediction tasks like BERT’s MLM learn to predict missing parts from context, requiring deep understanding of data structure. Self-supervised pre-training often matches or exceeds supervised pre-training for transfer learning, demonstrating that task-agnostic learning from unlabeled data produces versatile representations.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Contrastive Learning with SimCLR&lt;/td&gt;
          &lt;td&gt;Deep Learning Animated](https://www.youtube.com/watch?v=UqJauYELn6c) — Deepia, English. The NT-Xent loss on two views of one image is the contrastive section.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=h3ij3F3cPIk&quot;&gt;DINO: Emerging Properties in Self-Supervised Vision Transformers (Facebook AI Research Explained)&lt;/a&gt; — Yannic Kilcher, English. DINO’s emerging segmentation is the paper the lesson cites for self-distillation.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is cross-entropy?&lt;/td&gt;
          &lt;td&gt;Compression is Intelligence Part 2](https://www.youtube.com/watch?v=GlYgs6v2YfU) — 3Blue1Brown, English. Cross-entropy on a masked target is the language pretext (BERT-style) the lesson writes next to NT-Xent.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>16 Self-Supervised Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter16/16_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter16/16_00_Introduction</id>
   <content type="html">&lt;p&gt;Humans do not need a million labeled flash cards to learn that a rotated coffee cup is still the same cup, or that the missing word in &lt;em&gt;“The cat sat on the ___”&lt;/em&gt; is probably &lt;em&gt;mat&lt;/em&gt;. Self-Supervised Learning (SSL) unlocks the vast ocean of unlabeled text, images, audio, and video by inventing &lt;strong&gt;pretext tasks&lt;/strong&gt; whose labels come for free from the data itself—turning raw structure into supervision signals powerful enough to rival and surpass supervised pretraining.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-foundations-of-self-supervised-learning&quot;&gt;Key ideas: Foundations of Self-Supervised Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Pretext Tasks &amp;amp; Invariance Design&lt;/strong&gt;: Crafts supervision directly from raw inputs (masked patches, next tokens, augmented views) so solving the pretext task forces the encoder to capture high-level semantics.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Contrastive Learning (InfoNCE)&lt;/strong&gt;: Pulls representations of two augmented views of the same image together while pushing all other images in the batch apart on the unit hypersphere.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Generative / Masked Prediction (MLM &amp;amp; MAE)&lt;/strong&gt;: Hides a fraction of input tokens or patches and trains the network to reconstruct them from context, scaling effortlessly without large negative-sample banks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Collapse Prevention Mechanisms&lt;/strong&gt;: Explains why naive positive-pair matching collapses to a constant vector $f(x) \equiv c$ and how negatives, stop-gradients, momentum encoders, and variance-covariance regularizers prevent it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-infonce-loss-on-one-positive-and-two-negatives&quot;&gt;Worked example: Computing InfoNCE Loss on One Positive and Two Negatives&lt;/h3&gt;

&lt;p&gt;Suppose an anchor embedding $z_i$, its positive augmented view $z_j$, and two negative images $z_{k_1}, z_{k_2}$ are L2-normalized with cosine similarities:
\(s_{ij} = 0.80, \qquad s_{i, k_1} = 0.20, \qquad s_{i, k_2} = -0.10, \qquad \text{temperature } \tau = 0.5.\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Scale similarities by $1/\tau = 2.0$&lt;/strong&gt;:
\(s_{ij}/\tau = 1.60, \qquad s_{i,k_1}/\tau = 0.40, \qquad s_{i,k_2}/\tau = -0.20.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exponentiate each scaled logit&lt;/strong&gt;:
\(e^{1.60} \approx 4.953, \qquad e^{0.40} \approx 1.492, \qquad e^{-0.20} \approx 0.819.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute InfoNCE probability and loss&lt;/strong&gt;:
\(p_{ij} = \frac{4.953}{4.953 + 1.492 + 0.819} = \frac{4.953}{7.264} \approx 0.6819.\)
\(\mathcal{L}_{\text{InfoNCE}} = -\ln(0.6819) \approx 0.3829\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: InfoNCE is literally cross-entropy classification over the batch, and lowering temperature $\tau$ sharpens the softmax so the model focuses its gradients on the &lt;em&gt;hardest&lt;/em&gt; negatives (those with highest $s_{ik}$).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Self-supervised learning trains models using automatically generated labels from the data itself, without manual annotation. This paradigm has revolutionized pre-training in NLP (masked language modeling) and computer vision (contrastive learning). This chapter covers contrastive learning, SimCLR, CLIP, MAE, and modern self-supervised approaches.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After SimCLR/CLIP/MAE, see &lt;strong&gt;16-99 Modern Applications and Updates&lt;/strong&gt; for DINOv2, SigLIP, and JEPA-style predictive SSL.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Contrastive Learning with SimCLR&lt;/td&gt;
          &lt;td&gt;Deep Learning Animated](https://www.youtube.com/watch?v=UqJauYELn6c) — Deepia, English. Contrastive learning builds a pretext task from augmentations, which is this chapter’s main idea.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=h3ij3F3cPIk&quot;&gt;DINO: Emerging Properties in Self-Supervised Vision Transformers (Facebook AI Research Explained)&lt;/a&gt; — Yannic Kilcher, English. DINO is the self-distillation pretext the chapter also needs, especially before the DINOv2 note.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, English. Next-token prediction is the language pretext the lesson sets beside the vision ones.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;When a foundation model has 70 billion parameters, classical full fine-tuning requires over a terabyte of GPU memory—putting adaptation out of reach for almost every team. Parameter-Efficient Fine-Tuning (PEFT) changed the economics of transfer learning overnight: by freezing the giant base weight matrix $W_0$ and learning a tiny low-rank update $\Delta W = B A$ (LoRA) on top of 4-bit quantized base weights (QLoRA), a single workstation GPU can specialize a frontier model while storing a 50 MB adapter instead of a 140 GB checkpoint.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-modern-transfer-learning-via-peft-20222026&quot;&gt;Key ideas: Modern Transfer Learning via PEFT (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Low-Rank Adaptation (LoRA)&lt;/strong&gt;: Parameterizes weight updates as $W = W_0 + \frac{\alpha}{r} B A$ with $B \in \mathbb{R}^{d_{\text{out}} \times r}$, $A \in \mathbb{R}^{r \times d_{\text{in}}}$ ($r \ll \min(d_{\text{in}}, d_{\text{out}})$), adding zero inference latency once merged into $W_0$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Quantized Transfer (QLoRA &amp;amp; NF4)&lt;/strong&gt;: Stores frozen $W_0$ in 4-bit NormalFloat with double quantization and dequantizes on-the-fly into BF16 during forward/backward passes, slashing memory by $\sim 4\times$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Multimodal &amp;amp; Multi-Tenant Adapters&lt;/strong&gt;: Enables serving dozens of domain-specific LoRA adapters dynamically on top of a single shared frozen base model in GPU memory.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Limits of Low-Rank Updates&lt;/strong&gt;: Clarifies when full fine-tuning or continual pretraining still beats LoRA (e.g., injecting massive new factual knowledge or learning an entirely new language/modality).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-lora-parameter-reduction--rank-2-matrix-update&quot;&gt;Worked example: LoRA Parameter Reduction &amp;amp; Rank-2 Matrix Update&lt;/h3&gt;

&lt;p&gt;Consider a Transformer projection matrix $W_0 \in \mathbb{R}^{4096 \times 4096}$ adapted with LoRA rank $r = 16$ and scaling $\alpha = 32$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Parameter count comparison&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Full matrix $W_0$: $4096 \times 4096 = 16{,}777{,}216$ parameters.&lt;/li&gt;
      &lt;li&gt;LoRA matrices $A \in \mathbb{R}^{16 \times 4096}$ and $B \in \mathbb{R}^{4096 \times 16}$: $2 \times 16 \times 4096 = 131{,}072$ parameters.&lt;/li&gt;
      &lt;li&gt;Reduction factor: $\frac{16{,}777{,}216}{131{,}072} = 128\times$ fewer trainable parameters ($0.78\%$).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Concrete $2 \times 2$ rank-1 LoRA forward pass&lt;/strong&gt; ($r = 1, \alpha = 2 \implies \alpha/r = 2$):
Let $W_0 = \begin{bmatrix}1 &amp;amp; 0\ 0 &amp;amp; 1\end{bmatrix}$, $B = \begin{bmatrix}0.5\ -0.5\end{bmatrix}$, $A = \begin{bmatrix}1.0 &amp;amp; 2.0\end{bmatrix}$, and input $x = \begin{bmatrix}2\ 1\end{bmatrix}$.
    &lt;ul&gt;
      &lt;li&gt;Base path: $W_0 x = [2,\; 1]^\top$.&lt;/li&gt;
      &lt;li&gt;LoRA path: $A x = 1(2) + 2(1) = 4$; $\; B(Ax) = [2,\; -2]^\top$; $\; \frac{\alpha}{r} B A x = 2[2,\; -2]^\top = [4,\; -4]^\top$.&lt;/li&gt;
      &lt;li&gt;Combined output: $y = [2, 1]^\top + [4, -4]^\top = [6,\; -3]^\top$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Because $B$ is initialized to $0$ and $A$ to Gaussian noise, $\Delta W = 0$ at step 0—preserving the pretrained model’s exact behavior at initialization while cutting trainable parameters by $128\times$.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-transfer-learning-as-peft--lora-qlora-and-adapters&quot;&gt;Optional: transfer learning as PEFT — LoRA, QLoRA, and adapters&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace feature-extraction vs full fine-tune theory. The core notes still start from ResNet/BERT heads; this lesson is the 2022–2026 default for &lt;strong&gt;billion-parameter&lt;/strong&gt; models.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Full fine-tuning updates every \(\theta\). Parameter-efficient fine-tuning (PEFT) freezes \(\theta\) and learns a small $\Delta$:&lt;/p&gt;

\[W&apos; = W + \frac{\alpha}{r} BA, \quad B\in\mathbb{R}^{d\times r},\; A\in\mathbb{R}^{r\times k},\; r\ll \min(d,k).\]

&lt;p&gt;That is &lt;a href=&quot;https://arxiv.org/abs/2106.09685&quot;&gt;LoRA (Hu et al., 2021/2022)&lt;/a&gt;. It is still &lt;em&gt;transfer learning&lt;/em&gt;: the pretrained features move, but only along a low-rank subspace.&lt;/p&gt;

&lt;h2 id=&quot;1-qlora-and-quantized-transfer&quot;&gt;1. QLoRA and quantized transfer&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.14314&quot;&gt;Dettmers et al., 2023&lt;/a&gt; keep the base weights in 4-bit (NF4) and train LoRA in 16-bit. A 65B model becomes fine-tunable on a single 48 GB GPU. &lt;a href=&quot;https://github.com/TimDettmers/bitsandbytes&quot;&gt;bitsandbytes&lt;/a&gt; plus &lt;a href=&quot;https://github.com/huggingface/peft&quot;&gt;Hugging Face PEFT&lt;/a&gt; made this the applied-DS default.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;instruction-and-domain-adapters&quot;&gt;Instruction and domain adapters&lt;/h3&gt;

&lt;p&gt;Instead of a new BERT for every client, teams ship &lt;strong&gt;one base + many LoRA adapters&lt;/strong&gt; (legal, medical, SQL). Serving stacks (vLLM, SGLang) can swap adapters per request.&lt;/p&gt;

&lt;h3 id=&quot;vision-and-multimodal-peft&quot;&gt;Vision and multimodal PEFT&lt;/h3&gt;

&lt;p&gt;LoRA on U-Net / DiT attention (DreamBooth-LoRA, SDXL LoRA) is the consumer “train my style on 10 photos” path. Same math as language LoRA; different tensors.&lt;/p&gt;

&lt;h3 id=&quot;when-not-to-lora&quot;&gt;When &lt;em&gt;not&lt;/em&gt; to LoRA&lt;/h3&gt;

&lt;p&gt;Tiny CNNs, from-scratch tabular nets, and cases where the whole representation must move (heavy domain shift with abundant labels) still want full fine-tune or a new head — the theory lesson’s feature-extractor vs fine-tune split.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/peft&quot;&gt;huggingface/peft&lt;/a&gt; — LoRA, AdaLoRA, IA3, prefix-tuning.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/TimDettmers/bitsandbytes&quot;&gt;bitsandbytes&lt;/a&gt; + &lt;a href=&quot;https://github.com/artidoro/qlora&quot;&gt;QLoRA&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/unslothai/unsloth&quot;&gt;unsloth&lt;/a&gt; — faster LoRA trainers used in 2024–2026 tutorials.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2106.09685&quot;&gt;LoRA (Hu et al., 2021)&lt;/a&gt; — low-rank adapters; ubiquitous after 2022.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.14314&quot;&gt;QLoRA (Dettmers et al., 2023)&lt;/a&gt; — 4-bit base + LoRA.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2104.08691&quot;&gt;The Power of Scale for Parameter-Efficient Prompt Tuning (Lester et al., 2021)&lt;/a&gt; — prompt tuning as the other PEFT pole.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Do the ResNet/BERT fine-tune homework first. This lesson only adds the &lt;strong&gt;low-rank / quantized&lt;/strong&gt; transfer recipe that replaced “unfreeze the last three layers” for LLMs.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [QLoRA: Efficient Finetuning of Quantized LLMs&lt;/td&gt;
          &lt;td&gt;Tim Dettmers](https://www.youtube.com/watch?v=fQirE9N5q_Y) — AMLD Intelligence Summit, English. QLoRA is quantized low-rank fine-tuning, the transfer method this note adds. The talk is Tim Dettmers at AMLD.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How LLMs survive in low precision&lt;/td&gt;
          &lt;td&gt;Quantization Fundamentals](https://www.youtube.com/watch?v=qoQJq5UwV1c) — Julia Turc, English. The low-precision arithmetic QLoRA depends on.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, English. Ordinary fine-tuning, so the quantized variant is a change of how, not of why.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15-98 Interviews Practice (feature extraction and transfer)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;In senior ML engineering interviews, transfer learning questions rarely ask you to recite definitions—they drop you into a messy production scenario: &lt;em&gt;“Your linear probe hits 78% on satellite imagery, full fine-tuning overfits to 71%, and your batch size is 4. What do you do?”&lt;/em&gt; Practicing crisp, first-principles answers to these four diagnostic prompts trains you to reason about feature geometry, BatchNorm statistics, and domain shift under pressure.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-interview-reasoning-on-transfer--feature-extraction&quot;&gt;Key ideas: Interview Reasoning on Transfer &amp;amp; Feature Extraction&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Bias–Variance Trade-off in Adaptation&lt;/strong&gt;: Diagnoses when frozen features underfit (high bias under domain shift) versus when full fine-tuning overfits (high variance on scarce labels).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Layer Selection &amp;amp; Feature Extraction Mechanics&lt;/strong&gt;: Distinguishes penultimate pooled embeddings from intermediate spatial feature maps depending on whether the task needs semantic class identity or fine-grained localization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Domain Shift Diagnostics&lt;/strong&gt;: Separates covariate shift (input style/lighting changes), label shift (class priors change), and concept drift (label definitions change).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Failure Modes in Low-Data Regimes&lt;/strong&gt;: Anticipates BatchNorm instability on small batches, head-initialization gradient shock (fixed by LP-FT), and negative transfer.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-diagnosing-feature-distribution-drift-via-cosine-similarity&quot;&gt;Worked example: Diagnosing Feature-Distribution Drift via Cosine Similarity&lt;/h3&gt;

&lt;p&gt;Suppose a frozen ImageNet encoder maps daytime cat photos to average unit embedding $\bar{u}_S = [0.8,\, 0.6,\, 0.0]^\top$, and infrared thermal cat photos to $\bar{u}_T = [0.2,\, 0.4,\, 0.8944]^\top$ (verify: $0.2^2 + 0.4^2 + 0.8944^2 = 0.04 + 0.16 + 0.80 = 1.00$).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute cosine similarity between source and target centroids&lt;/strong&gt;:
\(\cos(\theta) = \bar{u}_S^\top \bar{u}_T = (0.8)(0.2) + (0.6)(0.4) + (0.0)(0.8944) = 0.16 + 0.24 = 0.40 \implies \theta \approx 66.4^\circ.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Interpret for an interview decision&lt;/strong&gt;:
A $66.4^\circ$ shift into an orthogonal subspace ($z_3 = 0.8944$) means a frozen linear probe trained on source RGB features will misalign severely. The disciplined engineering response is: &lt;strong&gt;unfreeze at least the top 1–2 residual stages (or add LoRA adapters) and recalibrate BatchNorm/LayerNorm statistics on target data&lt;/strong&gt; rather than relying solely on a frozen linear probe.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Quantifying representation alignment turns hand-wavy interview intuition into an actionable architectural diagnosis.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-interview-practice--feature-extraction-and-transfer&quot;&gt;Optional: interview practice — feature extraction and transfer&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace feature-extraction vs fine-tune theory. After those notes, use this drill, then open &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for solved items on CNN feature extraction. Architecture geometry stays in &lt;strong&gt;04-98&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Book themes for this chapter (study in the PDF, not here):&lt;/strong&gt; using a trained CNN as a feature extractor; frozen vs trainable trunks.&lt;/p&gt;

&lt;p&gt;Hub: &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;practice-prompts-original&quot;&gt;Practice prompts (original)&lt;/h2&gt;

&lt;h3 id=&quot;q1-linear-probe-vs-last-block-fine-tune&quot;&gt;Q1. Linear probe vs last-block fine-tune&lt;/h3&gt;

&lt;p&gt;You have 800 labeled medical images and a ResNet pretrained on ImageNet. Compare (a) freeze the trunk, train a linear head and (b) unfreeze the last residual stage plus the head. What risk does (b) add that (a) does not?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Number of trainable parameters vs how close the source and target statistics are.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; (a) is a linear probe: cheap, hard to destroy pretrained filters, often a strong baseline. (b) can adapt mid/high-level filters to lesions or textures ImageNet never saw, but 800 images can overwrite those filters (catastrophic fine-tuning). A practical compromise is a small learning rate on the trunk and a larger one on the head, or adapters (Chapter 15 optional modern note) — say that as an extension, not as the core answer.&lt;/p&gt;

&lt;h3 id=&quot;q2-when-frozen-features-are-the-wrong-tool&quot;&gt;Q2. When frozen features are the wrong tool&lt;/h3&gt;

&lt;p&gt;Give a concrete target domain where ImageNet activations are a weak representation even though both source and target are “images,” and name the mismatch.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Think sensors, viewpoint, or label granularity — not “the dataset is small.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Examples: grayscale histopathology at 40×, satellite bands beyond RGB, or extreme close-up industrial defects. The mismatch is &lt;em&gt;low-level statistics and semantics&lt;/em&gt;, not merely sample size. Fine-tuning more of the trunk, or pretraining in-domain (self-supervision, Chapter 16), is more honest than stacking a deeper MLP on frozen RGB-object features.&lt;/p&gt;

&lt;h3 id=&quot;q3-what-you-actually-extract&quot;&gt;Q3. What you actually extract&lt;/h3&gt;

&lt;p&gt;A teammate “extracts features” by taking the \(7\times7\times2048\) map of a ResNet-50 and flattening it to train an SVM. Give one reason to global-average-pool first, and one task where you would &lt;em&gt;keep&lt;/em&gt; the spatial map.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Invariance vs localization.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; GAP to \(2048\)-d yields a translation-tolerant descriptor and a sane SVM dimension. Detection, segmentation, or any task that must know &lt;em&gt;where&lt;/em&gt; the object is should keep the spatial tensor (or use a feature pyramid). “Feature extraction” is not one vector shape; it is a choice about which invariances you want.&lt;/p&gt;

&lt;h3 id=&quot;q4-domain-shift-in-one-picture&quot;&gt;Q4. Domain shift in one picture&lt;/h3&gt;

&lt;p&gt;Training images are studio product shots; production images are phone photos in warehouses. You fine-tune the head only and val accuracy looks great (val is also studio). What did you measure, and what experiment would you add before shipping?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; i.i.d. val vs the deployment distribution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; You measured in-domain head quality, not transfer. Add a warehouse-labeled slice (or at least a visually matched proxy) and report that number. Color / crop augmentation that mimics warehouse lighting is a cheap intermediate; it is not a substitute for a true target val set. Interviewers want this humility more than a magic architecture name.&lt;/p&gt;

&lt;h2 id=&quot;attribution&quot;&gt;Attribution&lt;/h2&gt;

&lt;p&gt;Kashani, S., and Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Download the PDF from arXiv for the full solved Q&amp;amp;A. This page is original course practice, not a reprint.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, English. Feature-extraction versus fine-tuning prompts.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qaDe0qQZ5AQ&quot;&gt;Pytorch Transfer Learning and Fine Tuning Tutorial&lt;/a&gt; — Aladdin Persson, English. Be able to say which parameters still receive gradients.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. Why the early filters are the ones worth keeping.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15-01 Transfer Learning Fundamentals</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_01_Transfer_Learning_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_01_Transfer_Learning_Fundamentals</id>
   <content type="html">&lt;p&gt;Transfer learning is the quiet superpower behind almost every real-world deep learning deployment: almost nobody trains a vision or language backbone from scratch when a strong pretrained checkpoint exists. Pairing the theory of domain shift with concrete PyTorch freezing and fine-tuning recipes gives you a reliable decision matrix for any dataset size and domain distance.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-transfer-learning-decision-matrix&quot;&gt;Key ideas: Transfer Learning Decision Matrix&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — The 2×2 Data-vs-Similarity Grid&lt;/strong&gt;: Maps target dataset size (small vs. large) and domain similarity (close vs. distant) directly to linear probing, partial unfreezing, or full fine-tuning.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Representation Depth &amp;amp; Generality&lt;/strong&gt;: Connects shallow universal features to deep task-specific features so you know &lt;em&gt;which&lt;/em&gt; layers to freeze.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Optimization Hygiene&lt;/strong&gt;: Uses LP-FT warm-up, differential learning rates, and weight decay to avoid catastrophic forgetting.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Empirical Validation&lt;/strong&gt;: Benchmarks feature extraction against full fine-tuning on identical data splits to measure true generalization gain.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-memory-savings-of-freezing-80-of-a-backbone&quot;&gt;Worked example: Memory Savings of Freezing 80% of a Backbone&lt;/h3&gt;

&lt;p&gt;Consider a $20\text{M}$-parameter model trained with Adam in FP32 ($4$ bytes/param for weights, $4$ for gradients, $8$ for Adam’s first and second moments $= 16$ bytes per trainable parameter).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Full Fine-Tuning optimizer + weight + grad memory&lt;/strong&gt;:
\(20\text{M} \times 16\text{ bytes} = 320\text{ MB}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Freezing 80% of parameters ($16\text{M}$ frozen, $4\text{M}$ trainable)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Frozen weights need only $4$ bytes/param (no gradients, no Adam states): $16\text{M} \times 4 = 64\text{ MB}$.&lt;/li&gt;
      &lt;li&gt;Trainable weights need $16$ bytes/param: $4\text{M} \times 16 = 64\text{ MB}$.&lt;/li&gt;
      &lt;li&gt;Total: $128\text{ MB}$ ($60\%$ memory reduction, plus faster backward passes since frozen layers skip weight-gradient computation!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Freezing lower layers is simultaneously a statistical regularizer &lt;em&gt;and&lt;/em&gt; a major GPU memory and compute accelerator.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Transfer learning:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Theory&lt;/strong&gt; — concepts, strategies, intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implementation&lt;/strong&gt; — feature extraction vs fine-tuning, papers, pitfalls&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, English. Feature extraction versus fine-tuning.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qaDe0qQZ5AQ&quot;&gt;Pytorch Transfer Learning and Fine Tuning Tutorial&lt;/a&gt; — Aladdin Persson, English. Both strategies in code.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. The early visual features those strategies reuse.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15-01-02 Transfer Learning Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_01_02_Transfer_Learning_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_01_02_Transfer_Learning_Implementation</id>
   <content type="html">&lt;p&gt;Most transfer-learning bugs in PyTorch are silent: your training loop runs cleanly, the loss drops, and yet test accuracy is 12% worse than expected. The culprits are almost always the same three details—forgetting to match ImageNet’s RGB normalization mean/std, leaving &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BatchNorm&lt;/code&gt; running statistics unfrozen when fine-tuning on tiny batches, or hitting pretrained weights with the same aggressive learning rate (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-3&lt;/code&gt;) used for a freshly initialized linear head.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-practical-pytorch-transfer-learning-pipeline&quot;&gt;Key ideas: Practical PyTorch Transfer Learning Pipeline&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Preprocessing &amp;amp; Normalization Parity&lt;/strong&gt;: Matches the exact input resolution, channel order, and per-channel &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(mean, std)&lt;/code&gt; used during pretraining so early convolutional filters see activations in their expected dynamic range.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Selective Parameter Freezing (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;requires_grad = False&lt;/code&gt;)&lt;/strong&gt;: Filters frozen parameters out of the optimizer (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;filter(lambda p: p.requires_grad, model.parameters())&lt;/code&gt;) to save optimizer memory and prevent accidental weight drift.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Two-Stage Linear-Probe-Then-Fine-Tune (LP-FT)&lt;/strong&gt;: Trains the randomly initialized head first while the backbone is frozen, then unfreezes upper blocks with discriminative learning rates (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-4&lt;/code&gt; backbone, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-3&lt;/code&gt; head) to prevent feature distortion.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — BatchNorm Mode Discipline&lt;/strong&gt;: Explains when to keep frozen backbone &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BatchNorm&lt;/code&gt; layers in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.eval()&lt;/code&gt; mode during feature extraction versus letting running stats adapt under severe domain shift.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-differential-learning-rate-updates-in-lp-ft&quot;&gt;Worked example: Computing Differential Learning-Rate Updates in LP-FT&lt;/h3&gt;

&lt;p&gt;Suppose during Stage 2 fine-tuning of a ResNet-18, we use AdamW/SGD with backbone learning rate $\eta_{\text{bb}} = 10^{-4}$ and head learning rate $\eta_{\text{head}} = 10^{-3}$. At step 1, a pretrained convolutional weight is $w_{\text{bb}} = 0.5000$ with gradient $g_{\text{bb}} = 2.0$, and a head weight is $w_{\text{head}} = 0.0500$ with gradient $g_{\text{head}} = 2.0$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Backbone weight update (gentle adaptation)&lt;/strong&gt;:
\(w_{\text{bb}}^{\text{new}} = 0.5000 - 10^{-4}(2.0) = 0.4998 \quad (\text{relative shift: } 0.04\%).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Head weight update (rapid task alignment)&lt;/strong&gt;:
\(w_{\text{head}}^{\text{new}} = 0.0500 - 10^{-3}(2.0) = 0.0480 \quad (\text{relative shift: } 4.0\%).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why ImageNet normalization matters&lt;/strong&gt;: For a pixel value $x = 0.80$ in the red channel ($\mu_R = 0.485, \sigma_R = 0.229$),
\(x_{\text{norm}} = \frac{0.80 - 0.485}{0.229} = +1.376,\)
whereas feeding raw $0.80$ shifts the entire activation distribution by over $0.5$ standard deviations before layer 1 even runs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Pairing exact input normalization with a $10\times$ smaller backbone learning rate preserves generalizable pretrained representations while letting the task head converge rapidly.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Complete transfer learning implementation:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.utils.data&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_split&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Transfer Learning: Fine-tuning Pre-trained ResNet for Custom Dataset&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Load pre-trained ResNet18 (smaller than ResNet50 for demonstration)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Loading Pre-trained Model&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# weights=&apos;IMAGENET1K_V1&apos; loads ImageNet pre-trained weights
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;resnet18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;IMAGENET1K_V1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Loaded ResNet18 pre-trained on ImageNet&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Original output layer: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (1000 classes for ImageNet)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Examine what pre-trained model has learned
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pre-trained features:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Layer 1 filters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (64, 3, 7, 7)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  These are edge/texture detectors learned from ImageNet&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 2. Adapt for new task
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Adapting for Custom Task (10 Classes)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Replace final fully-connected layer for our task
# Everything else keeps pre-trained weights
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Our custom task has 10 classes
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_features&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Get input size of fc layer
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Original FC input features: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Replacing final layer for &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; classes...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;New model output layer: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_pretrained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (10 classes for our custom task)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create dummy dataset (in practice, use your real data)
# We&apos;ll simulate with CIFAR-10 as our &quot;custom&quot; task
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;3. Preparing Custom Dataset&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;transform_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Compose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Resize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;224&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ResNet expects 224×224 (CIFAR is 32×32)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ToTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normalize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.485&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.456&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.406&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.229&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.224&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.225&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ImageNet stats
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simulate limited data scenario: use only 1000 training images
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;full_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CIFAR10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Take subset to simulate limited data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;limited_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;remaining&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;full_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;limited_size&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;random_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;full_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;limited_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;remaining&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CIFAR10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training with only &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;limited_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; images (simulating limited data)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Test set: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; images&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 3. Training Strategy: Feature Extraction vs Fine-Tuning
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;4. Strategy A: Feature Extraction (Freeze Pre-trained Layers)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create copy of model for feature extraction
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;resnet18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;IMAGENET1K_V1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Freeze all layers except final FC
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Unfreeze final layer
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;trainable_params_fe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Total parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trainable parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainable_params_fe&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainable_params_fe&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Only training the final classification layer!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Optimizer for feature extraction (only fc layer parameters)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer_fe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CrossEntropyLoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training feature extraction model (5 epochs)...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_fe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward (conv layers frozen, only fc trains)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_fe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Train Acc = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Evaluate
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_acc_fe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature Extraction Test Accuracy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_acc_fe&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 4. Strategy B: Fine-Tuning
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;5. Strategy B: Fine-Tuning (Update All Layers)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;resnet18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;IMAGENET1K_V1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# All parameters trainable
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainable_params_ft&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Trainable parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainable_params_ft&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (100%)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Use differential learning rates
# Lower LR for pre-trained layers, higher for new layer
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer_ft&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0002&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0005&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;},&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Highest for new layer
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Default for any params not specified
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Using layer-wise differential learning rates:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Early layers: 0.0001 (barely change)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Middle layers: 0.0002&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Deep layers: 0.0005&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  New FC layer: 0.001 (change most)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training fine-tuning model (5 epochs)...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_ft&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_ft&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_loss&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Train Acc = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Evaluate
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_acc_ft&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Fine-Tuning Test Accuracy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_acc_ft&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compare results
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Transfer Learning Results Comparison&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature Extraction: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_acc_fe&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% test accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Fine-Tuning:        &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_acc_ft&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% test accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Both dramatically outperform training from scratch (~60% on 1000 images)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Transfer learning enabled competitive performance with limited data!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Demonstrate feature visualization:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Analyzing Transferred Features&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Extract features for analysis
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;extract_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_name&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;layer4&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Extract features from a specific layer.
    
    This shows what representations the model uses for classification.
    Pre-trained features should be meaningful even for custom task.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;features_list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;labels_list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Register hook to capture layer outputs
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;features_hook&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;hook_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;features_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Get the layer
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;dict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;named_modules&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;handle&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;register_forward_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hook_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;features_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;labels_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;features_hook&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;handle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;remove&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Concatenate all batches
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Extract layer4 features (last conv layer before FC)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;extract_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model_finetune&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
    &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; 
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;layer4&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Extracted features from layer4 (last conv layer)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Feature shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1000, 512, 7, 7)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Global average pool to get 512-dim vectors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_pooled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;features_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1000, 512)
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;After global average pooling: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features_pooled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;These 512-dimensional features encode:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Low-level: edges, textures (from ImageNet)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Mid-level: object parts, shapes (from ImageNet)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - High-level: bird-specific patterns (adapted during fine-tuning)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;The pre-trained features provide strong starting point!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Transfer learning connects to multi-task learning, where we train a single model on multiple related tasks simultaneously rather than sequentially. Multi-task learning uses shared representations (early/middle layers) while maintaining task-specific heads (final layers), similar to transfer learning’s architecture but with joint training. The shared representation learns features useful across tasks, providing implicit regularization (a feature must help multiple tasks to be retained) that often improves generalization compared to single-task training. Understanding this connection helps appreciate that transfer learning and multi-task learning address similar problems—leveraging shared structure across related tasks—through different training procedures.&lt;/p&gt;

&lt;p&gt;The relationship to meta-learning (learning to learn) is more subtle but important. Meta-learning aims to learn an initialization or learning algorithm that enables fast adaptation to new tasks with minimal data. Model-Agnostic Meta-Learning (MAML), for instance, learns an initialization that’s a few gradient steps away from good performance on any task from a distribution. Transfer learning can be viewed as a simple form of meta-learning where the “meta-training” is pre-training on the source task and “adaptation” is fine-tuning on the target. More sophisticated meta-learning approaches extend this idea to learn better adaptations or to handle more diverse task distributions.&lt;/p&gt;

&lt;p&gt;Transfer learning’s success in NLP through pre-trained language models exemplifies domain-specific evolution of the paradigm. Word2Vec and GloVe provided pre-trained word embeddings, transferring lexical knowledge. ELMo provided pre-trained contextual representations. BERT revolutionized the field by pre-training entire Transformer models on massive text corpora through masked language modeling, then fine-tuning for specific tasks. GPT took this further with models so large that fine-tuning isn’t always necessary—few-shot learning through prompting can adapt the model without any parameter updates. This progression from transferring embeddings to transferring complete models to avoiding fine-tuning entirely shows how transfer learning evolved as models scaled.&lt;/p&gt;

&lt;p&gt;The connection to curriculum learning provides another perspective. Transfer learning can be viewed as a two-stage curriculum: first learn general features (easier task with abundant data), then learn task-specific features (harder task with limited data). This staged approach mirrors how humans learn—general education before specialization—and often works better than jumping directly to the hardest problem. Understanding this connection suggests we might use multi-stage transfer: pre-train on general data (ImageNet), intermediate training on domain-specific data (medical images broadly), then fine-tune on specific task (lung cancer detection). Such staged transfer has proven effective in specialized domains.&lt;/p&gt;

&lt;p&gt;Finally, transfer learning connects to the broader question of sample efficiency in machine learning. Deep learning’s data hunger—requiring millions of examples—limits applications where data is expensive (medical imaging, rare events) or impossible to collect at scale (private data, unique scenarios). Transfer learning dramatically improves sample efficiency by amortizing the cost of learning general features across many downstream tasks. Understanding transfer learning’s sample efficiency provides insights into what makes learning difficult (learning general features requires lots of data) versus easier (learning task-specific mappings given good features needs less data), informing when to expect transfer to help most dramatically.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1411.1792&quot;&gt;“How transferable are features in deep neural networks?” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Jason Yosinski, Jeff Clune, Yoshua Bengio, Hector Lipson&lt;br /&gt;
This paper systematically investigated transferability of neural network features across tasks, providing empirical evidence and theoretical understanding of when transfer works. The authors trained networks on ImageNet variants, freezing different numbers of layers when transferring to new tasks, measuring performance degradation versus full fine-tuning. Key findings: early layers learn general features that transfer almost universally; middle layers are more task-specific but still broadly useful; final layers are highly task-specific and benefit most from adaptation. The paper also showed that co-adapted features (features that work well together) can be disrupted by freezing some while training others, suggesting fine-tuning all layers often works better than freezing many. This work established the empirical foundations for transfer learning best practices and demonstrated that feature transferability isn’t universal but depends on layer depth and task similarity.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.cv-foundation.org/openaccess/content_cvpr_2014/papers/Oquab_Learning_and_Transferring_2014_CVPR_paper.pdf&quot;&gt;“Learning and Transferring Mid-Level Image Representations using Convolutional Neural Networks” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Maxime Oquab, Leon Bottou, Ivan Laptev, Josef Sivic&lt;br /&gt;
This paper demonstrated that CNN features pre-trained on ImageNet transfer effectively to diverse visual recognition tasks including object detection, scene classification, and fine-grained recognition. The authors showed that simply using pre-trained conv layers as feature extractors and training a classifier on these features achieved strong performance across tasks, outperforming hand-engineered features. The work established transfer learning as practical standard practice in computer vision, showing the features learned on one large dataset (ImageNet) generalize to many other vision tasks. The paper’s experimental methodology—systematic evaluation across multiple tasks with controlled comparisons—set standards for demonstrating transfer effectiveness and influenced the widespread adoption of pre-trained models in computer vision.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;“BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova&lt;br /&gt;
While primarily introducing BERT, this paper revolutionized transfer learning in NLP by showing that pre-training Transformers on massive text through masked language modeling, then fine-tuning on specific tasks, achieved state-of-the-art results across eleven diverse NLP tasks including question answering, natural language inference, and named entity recognition. BERT demonstrated the power of transfer learning at scale: a single pre-trained model could be adapted to vastly different tasks with minimal architectural changes (just adding simple task-specific heads). The pre-train-then-fine-tune paradigm became dominant in NLP, showing that transfer learning isn’t vision-specific but a general principle applicable across modalities. The paper’s impact extended beyond BERT itself to establishing large-scale unsupervised pre-training as a standard first step in NLP model development.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://ieeexplore.ieee.org/document/5288526&quot;&gt;“A Survey on Transfer Learning” (2010)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Sinno Jialin Pan, Qiang Yang&lt;br /&gt;
This comprehensive survey paper organized and taxonomized transfer learning approaches across machine learning, not just deep learning. Pan and Yang defined: inductive transfer (labeled target data), transductive transfer (no labeled target data), and unsupervised transfer. They analyzed when transfer works (source and target share marginal or conditional distributions) versus fails (large domain shift), providing theoretical frameworks for understanding transferability. While pre-dating the deep learning era’s dramatic transfer learning successes, the theoretical foundations remain relevant: understanding transfer as leveraging shared structure between source and target, analyzing domain shift quantitatively, and recognizing that negative transfer (where using source data hurts target performance) can occur when domains are too dissimilar. The survey connects deep transfer learning to broader machine learning traditions, providing theoretical context for why and when transfer is effective.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1811.08883&quot;&gt;“Rethinking ImageNet Pre-training” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Kaiming He, Ross Girshick, Piotr Dollár&lt;br /&gt;
This paper challenged the conventional wisdom that ImageNet pre-training is always beneficial, showing that for tasks with sufficient data (tens of thousands of images), training from scratch can match or exceed fine-tuning pre-trained models, given enough training time. The key insight was that pre-training’s advantage is primarily in faster convergence and better performance with limited data, not in reaching fundamentally better solutions. With abundant task-specific data and proper regularization, random initialization can work well, though requiring much longer training. The paper refined understanding of when transfer helps most: in low-data regimes (hundreds to thousands of examples), pre-training provides massive advantages; in high-data regimes (hundreds of thousands+), advantages diminish. This nuanced view helps practitioners make informed decisions about whether to use pre-trained models or train from scratch based on data availability and computational budget.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;The most common mistake is using pre-trained models without matching preprocessing to the pre-training protocol. If a model was pre-trained on ImageNet with specific normalization (mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] for RGB channels), fine-tuning or feature extraction must use identical normalization. Mismatched preprocessing causes the model to receive inputs from a different distribution than it was trained on, degrading performance dramatically. Always check the pre-training protocol (input size, normalization statistics, preprocessing steps) and replicate it exactly for transfer.&lt;/p&gt;

&lt;p&gt;Using too high a learning rate when fine-tuning destroys pre-trained features before they can adapt to the new task. The pre-trained weights represent useful features; large updates can push them far from this useful region into random territory. A good rule: use 10-100× smaller learning rate for fine-tuning than for training from scratch. If normal training uses lr=0.1, fine-tuning should use lr=0.001-0.01. Even better: use differential learning rates with earlier layers getting smaller rates (they’re more general, should change less) and later layers getting larger rates (more task-specific, should adapt more).&lt;/p&gt;

&lt;p&gt;Forgetting to set the model to eval mode when extracting features is a subtle bug that causes inconsistent results. If the model contains batch normalization or dropout layers and remains in train mode during feature extraction, these layers behave differently on different calls (batch norm uses batch statistics, dropout drops random units), causing the same input to produce different features. Always call &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; and use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.no_grad()&lt;/code&gt; when extracting features or making predictions.&lt;/p&gt;

&lt;p&gt;When fine-tuning NLP models like BERT, a common issue is catastrophic forgetting on short sequences. BERT was pre-trained on sequences of 512 tokens. Fine-tuning on a task with short sequences (tweets, SMS messages of 20-50 tokens) can degrade the model’s ability to handle long sequences. If you need to preserve this capability, include long-sequence examples during fine-tuning or use a mixture of source and target data (partial fine-tuning).&lt;/p&gt;

&lt;p&gt;A powerful trick for better transfer is using cyclical learning rates during fine-tuning. Start with a low learning rate, gradually increase to a moderate peak, then decrease again. This allows gentle adaptation initially (not destroying pre-trained features), more aggressive updates at the peak (finding task-specific features), and refinement finally (fine-tuning the adapted features). Combined with gradual unfreezing (start by training only the head, then unfreeze top layers, then middle layers), this provides smooth adaptation from pre-trained to task-specific features.&lt;/p&gt;

&lt;p&gt;For tasks very different from the pre-training domain, partial fine-tuning often works better than full fine-tuning. Freeze early layers (most general, least likely to need adaptation), fine-tune middle and late layers. This preserves universal low-level features while adapting task-specific higher-level features. The choice of where to freeze involves experimentation but follows the principle: freeze what transfers well, adapt what needs task-specific learning.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Transfer learning leverages pre-trained models to achieve strong performance on target tasks with limited data by transferring learned features from related source tasks with abundant data. The hierarchical nature of deep network features—general low-level features in early layers, task-specific high-level features in late layers—enables selective transfer where we keep useful general features and adapt task-specific components. Feature extraction freezes pre-trained weights and trains only a new task-specific head, working well with very limited data (hundreds of examples) and minimal computational cost. Fine-tuning adapts all or most layers with small learning rates, typically achieving better performance with moderate data (thousands of examples) by specializing pre-trained features to the target domain. Layer-wise differential learning rates control adaptation, with early layers changing minimally (preserving general features) and late layers changing more (learning task-specific features), preventing catastrophic forgetting while enabling effective specialization. Transfer learning’s effectiveness depends on source-target similarity—more similar domains enable better transfer—and the quality of pre-training—better source task performance generally improves transfer. Modern practice in computer vision starts with ImageNet pre-training, in NLP with BERT/GPT pre-training, and in speech with Wav2Vec pre-training, making transfer learning a standard first step rather than advanced technique. Understanding transfer learning deeply means recognizing it as amortizing the cost of learning general representations across many tasks, democratizing deep learning by making high performance achievable without massive task-specific datasets, and embodying the principle that good representations learned on one task often help on related tasks—a form of knowledge reuse fundamental to efficient learning.&lt;/p&gt;

&lt;p&gt;Transfer learning exemplifies how deep learning matured from requiring massive datasets for every task to enabling strong performance with limited task-specific data through strategic reuse of learned knowledge.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qaDe0qQZ5AQ&quot;&gt;Pytorch Transfer Learning and Fine Tuning Tutorial&lt;/a&gt; — Aladdin Persson, English. Load a pretrained model, replace the head, and train.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, English. The freeze-or-not decision that code is implementing.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pDdP0TFzsoQ&quot;&gt;PyTorch Tutorial 14 - Convolutional Neural Network (CNN)&lt;/a&gt; — Patrick Loeber, English. How the backbone you are freezing was built, if its layer names are unfamiliar.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15-01-01 Transfer Learning Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_01_01_Transfer_Learning_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_01_01_Transfer_Learning_Theory</id>
   <content type="html">&lt;p&gt;Why does pretraining on dogs, cars, and coffee mugs help a model diagnose diabetic retinopathy? Ben-David’s domain adaptation theorem gives a crisp mathematical answer: target-domain error is bounded by three exact quantities—source error, the statistical divergence between source and target feature distributions, and the irreducible error of the best shared hypothesis. Transfer learning works precisely when a pretrained encoder maps both domains into a shared representation where that divergence shrinks dramatically.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-theoretical-foundations-of-transfer--domain-adaptation&quot;&gt;Key ideas: Theoretical Foundations of Transfer &amp;amp; Domain Adaptation&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Ben-David Target Risk Bound&lt;/strong&gt;: Formalizes $\epsilon_T(h) \le \epsilon_S(h) + \frac{1}{2}d_{\mathcal{H}\Delta\mathcal{H}}(\mathcal{D}_S, \mathcal{D}_T) + \lambda^&lt;em&gt;$, clarifying when transfer succeeds versus when *negative transfer&lt;/em&gt; hurts performance.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Representation Transferability Across Depth&lt;/strong&gt;: Explains Yosinski et al.’s empirical finding that transferability decays smoothly with layer depth, and that co-adapted adjacent layers suffer fragile splits if frozen mid-block.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Differential Learning Rates &amp;amp; Catastrophic Forgetting&lt;/strong&gt;: Uses smaller learning rates ($\eta_{\text{backbone}} \ll \eta_{\text{head}}$) so random gradients from an untrained classification head do not destroy delicate pretrained filters during epoch 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Inductive vs. Transductive Adaptation&lt;/strong&gt;: Distinguishes labeled target fine-tuning from Unsupervised Domain Adaptation (UDA), where target labels are absent and feature alignment (MMD, DANN) bridges the gap.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-evaluating-the-ben-david-domain-adaptation-bound&quot;&gt;Worked example: Evaluating the Ben-David Domain Adaptation Bound&lt;/h3&gt;

&lt;p&gt;Suppose a pretrained classifier achieves source error $\epsilon_S(h) = 0.04$ ($4\%$) on ImageNet-style daylight photos. We test it on nighttime dashcam images where a domain classifier trained to distinguish source vs. target features achieves accuracy $a_{\text{dom}} = 0.72$ (so its error is $\text{err}_{\text{dom}} = 0.28$), and the best joint hypothesis error is $\lambda^* = 0.03$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Estimate the $\mathcal{H}\Delta\mathcal{H}$-divergence via the proxy $\mathcal{A}$-distance&lt;/strong&gt;:
\(d_{\mathcal{H}\Delta\mathcal{H}}(\mathcal{D}_S, \mathcal{D}_T) \approx 2(1 - 2\,\text{err}_{\text{dom}}) = 2(1 - 0.56) = 0.88.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Substitute into the target risk upper bound&lt;/strong&gt;:
\(\epsilon_T(h) \le 0.04 + \frac{1}{2}(0.88) + 0.03 = 0.04 + 0.44 + 0.03 = 0.51.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Now apply domain-invariant feature alignment&lt;/strong&gt;, lowering domain-classifier accuracy from $0.72$ down to $0.55$ ($\text{err}_{\text{dom}} = 0.45$, near random chance):
\(d_{\mathcal{H}\Delta\mathcal{H}} \approx 2(1 - 0.90) = 0.20 \implies \epsilon_T(h) \le 0.04 + 0.10 + 0.03 = 0.17.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Making source and target features indistinguishable to a domain discriminator slashes the worst-case target error bound from $51\%$ down to $17\%$ without changing a single source label.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;transfer-learning-leveraging-pre-trained-knowledge&quot;&gt;Transfer Learning: Leveraging Pre-trained Knowledge&lt;/h1&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Transfer learning represents one of the most practically important paradigms in modern deep learning, enabling us to build highly effective models with limited task-specific data by leveraging knowledge learned from related tasks. The core principle is deceptively simple: instead of training a neural network from scratch with randomly initialized weights, we start with weights pre-trained on a large dataset for a related task, then adapt these weights to our specific problem. This approach has democratized deep learning, making it accessible to practitioners who lack the massive datasets and computational resources required to train large models from scratch. A medical imaging application might leverage a network pre-trained on ImageNet. A sentiment analysis model might start from BERT pre-trained on web text. A speech recognition system might fine-tune Wav2Vec learned on unlabeled audio.&lt;/p&gt;

&lt;p&gt;Understanding why transfer learning works requires appreciating what neural networks learn during training. The layers of a deep network progressively build hierarchical representations. Early layers learn general, low-level features—edges, textures, simple shapes for images; basic phonemes for audio; common word patterns for text. These features are remarkably consistent across tasks and datasets. A network trained to classify cars versus trucks learns edge detectors nearly identical to a network classifying dogs versus cats, because edges are fundamental to visual understanding regardless of the specific objects. Middle layers learn mid-level features—object parts, texture combinations, shape compositions—that are somewhat task-specific but still broadly useful. Only the deepest layers learn highly task-specific features—”this particular combination indicates a golden retriever” for dog breed classification.&lt;/p&gt;

&lt;p&gt;This feature reuse across tasks is what makes transfer learning possible. The early and middle layers, having learned general features on a large source dataset, provide a strong starting point for a target task. Even if the target task differs (classifying medical images instead of natural images), the fundamental visual features—edges, textures, shapes—remain relevant. We don’t need millions of medical images to learn these basics; we can transfer them from ImageNet and focus our limited medical data on learning the task-specific features in deeper layers. This is analogous to how humans learn: having learned basic visual concepts from everyday experience, we can quickly learn to identify rare diseases from a few examples, transferring our general visual understanding rather than learning vision from scratch.&lt;/p&gt;

&lt;p&gt;The practical impact cannot be overstated. Before transfer learning became standard practice, training good image classifiers required hundreds of thousands of labeled images. With transfer learning from ImageNet pre-trained models, competitive results are possible with thousands or even hundreds of images. In natural language processing, the impact was even more dramatic. Pre-trained language models like BERT, trained on billions of words of text, can be fine-tuned for specific tasks (sentiment analysis, named entity recognition, question answering) with datasets of just thousands of labeled examples, achieving performance that would require millions of labels if training from scratch. This has enabled applications of deep learning in domains where large labeled datasets don’t exist: medical diagnosis with limited patient data, rare language processing, specialized technical document understanding.&lt;/p&gt;

&lt;p&gt;Yet transfer learning is not magic, and understanding when it works versus when it fails is crucial for practitioners. Transfer learning assumes the source and target tasks share relevant structure—edges learned from ImageNet help with medical images because both involve natural images with edges, textures, and shapes. But ImageNet features might not transfer well to radar images (different data modality), satellite images (different scale and perspective), or abstract art (different statistical properties). The more similar the source and target distributions, the more effectively features transfer. This principle guides choice of pre-trained models: for medical imaging, networks pre-trained on chest X-rays transfer better than ImageNet, though ImageNet remains surprisingly effective due to the generality of low and mid-level visual features.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;The mathematical framework for transfer learning connects to domain adaptation, multi-task learning, and meta-learning. Let’s formalize what we’re doing when we transfer knowledge and understand the theoretical foundations that explain why it works.&lt;/p&gt;

&lt;p&gt;Suppose we have a source domain with distribution \(p_S(\mathbf{x}, y)\) and abundant labeled data \(\mathcal{D}_S = \{(\mathbf{x}_i^S, y_i^S)\}_{i=1}^{N_S}\), and a target domain with distribution \(p_T(\mathbf{x}, y)\) and limited labeled data \(\mathcal{D}_T = \{(\mathbf{x}_j^T, y_j^T)\}_{j=1}^{N_T}\) where \(N_T \ll N_S\). We want to learn a predictor \(f_\theta(\mathbf{x})\) that performs well on the target domain.&lt;/p&gt;

&lt;p&gt;In standard supervised learning, we would minimize empirical risk on target data:&lt;/p&gt;

\[\theta^* = \arg\min_\theta \frac{1}{N_T}\sum_{j=1}^{N_T} \mathcal{L}(f_\theta(\mathbf{x}_j^T), y_j^T)\]

&lt;p&gt;But with small \(N_T\), this leads to severe overfitting—the model memorizes training examples without learning generalizable patterns.&lt;/p&gt;

&lt;p&gt;Transfer learning instead performs two-stage optimization:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stage 1 (Pre-training)&lt;/strong&gt;: Train on source domain
\(\theta_S^* = \arg\min_\theta \frac{1}{N_S}\sum_{i=1}^{N_S} \mathcal{L}(f_\theta(\mathbf{x}_i^S), y_i^S)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stage 2 (Fine-tuning)&lt;/strong&gt;: Initialize with \(\theta_S^*\), then train on target domain
\(\theta_T^* = \arg\min_\theta \frac{1}{N_T}\sum_{j=1}^{N_T} \mathcal{L}(f_\theta(\mathbf{x}_j^T), y_j^T), \quad \text{starting from } \theta_0 = \theta_S^*\)&lt;/p&gt;

&lt;p&gt;The initialization \(\theta_0 = \theta_S^*\) is crucial—it provides a starting point already close to a good solution for the target task (assuming domains are related), allowing fine-tuning to converge quickly with limited data.&lt;/p&gt;

&lt;p&gt;We can decompose the model as \(f_\theta = h_{\theta_h} \circ g_{\theta_g}\) where \(g_{\theta_g}\) is the feature extractor (early/middle layers) and \(h_{\theta_h}\) is the task-specific head (final layers). Transfer learning strategies differ in what they transfer and what they adapt:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Feature extraction&lt;/strong&gt;: Freeze \(\theta_g = \theta_g^S\) (use pre-trained features), only train \(\theta_h\) on target data
\(\theta_h^* = \arg\min_{\theta_h} \frac{1}{N_T}\sum_{j=1}^{N_T} \mathcal{L}(h_{\theta_h}(g_{\theta_g^S}(\mathbf{x}_j^T)), y_j^T)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Fine-tuning all layers&lt;/strong&gt;: Initialize both \(\theta_g\) and \(\theta_h\) from source, train both on target
\((\theta_g^*, \theta_h^*) = \arg\min_{\theta_g, \theta_h} \frac{1}{N_T}\sum_{j=1}^{N_T} \mathcal{L}(h_{\theta_h}(g_{\theta_g}(\mathbf{x}_j^T)), y_j^T)\)
starting from \((\theta_g^S, \theta_h^{\text{random}})\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Layer-wise differential learning rates&lt;/strong&gt;: Use different learning rates for different layers
\(\theta_g \leftarrow \theta_g - \eta_g \nabla_{\theta_g} \mathcal{L}, \quad \theta_h \leftarrow \theta_h - \eta_h \nabla_{\theta_h} \mathcal{L}\)
typically with \(\eta_g &amp;lt; \eta_h\) (smaller learning rate for pre-trained layers, larger for new head)&lt;/p&gt;

&lt;p&gt;The choice depends on dataset size and similarity. With very small target data (hundreds of examples) and similar domains, feature extraction often works best—frozen pre-trained features provide robust representations, and we only need to learn the task-specific mapping. With moderate data (thousands) and moderate similarity, fine-tuning with small learning rates adapts features slightly while avoiding catastrophic forgetting. With large data (tens of thousands+), full fine-tuning or even training from scratch might be preferable.&lt;/p&gt;

&lt;h3 id=&quot;domain-adaptation-theory&quot;&gt;Domain Adaptation Theory&lt;/h3&gt;

&lt;p&gt;The theoretical analysis of when transfer works invokes domain adaptation theory. Define the hypothesis space \(\mathcal{H}\) (all functions representable by our architecture). The error on target domain for hypothesis \(h \in \mathcal{H}\) can be bounded:&lt;/p&gt;

\[\epsilon_T(h) \leq \epsilon_S(h) + \frac{1}{2}d_{\mathcal{H}}(D_S, D_T) + \lambda\]

&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\epsilon_S(h)\): error on source domain (can be minimized with abundant source data)&lt;/li&gt;
  &lt;li&gt;\(d_{\mathcal{H}}(D_S, D_T)\): distance between source and target distributions (measures domain shift)&lt;/li&gt;
  &lt;li&gt;\(\lambda\): error of ideal joint hypothesis (minimum possible error on both domains)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This bound reveals what’s needed for successful transfer: (1) low source error (good pre-training), (2) small domain distance (similar source and target), (3) small \(\lambda\) (shared optimal hypothesis exists). When domains are very different, \(d_{\mathcal{H}}\) is large, and the bound becomes loose—no guarantee transfer helps. This formalizes the intuition that transfer works when domains share structure.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Consider a concrete scenario: building a bird species classifier with only 500 labeled images across 20 species (25 images per species). Training a ResNet-50 (25 million parameters) from scratch on this data would catastrophically overfit—we have far more parameters than training examples.&lt;/p&gt;

&lt;p&gt;The transfer learning approach starts with ResNet-50 pre-trained on ImageNet (1.2 million images, 1000 classes). This network has already learned:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Layer 1&lt;/strong&gt;: Edge detectors (horizontal, vertical, diagonal, curved)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Layer 2&lt;/strong&gt;: Texture patterns (feathers, beaks, backgrounds)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Layer 3&lt;/strong&gt;: Object parts (wings, heads, feet)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Layer 4&lt;/strong&gt;: Object compositions (whole birds, though specific to ImageNet bird species)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For our bird classification task, we:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Option 1: Feature Extraction&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Remove final classification layer (1000 classes)&lt;/li&gt;
  &lt;li&gt;Freeze all conv layers (keep pre-trained features)&lt;/li&gt;
  &lt;li&gt;Add new classification head (20 bird species)&lt;/li&gt;
  &lt;li&gt;Train only this new head on our 500 images&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This works because the frozen layers provide rich 2048-dimensional feature vectors for each image, capturing edges, textures, and bird-like parts. We only need to learn which combinations of these features correspond to which of our 20 species—a much simpler problem requiring far less data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Option 2: Fine-Tuning&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Start with pre-trained weights everywhere&lt;/li&gt;
  &lt;li&gt;Replace final layer with 20-class head (random initialization)&lt;/li&gt;
  &lt;li&gt;Train entire network with small learning rate (0.0001 vs typical 0.1)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The small learning rate is crucial. Pre-trained features are already good; we want to adapt them slightly, not destroy them. Early layers might barely change (edges are universal). Middle layers adapt more (bird-specific textures). Deep layers change most (our specific species features).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Concrete numerical example&lt;/strong&gt;: Suppose a pre-trained conv filter in layer 3 has weights detecting “curved structures” (useful for any object with curves). For bird species, we might want to detect “feather curves” specifically. Fine-tuning adjusts this filter’s weights slightly:&lt;/p&gt;

&lt;p&gt;Original weight: \(w_{\text{pre}} = 0.523\)&lt;br /&gt;
Gradient on bird data: \(\nabla w = 0.015\) (indicates small adjustment needed)&lt;br /&gt;
Updated weight: \(w_{\text{fine}} = 0.523 - 0.0001 \times 0.015 = 0.5229985\)&lt;/p&gt;

&lt;p&gt;The tiny change (0.0001 learning rate) adapts the feature slightly without destroying the useful structure learned from ImageNet. Across thousands of weights, these small adaptations accumulate to specialize the network for birds while preserving general visual understanding.&lt;/p&gt;

&lt;p&gt;Results: With feature extraction, we might achieve 85% accuracy on bird classification. With fine-tuning, 92% accuracy. Training from scratch with our 500 images: perhaps 60% accuracy (severe overfitting). The transfer learning advantage is dramatic and practical.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, English. Which layers to freeze is the theory question.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, English. Why early conv layers transfer and late layers do not, in a 2024 lecture.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. A concrete feature hierarchy to point at while you choose the cut.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>15 Transfer Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter15/15_00_Introduction</id>
   <content type="html">&lt;p&gt;If a radiologist wants to train a neural network to detect a rare lung tumor from just 400 X-rays, training a 25-million-parameter ResNet from random weights is mathematical suicide—it will memorize all 400 images by epoch 10 and fail on the 401st. Transfer learning flips the script: start from a backbone that already spent weeks learning edges, textures, curves, and object parts on millions of general images, then adapt only the final decision boundary (or gently fine-tune the upper layers) to your specialized domain.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-core-mechanics-of-transfer-learning&quot;&gt;Key ideas: Core Mechanics of Transfer Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Hierarchical Feature Reuse&lt;/strong&gt;: Recognizes that early layers of deep networks learn universal primitives (Gabor-like edges, color blobs, syntactic n-grams) while deeper layers specialize to source-task semantics.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Feature Extraction vs. Fine-Tuning Spectrum&lt;/strong&gt;: Balances freezing the backbone (low variance, ideal for tiny target datasets) against unfreezing upper or all layers with a small learning rate (lower bias, ideal for larger or shifted target domains).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Domain Shift &amp;amp; Distribution Alignment&lt;/strong&gt;: Analyzes covariate shift $p_S(x) \ne p_T(x)$ and label shift $p_S(y) \ne p_T(y)$, guiding when BatchNorm statistics and lower layers must adapt.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Parameter-Efficient Adaptation&lt;/strong&gt;: Connects classical head-replacement transfer learning directly to modern foundation-model adaptation via LoRA and adapters.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-trainable-parameter-budget--linear-probe-vs-full-fine-tuning&quot;&gt;Worked example: Trainable Parameter Budget — Linear Probe vs. Full Fine-Tuning&lt;/h3&gt;

&lt;p&gt;Suppose we adapt a ResNet-50 backbone ($23{,}508{,}032$ parameters, final pooled feature dimension $d = 2048$) to a new medical imaging task with $C = 5$ classes.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Linear Probe (Feature Extraction — freeze backbone, train only new linear head)&lt;/strong&gt;:
\(\text{Trainable params} = 2048 \times 5 + 5 = 10{,}245.\)
Fraction of model updated: $\frac{10{,}245}{23{,}518{,}277} \approx 0.044\%$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Samples-per-parameter ratio on $N = 500$ training images&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Full fine-tuning: $500 / 23{,}518{,}277 \approx 0.000021$ images per parameter (extreme overfitting risk!).&lt;/li&gt;
      &lt;li&gt;Linear probe: $500 / 10{,}245 \approx 0.049$ images per parameter ($2{,}300\times$ tighter capacity control!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Freezing the backbone shrinks the trainable hypothesis space by more than three orders of magnitude, turning an impossible 500-image problem into a well-posed convex-like classification task.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Transfer learning leverages knowledge from pre-trained models to solve new tasks with limited data. Instead of training from scratch, we fine-tune existing models or use them as feature extractors. This chapter covers feature extraction, fine-tuning strategies, domain adaptation, and practical transfer learning with popular models like ResNet, BERT, and GPT.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After feature extraction and fine-tuning, see &lt;strong&gt;15-99 Modern Applications and Updates&lt;/strong&gt; for LoRA, QLoRA, and PEFT adapters on foundation models.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (interview practice):&lt;/strong&gt; After the transfer notes, see &lt;strong&gt;15-98 Interviews Practice&lt;/strong&gt; for original feature-extraction / domain-shift prompts; full solved Q&amp;amp;A is in &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=5T-iXNNiwIs&quot;&gt;Fine-tuning a Neural Network explained&lt;/a&gt; — deeplizard, English. Fine-tuning a pretrained net is this chapter.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qaDe0qQZ5AQ&quot;&gt;Pytorch Transfer Learning and Fine Tuning Tutorial&lt;/a&gt; — Aladdin Persson, English. The PyTorch version of that fine-tune, which the code lesson follows.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, English. The conv nets you are usually transferring from.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>14-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter14/14_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter14/14_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Many observers declared GANs dead once Latent Diffusion took over text-to-image generation in 2022—yet look inside 2024–2026’s fastest one-step image generators (SDXL-Turbo, DMD2, LADD) and neural codecs, and you will find an adversarial discriminator doing the heavy lifting. While diffusion owns iterative multi-step sampling, GANs remain unmatched whenever you need single-step sub-50ms inference, razor-sharp local texture, or clean latent-space facial editing.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-gans-in-the-post-diffusion-era-20222026&quot;&gt;Key ideas: GANs in the Post-Diffusion Era (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — StyleGAN3 &amp;amp; Disentangled Latent Inversion&lt;/strong&gt;: Achieves alias-free equivariant synthesis and projects real photographs into $\mathcal{W}^+$ latent space for instant semantic editing (age, lighting, gaze).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Adversarial Diffusion Distillation (ADD / LADD)&lt;/strong&gt;: Combines a pretrained diffusion teacher with a PatchGAN/feature-space discriminator to collapse 50-step diffusion down to 1–4 real-time steps without losing sharpness.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Perceptual Discriminators Inside Codecs&lt;/strong&gt;: Uses multi-scale PatchGAN and multi-period audio discriminators (HiFi-GAN, EnCodec) so VAE and audio-codec decoders reconstruct crisp edges and harmonics.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Latency vs. Diversity Engineering Trade-offs&lt;/strong&gt;: Defines when to choose a GAN or adversarially distilled student (real-time video, on-device filters, super-resolution) over multi-step diffusion.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-inference-latency-speedup-of-adversarial-diffusion-distillation&quot;&gt;Worked example: Inference Latency Speedup of Adversarial Diffusion Distillation&lt;/h3&gt;

&lt;p&gt;Suppose a standard diffusion U-Net/DiT takes $t_{\text{step}} = 35\text{ ms}$ per denoising step on a consumer GPU, uses Classifier-Free Guidance (doubling batch size so each step costs $2 \times 35 = 70\text{ ms}$), runs for $N = 30$ steps, plus a $40\text{ ms}$ VAE decode. Compare this to an adversarially distilled 1-step GAN-diffusion student (no CFG needed at inference).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standard 30-step Diffusion with CFG&lt;/strong&gt;:
\(T_{\text{diff}} = 30 \times 70\text{ ms} + 40\text{ ms} = 2{,}140\text{ ms} \approx 2.14\text{ seconds/image}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adversarially Distilled 1-Step Student&lt;/strong&gt;:
\(T_{\text{1-step}} = 1 \times 35\text{ ms} + 40\text{ ms} = 75\text{ ms/image} \quad (\approx 13.3\text{ frames/sec}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;End-to-end speedup&lt;/strong&gt;:
\(\frac{2{,}140}{75} \approx 28.5\times\text{ faster}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Pairing adversarial discriminators with diffusion teachers preserves modern foundation-model semantics while restoring classic GAN single-pass speed.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-gans-after-diffusion--faces-inversion-and-one-step-generators&quot;&gt;Optional: GANs after diffusion — faces, inversion, and one-step generators&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace GAN losses, DCGAN/StyleGAN theory, or the training-pitfalls notes. It records what GANs are still &lt;em&gt;for&lt;/em&gt; after diffusion became the default sampler.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The adversarial pair&lt;/p&gt;

\[\min_G \max_D \mathbb{E}_{x}[\log D(x)] + \mathbb{E}_{z}[\log(1-D(G(z)))]\]

&lt;p&gt;is unchanged. The market share changed: text-to-image is mostly diffusion/flow; &lt;strong&gt;GANs remain&lt;/strong&gt; where you need instant sampling, inversion, or a well-studied face prior.&lt;/p&gt;

&lt;h2 id=&quot;1-stylegan3-and-the-20222023-face-stack&quot;&gt;1. StyleGAN3 and the 2022–2023 face stack&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2106.12423&quot;&gt;Karras et al., 2021&lt;/a&gt; (StyleGAN3, used throughout 2022–2024) remove texture sticking via alias-free convs. Industry still uses StyleGAN2/3 for identity, aging, and editing because the &lt;strong&gt;W / W+&lt;/strong&gt; latent is invertible and editable (&lt;a href=&quot;https://github.com/omertov/encoder4editing&quot;&gt;Richardson et al., e4e / pSp&lt;/a&gt; pipelines). Diffusion inversion exists, but StyleGAN inversion is cheaper and more mature.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;gigagan-and-large-scale-text-to-image-gans&quot;&gt;GigaGAN and large-scale text-to-image GANs&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.05511&quot;&gt;Kang et al., 2023&lt;/a&gt; (GigaGAN) show a GAN can reach diffusion-like text-to-image quality with &lt;strong&gt;one forward pass&lt;/strong&gt;. The paper is the existence proof that adversarial training did not die; most open products still chose diffusion for stability.&lt;/p&gt;

&lt;h3 id=&quot;distillation-gan-as-a-student-of-diffusion&quot;&gt;Distillation: GAN as a student of diffusion&lt;/h3&gt;

&lt;p&gt;Many one-step generators (SD-Turbo, LCM-LoRA-style distillations, UFOGen-class work) add an &lt;strong&gt;adversarial&lt;/strong&gt; head so a tiny student matches a slow teacher. That is Chapter 14’s discriminator used as a &lt;em&gt;distillation&lt;/em&gt; tool, not as the only generative model.&lt;/p&gt;

&lt;h3 id=&quot;when-to-pick-a-gan-in-2026&quot;&gt;When to pick a GAN in 2026&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Real-time avatars, talking-head, and game sprites.&lt;/li&gt;
  &lt;li&gt;Dataset rebalancing when you already have a StyleGAN fit.&lt;/li&gt;
  &lt;li&gt;Not your first choice for open-vocabulary “a red cube on the moon.”&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/NVlabs/stylegan3&quot;&gt;NVlabs/stylegan3&lt;/a&gt; and &lt;a href=&quot;https://github.com/NVlabs/stylegan2-ada-pytorch&quot;&gt;NVlabs/stylegan2-ada-pytorch&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/mingukkang/GigaGAN&quot;&gt;mingukkang/GigaGAN&lt;/a&gt; (paper code).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/diffusers&quot;&gt;huggingface/diffusers&lt;/a&gt; — some turbo/adversarial distill checkpoints.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2106.12423&quot;&gt;Alias-Free Generative Adversarial Networks — StyleGAN3 (Karras et al., 2021)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.05511&quot;&gt;Scaling up GANs for Text-to-Image Synthesis — GigaGAN (Kang et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2311.17042&quot;&gt;Adversarial Diffusion Distillation (Sauer et al., 2023)&lt;/a&gt; — SD-Turbo: GAN loss on a diffusion student.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Train the toy GAN and read the mode-collapse notes first. This lesson only answers “why is StyleGAN still in production while DALL·E-class demos use diffusion?”&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=4LNO8nLxF4Y&quot;&gt;AI generated faces - StyleGAN explained!&lt;/a&gt; — AI Bites, English. StyleGAN is the face-synthesis stack this note’s 2022–2023 section describes.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, English. The original two-player game StyleGAN did not replace.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TpMIssRdhco&quot;&gt;What are GANs (Generative Adversarial Networks)?&lt;/a&gt; — IBM Technology, English. A short baseline if StyleGAN’s style space is hard to separate from a vanilla GAN.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>14-01 Generative Adversarial Networks</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter14/14_01_GAN_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter14/14_01_GAN_Fundamentals</id>
   <content type="html">&lt;p&gt;Generative Adversarial Networks transformed deep learning by proving you can learn to synthesize crisp, high-resolution data without ever writing down a tractable probability density. Connecting the minimax game theory directly to hands-on PyTorch training loops equips you to understand not only classic DCGANs and StyleGANs, but also why adversarial losses remain essential inside modern VAEs, audio codecs, and distilled diffusion models.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-core-pillars-of-gan-mastery&quot;&gt;Key ideas: Core Pillars of GAN Mastery&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Minimax Equilibrium &amp;amp; Density Ratios&lt;/strong&gt;: Explains how an optimal discriminator estimates $\frac{p_{\text{data}}}{p_{\text{data}} + p_G}$ and reduces generator optimization to minimizing Jensen–Shannon divergence.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Stability Theory (WGAN, Gradient Penalty, Spectral Norm)&lt;/strong&gt;: Bridges the gap between brittle early GANs and smooth, Lipschitz-constrained critics.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Practical DCGAN Training Mechanics&lt;/strong&gt;: Covers alternating updates, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.detach()&lt;/code&gt;, LeakyReLU, BatchNorm, and Adam $\beta_1 = 0.5$ tuning.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Diagnostic Discipline&lt;/strong&gt;: Distinguishes healthy equilibrium (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D(real) ≈ 0.5–0.7&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D(fake) ≈ 0.3–0.5&lt;/code&gt;) from mode collapse and discriminator overpowering.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-diagnosing-gan-health-from-discriminator-outputs&quot;&gt;Worked example: Diagnosing GAN Health from Discriminator Outputs&lt;/h3&gt;

&lt;p&gt;Consider three training snapshots reporting average discriminator probabilities $(\bar{D}&lt;em&gt;{\text{real}},\; \bar{D}&lt;/em&gt;{\text{fake}})$:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Snapshot A&lt;/strong&gt;: $\bar{D}&lt;em&gt;{\text{real}} = 0.999,\; \bar{D}&lt;/em&gt;{\text{fake}} = 0.001$&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Snapshot B&lt;/strong&gt;: $\bar{D}&lt;em&gt;{\text{real}} = 0.62,\; \bar{D}&lt;/em&gt;{\text{fake}} = 0.38$&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Snapshot C&lt;/strong&gt;: $\bar{D}&lt;em&gt;{\text{real}} = 0.50,\; \bar{D}&lt;/em&gt;{\text{fake}} = 0.50$, while generated images are all identical copies of the digit “1”.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute $\mathcal{L}&lt;em&gt;D = -\ln \bar{D}&lt;/em&gt;{\text{real}} - \ln(1 - \bar{D}_{\text{fake}})$ for each&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Snapshot A: $-\ln(0.999) - \ln(0.999) \approx 0.002$ (Discriminator has crushed Generator; vanishing gradients!).&lt;/li&gt;
      &lt;li&gt;Snapshot B: $-\ln(0.62) - \ln(0.62) = 2(0.478) = 0.956$ (Healthy informative competition near equilibrium!).&lt;/li&gt;
      &lt;li&gt;Snapshot C: $-\ln(0.5) - \ln(0.5) = 1.386$ (Loss looks “ideal,” yet visual inspection exposes mode collapse!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Never judge a GAN by loss scalars alone—always pair loss monitoring with generated image grids and diversity metrics like FID.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Generative adversarial networks:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Theory&lt;/strong&gt; — minimax formulation and intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implementation&lt;/strong&gt; — training loop, papers, pitfalls&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, English. Before theory and code diverge.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Gib_kiXgnvA&quot;&gt;The Math Behind Generative Adversarial Networks Clearly Explained!&lt;/a&gt; — Normalized Nerd, English. The value function both lessons write.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, English. CS231n’s GAN segment, including the failure modes the notes name.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>14-01-02 GAN Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter14/14_01_02_GAN_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter14/14_01_02_GAN_Implementation</id>
   <content type="html">&lt;p&gt;Coding a Deep Convolutional GAN (DCGAN) teaches you more about gradient hygiene than almost any other PyTorch exercise. Forget &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.detach()&lt;/code&gt; on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fake_images&lt;/code&gt; when updating the discriminator and you waste compute backpropagating through the generator twice; use standard ReLU in the discriminator and dead neurons choke gradient flow back to $G$; set Adam’s $\beta_1 = 0.9$ instead of $0.5$ and momentum overshoots the moving Nash equilibrium into wild oscillations.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-engineering-dcgans-in-pytorch&quot;&gt;Key ideas: Engineering DCGANs in PyTorch&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — DCGAN Architectural Stabilizers&lt;/strong&gt;: Replaces pooling with strided convolutions (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D&lt;/code&gt;) and transposed convolutions (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;G&lt;/code&gt;), applies &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BatchNorm2d&lt;/code&gt; (except &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D&lt;/code&gt;’s input and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;G&lt;/code&gt;’s output), and uses &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LeakyReLU(0.2)&lt;/code&gt; in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D&lt;/code&gt; to keep negative gradients alive.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Detaching &amp;amp; Alternating Optimizer Steps&lt;/strong&gt;: Separates discriminator updates (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fake.detach()&lt;/code&gt;) from generator updates (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D(fake)&lt;/code&gt; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;G&lt;/code&gt; gradients active and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D&lt;/code&gt; weights frozen/unstepped), preventing accidental graph corruption.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Non-Saturating Loss &amp;amp; Label Smoothing&lt;/strong&gt;: Trains &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;G&lt;/code&gt; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BCEWithLogitsLoss(D(fake), ones)&lt;/code&gt; and optionally smooths real labels to $0.9$ to keep &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D&lt;/code&gt; from becoming overconfident and starving &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;G&lt;/code&gt; of gradients.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Reduced Momentum ($\beta_1 = 0.5$) &amp;amp; Monitoring&lt;/strong&gt;: Lowers Adam’s first-moment decay from $0.9$ to $0.5$ so optimizers adapt rapidly to a non-stationary opponent, while tracking &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D(real)&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D(fake)&lt;/code&gt; probabilities every epoch.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-tracing-one-discriminator--generator-update-step-on-logits&quot;&gt;Worked example: Tracing One Discriminator &amp;amp; Generator Update Step on Logits&lt;/h3&gt;

&lt;p&gt;Suppose for a mini-batch of 2 real and 2 fake images, the discriminator outputs raw logits $s_{\text{real}} = [2.0, 0.0]$ and $s_{\text{fake}} = [-2.0, 0.0]$. Using $\sigma(2) \approx 0.8808$, $\sigma(0) = 0.5$, $\sigma(-2) \approx 0.1192$:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Discriminator loss $\mathcal{L}&lt;em&gt;D = \text{BCE}(s&lt;/em&gt;{\text{real}}, 1) + \text{BCE}(s_{\text{fake}}, 0)$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Real term: $-\frac{1}{2}[\ln(0.8808) + \ln(0.5)] = -\frac{1}{2}[-0.1269 - 0.6931] = 0.4100$.&lt;/li&gt;
      &lt;li&gt;Fake term: $-\frac{1}{2}[\ln(1 - 0.1192) + \ln(1 - 0.5)] = -\frac{1}{2}[-0.1269 - 0.6931] = 0.4100$.&lt;/li&gt;
      &lt;li&gt;Total $\mathcal{L}_D = 0.4100 + 0.4100 = 0.8200$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Non-saturating Generator loss $\mathcal{L}&lt;em&gt;G = \text{BCE}(s&lt;/em&gt;{\text{fake}}, 1)$&lt;/strong&gt;:
\(\mathcal{L}_G = -\frac{1}{2}[\ln(0.1192) + \ln(0.5)] = -\frac{1}{2}[-2.1269 - 0.6931] = 1.4100.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient on the generator’s fake logits $\frac{\partial \mathcal{L}&lt;em&gt;G}{\partial s&lt;/em&gt;{\text{fake}}} = \frac{1}{2}(\sigma(s_{\text{fake}}) - 1)$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;For $s_{\text{fake},1} = -2.0$: $\frac{1}{2}(0.1192 - 1) = -0.4404$ (strong push upward toward real!).&lt;/li&gt;
      &lt;li&gt;For $s_{\text{fake},2} = 0.0$: $\frac{1}{2}(0.5 - 1) = -0.2500$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Even when a fake image is confidently rejected ($s = -2.0$), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BCEWithLogitsLoss(..., ones)&lt;/code&gt; delivers a clean, non-vanishing gradient of $-0.4404$ straight into the generator.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Let’s implement a complete GAN from scratch to understand the training dynamics:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision.utils&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;make_grid&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Generator: maps random noise to fake data.
    
    Architecture follows common pattern for image generation:
    - Start with low spatial resolution but many channels
    - Progressively upsample spatially while reducing channels
    - Final layer outputs image with correct dimensions
    
    For MNIST: noise (100) → (256×7×7) → (128×14×14) → (1×28×28)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Project and reshape noise
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Linear layer: 100 → 256*7*7, then reshape to (256, 7, 7)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Upsample through transposed convolutions
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;deconv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# 256×7×7 → 128×14×14
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ConvTranspose2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Stabilizes training
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# 128×14×14 → 1×28×28
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ConvTranspose2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Output in [-1, 1] (we&apos;ll normalize real data to match)
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        z: (batch, latent_dim) random noise
        Returns: (batch, 1, 28, 28) generated images
        
        The forward pass transforms unstructured noise into structured
        images through learned transformations. Early in training, outputs
        are noise. As training progresses, digit-like structures emerge.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reshape to feature maps
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;deconv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Discriminator: distinguishes real from fake.
    
    Architecture mirrors generator in reverse:
    - Input: (1×28×28) image
    - Conv layers progressively downsample while increasing channels
    - Final: scalar output (probability image is real)
    
    Uses LeakyReLU instead of ReLU to prevent dying units, and no pooling
    (stride for downsampling instead) following DCGAN best practices.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# 1×28×28 → 64×14×14
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LeakyReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Negative slope 0.2
&lt;/span&gt;            
            &lt;span class=&quot;c1&quot;&gt;# 64×14×14 → 128×7×7
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LeakyReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Flatten: 128×7×7 → 6272
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Final classification
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Probability of being real
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (batch, 1, 28, 28) images
        Returns: (batch, 1) probabilities of being real
        
        The discriminator learns hierarchical features for detection:
        - Early layers: edges, textures (distinguish fake textures from real)
        - Middle layers: shapes, patterns (detect anatomically incorrect digits)  
        - Late layers: holistic features (identify subtle statistical differences)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training GAN
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Generative Adversarial Network on MNIST&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Hyperparameters
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0002&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Adam beta1 (lower than default 0.9 for GAN stability)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Data loading (normalize to [-1, 1] to match generator&apos;s tanh output)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Compose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ToTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normalize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Normalize to [-1, 1]
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                          &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;drop_last&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Initialize networks
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;generator&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;discriminator&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Optimizers (both use Adam with β1=0.5 for stability)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer_G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;betas&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer_D&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;betas&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Loss function (binary cross-entropy)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BCELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Labels for real and fake (used in loss computation)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;real_label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;fake_label&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generator parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Discriminator parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training for &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; epochs...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This demonstrates the adversarial training dynamics:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training loop
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;G_losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;D_losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;real_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;real_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# ==================== Train Discriminator ====================
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Discriminator wants to maximize: log D(x) + log(1 - D(G(z)))
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Equivalently, minimize: -log D(x) - log(1 - D(G(z)))
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Train on real data: maximize log D(x)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Loss: -log D(x) (negated because we minimize)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;labels_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;full&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;real_label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;real_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_D_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Train on fake data: maximize log(1 - D(G(z)))
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Loss: -log(1 - D(G(z)))
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;fake_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;full&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fake_label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Detach! Don&apos;t backprop through G
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss_D_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Total discriminator loss
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss_D&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss_D_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss_D_fake&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# ==================== Train Generator ====================
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Generator wants to minimize: -log D(G(z))
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Equivalently, maximize: log D(G(z)) (non-saturating objective)
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Generate fakes again (no detach this time - we need gradients through G!)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;fake_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output_fake_for_G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Generator tries to make discriminator output 1 (real) for its fakes
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;labels_real_for_G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;full&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;real_label&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_G&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_fake_for_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_real_for_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;loss_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Track losses
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Once per epoch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;G_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;D_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Print progress
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;if &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch [&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;]  &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;D_loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;G_loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_G&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;D(x): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;D(G(z)): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Complete! Analyzing Results&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate samples
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Generate 64 samples
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;z_sample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;fake_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; fake MNIST digits&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (64, 1, 28, 28)
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Check discriminator&apos;s opinion on generated samples
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;discriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Discriminator scores for generated samples:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (ideally ~0.5)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Std:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# If mean is near 0.5, generator is successfully fooling discriminator
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ✓ Generator successfully fools discriminator!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;disc_scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ✗ Discriminator still easily detects fakes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ~ Generator is somewhat convincing&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate latent space interpolation
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Latent Space Interpolation in GAN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Two random latent codes
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Interpolate
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generating &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; images by interpolating latent codes:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Step &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (t=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;): Generated image shape &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Interpolation should show smooth morphing between different digits.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Quality of interpolation indicates latent space structure.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GAN Training Insights&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Key observations from training:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Adversarial dynamics create natural curriculum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Balance between D and G is crucial (neither should dominate)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;3. Loss values don&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;t directly indicate quality (check samples!)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;4. Mode collapse is a constant danger (monitor diversity)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;5. Generated samples can be realistic despite imperfect equilibrium&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The relationship between GANs and variational autoencoders illuminates different approaches to generative modeling. VAEs explicitly model the data distribution through a latent variable model $$p(\mathbf{x}) = \int p(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})p(\mathbf{z})d\mathbf{z}$$, training through maximizing a variational lower bound on likelihood. This probabilistic framework provides theoretical guarantees and enables principled Bayesian inference but requires choosing parametric forms for distributions and often produces blurrier samples due to the reconstruction loss. GANs implicitly model distributions through the generator’s learned mapping from noise to data, using adversarial training instead of likelihood. This enables generating sharper, more realistic samples (because the discriminator can learn perceptual similarity rather than pixel-wise reconstruction) but lacks VAE’s theoretical guarantees and density estimation capability. Understanding both approaches reveals different tradeoffs: VAEs for theoretical understanding and density modeling, GANs for sample quality and flexibility.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;GANs connect to game theory through the minimax formulation. The generator and discriminator play a two-player zero-sum game where one’s gain (discriminator correctly identifying fakes) is the other’s loss (generator’s fakes being detected). Nash equilibrium—where neither player can improve by unilaterally changing strategy—corresponds to the generator matching the data distribution. However, reaching Nash equilibrium in practice is challenging because we’re using gradient-based optimization, which makes local moves, in a non-convex game where equilibria might not exist or be unstable. This connection to game theory helps understand why GAN training can be unstable (many games have no pure strategy Nash equilibrium or have multiple equilibria) and motivates algorithms from game theory like unrolled optimization.&lt;/p&gt;

&lt;p&gt;The relationship to adversarial examples and robustness provides an interesting perspective. In adversarial examples research, we perturb inputs slightly to fool classifiers. In GANs, we’re doing something similar but more ambitious: creating completely synthetic inputs that fool the discriminator. The discriminator trying to resist fooling is analogous to adversarial training for robust classifiers. This connection suggests techniques from adversarial robustness (like certified defenses) might apply to stabilizing GAN training, and conversely, that GAN discriminators might provide insights into what makes classifiers vulnerable to adversarial examples. The mathematical connection is deep: both involve optimizing over input space to maximize or minimize classifier outputs.&lt;/p&gt;

&lt;p&gt;GANs’ impact on semi-supervised learning demonstrates how generative models can improve discriminative tasks. By adding an auxiliary task to the discriminator—not just real/fake but also classifying real images into categories—we can leverage unlabeled data (used for adversarial training) to improve classification on limited labeled data. The discriminator learns representations through both tasks, with the generative task providing regularization and additional training signal. This semi-supervised GAN framework has been successful in low-data regimes, showing how generative and discriminative learning can be mutually beneficial.&lt;/p&gt;

&lt;p&gt;Finally, GANs connect to the broader theme of learning without direct supervision on the target task. We never show the generator example outputs—it learns purely from discriminator feedback. This is analogous to reinforcement learning where agents learn from reward signals rather than supervised examples. Indeed, GANs can be viewed as applying policy gradient methods (from RL) to generative modeling, with the discriminator providing rewards (high scores for good fakes) that guide generator improvement. This connection has led to hybrid approaches combining GAN training with reinforcement learning principles for improved stability and performance.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1406.2661&quot;&gt;“Generative Adversarial Networks” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ian Goodfellow, Jean Pouget-Abadie, Mehdi Mirza, Bing Xu, David Warde-Farley, Sherjil Ozair, Aaron Courville, Yoshua Bengio&lt;br /&gt;
This foundational paper introduced the GAN framework and remains one of the most influential papers in modern machine learning. Goodfellow conceived the basic idea—training generator and discriminator adversarially—reportedly in a single evening, though the paper’s development involved significant theoretical and empirical work. The paper formalized GANs as a minimax game, proved that at equilibrium the generator learns the data distribution, and demonstrated results on several datasets. What made GANs revolutionary was not just the results but the paradigm shift: generative modeling through competition rather than likelihood maximization or reconstruction. The paper acknowledged training challenges (instability, mode collapse) while showing the approach’s potential. Reading it today, one appreciates both the clarity of the core idea and the prescience about challenges that would occupy researchers for years. GANs demonstrated that sometimes the best way to solve a problem isn’t to attack it directly (modeling density explicitly) but indirectly (learning to generate through adversarial feedback).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1511.06434&quot;&gt;“Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Alec Radford, Luke Metz, Soumith Chintala&lt;br /&gt;
The DCGAN paper made GANs practical by identifying architectural guidelines that stabilize training and improve sample quality. The authors systematically explored design choices—convolutional vs fully connected layers, batch normalization placement, activation functions—finding combinations that consistently worked. Their guidelines: use strided convolutions instead of pooling, use batch norm in both networks (except generator output and discriminator input), use ReLU in generator except output (tanh), use LeakyReLU in discriminator. These weren’t theoretically motivated but empirically discovered through extensive experimentation, demonstrating that practical progress sometimes comes from systematic engineering rather than mathematical insight. DCGAN showed that GANs could generate high-quality images (64×64 faces) and that the learned latent space had meaningful structure—arithmetic in latent space (vector for “smiling woman” minus “neutral woman” plus “neutral man”) produced “smiling man.” This demonstrated GANs learn disentangled representations encoding semantic attributes, making them useful beyond generation for representation learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1606.03498&quot;&gt;“Improved Techniques for Training GANs” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Tim Salimans, Ian Goodfellow, Wojciech Zaremba, Vicki Cheung, Alec Radford, Xi Chen&lt;br /&gt;
This paper addressed GAN training instabilities through several techniques: feature matching (train generator to match statistics of discriminator’s intermediate features rather than fool final output), minibatch discrimination (let discriminator compare examples within a batch to detect lack of diversity), historical averaging (penalize parameters for deviating from historical averages), one-sided label smoothing (use 0.9 instead of 1.0 for real labels to prevent discriminator overconfidence), and virtual batch normalization (normalize using statistics from a reference batch to reduce batch-to-batch variance). Each technique addresses a specific failure mode: feature matching reduces instability, minibatch discrimination combats mode collapse, label smoothing prevents discriminator saturation. The paper also introduced the Inception Score for quantifying sample quality, providing an automated metric (though imperfect) for evaluating GANs. This work established that successful GAN training requires multiple complementary tricks rather than just the basic algorithm, providing a toolkit that has become standard practice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1710.10196&quot;&gt;“Progressive Growing of GANs for Improved Quality, Stability, and Variation” (2018)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Tero Karras, Timo Aila, Samuli Laine, Jaakko Lehtinen (NVIDIA)&lt;br /&gt;
This paper introduced progressive training: start with low-resolution images (4×4) and progressively add layers to generator and discriminator, increasing resolution (8×8, 16×16, …, up to 1024×1024). This approach stabilizes training (easier to learn low-resolution distributions first) and enables generating very high-resolution images that were previously impossible. The paper also introduced improved evaluation metrics and training techniques. The generated faces at 1024×1024 resolution were shockingly realistic, demonstrating GANs’ capability for high-fidelity generation. Progressive growing has influenced subsequent work (StyleGAN builds on it) and demonstrated that training curriculum—gradually increasing task difficulty—applies not just to data (easy examples first) but to architecture (simple generation first, complex later). The work showed that GAN training instability can be partially addressed through careful training procedures, not just architecture or loss modifications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1812.04948&quot;&gt;“A Style-Based Generator Architecture for Generative Adversarial Networks” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Tero Karras, Samuli Laine, Timo Aila (NVIDIA)&lt;br /&gt;
StyleGAN redesigned the generator architecture to enable fine-grained control over generated images. Instead of feeding latent code directly into the generator, StyleGAN maps it through a mapping network to an intermediate latent space \(\mathcal{W}\), then uses this to control style at different resolution levels through adaptive instance normalization. This enables incredible control: changing coarse styles (pose, face shape) independently of fine styles (hair texture, skin pores). The paper demonstrated unprecedented image quality and introduced tools for analyzing and improving GANs (like perceptual path length metric). StyleGAN generated faces indistinguishable from real photographs, achieving a milestone in generative modeling. The architecture’s success showed that generator design matters enormously—not all ways of mapping noise to images are equally good. The disentanglement properties (ability to control attributes independently) made StyleGAN useful for semantic editing and style transfer, expanding GANs from pure generation to controllable synthesis.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;Mode collapse is perhaps the most frustrating failure mode in GAN training. The generator discovers it can fool the discriminator by producing only a few types of outputs rather than the full data diversity. For MNIST, this might mean generating only 1s and 7s, ignoring other digits. For faces, generating only certain poses or expressions. Detection requires checking sample diversity, not just quality—generate many samples and verify they span the data distribution. Solutions include minibatch discrimination (let discriminator see multiple samples and detect homogeneity), unrolled optimization (let generator anticipate discriminator’s response), or using different loss functions like Wasserstein GAN that are less prone to mode collapse. Understanding that mode collapse stems from the generator finding local optima in the adversarial game helps recognize when it’s occurring and motivates these solutions.&lt;/p&gt;

&lt;p&gt;Discriminator overpowering the generator early in training is common and destructive. If the discriminator becomes too good too quickly, it assigns probability near 0 to all generator outputs, providing vanishing gradients to the generator which can’t learn. This happens when the discriminator is too large relative to the generator, learning rate is too high for discriminator, or real/fake distributions are easily separable initially (generator starts terrible). Solutions: train discriminator less frequently (every \(k\) generator updates), use lower learning rate for discriminator, add noise to discriminator inputs (blurring the real/fake distinction), or use one-sided label smoothing (real labels = 0.9 instead of 1.0, reducing discriminator overconfidence). Monitoring \(D(\mathbf{x}_{\text{real}})\) and \(D(G(\mathbf{z}))\) helps: if real is always near 1 and fake always near 0, discriminator is too strong.&lt;/p&gt;

&lt;p&gt;Using batch normalization in the discriminator can cause problems when batch sizes are small because batch statistics become unreliable. With batch size 1, batch norm fails entirely. Solutions include using larger batch sizes (at least 32-64), using layer normalization or instance normalization instead of batch norm, or using virtual batch normalization (normalize using statistics from a fixed reference batch). Understanding that discriminator’s normalization affects what features it learns helps debug training issues related to batch size.&lt;/p&gt;

&lt;p&gt;Evaluating GAN quality is challenging because we can’t compute likelihood. Inception Score measures both quality (samples should be confidently classified) and diversity (should cover all classes) using a pre-trained classifier, but has limitations (doesn’t detect memorization, biased toward ImageNet classes). Fréchet Inception Distance (FID) compares statistics of real and generated samples in feature space, providing a better metric but still imperfect. For practical work, visual inspection remains important—generate many samples and manually check quality and diversity. Quantitative metrics complement but don’t replace human evaluation.&lt;/p&gt;

&lt;p&gt;A powerful technique for stable training is spectral normalization, which constrains discriminator’s Lipschitz constant by normalizing weight matrices by their spectral norm (largest singular value). This prevents the discriminator from having arbitrarily large gradients, stabilizing training dynamics. The technique adds minimal computational cost (computing spectral norm via power iteration) while dramatically improving stability. Modern GANs often use spectral normalization in the discriminator as standard practice, showing how theoretical understanding of training dynamics (Lipschitz constraint improves stability) translates to practical techniques.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Generative Adversarial Networks learn to generate realistic data by training two networks adversarially: a generator creating fake samples from random noise and a discriminator distinguishing real from fake. The adversarial objective is formulated as a minimax game where the generator minimizes what the discriminator maximizes, creating competitive dynamics that drive both networks toward higher capability. At equilibrium, the generator’s distribution matches the data distribution and the discriminator cannot distinguish real from fake better than random guessing, though reaching this equilibrium in practice is challenging. Training alternates between discriminator updates (using real data and generator’s fakes) and generator updates (trying to fool the discriminator), requiring careful balancing to prevent either network from dominating. Mode collapse—the generator producing limited diversity—remains a persistent challenge addressed through architectural choices, modified objectives, and training techniques. GANs excel at generating high-quality, realistic samples (often superior to VAEs) and learning latent spaces with semantic structure enabling interpolation and manipulation. The implicit density modeling approach enables generating complex high-dimensional data without explicit probabilistic formulations, though at the cost of training instability and difficulty in evaluation. Understanding GANs deeply means appreciating both their creative power in generating realistic data and the delicate training dynamics that make them challenging but rewarding to work with in practice.&lt;/p&gt;

&lt;p&gt;The GAN framework demonstrates that competition can be a powerful learning signal, a principle that has influenced deep learning far beyond generative modeling.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, English. The alternating updates the code performs.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TpMIssRdhco&quot;&gt;What are GANs (Generative Adversarial Networks)?&lt;/a&gt; — IBM Technology, English. A compact reminder of which network receives which loss.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Gib_kiXgnvA&quot;&gt;The Math Behind Generative Adversarial Networks Clearly Explained!&lt;/a&gt; — Normalized Nerd, English. Use this when the implementation’s loss sign does not match the theory.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>14-01-01 GAN Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter14/14_01_01_GAN_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter14/14_01_01_GAN_Theory</id>
   <content type="html">&lt;p&gt;Why does a GAN produce razor-sharp hair strands where a VAE produces soft mist? The answer lies in the calculus of divergences: optimizing the discriminator to optimality turns the generator’s objective into minimizing the Jensen–Shannon divergence $D_{\text{JS}}(p_{\text{data}} | p_G)$, which—unlike forward KL—does not force the generator to smear probability mass across empty gaps between modes. Yet that same sharpness comes with a mathematical trap whenever real and generated manifolds fail to overlap.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mathematical-theory-of-gans&quot;&gt;Key ideas: Mathematical Theory of GANs&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;em&gt;*Pillar 1 — Variational Derivation of Optimal $D^&lt;/em&gt;$&lt;em&gt;*: Maximizes $a\log y + b\log(1-y)$ pointwise to prove $D^&lt;/em&gt;(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x) + p_G(x)}$ and $C(G) = -\log 4 + 2\,D_{\text{JS}}(p_{\text{data}} | p_G)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Disjoint Support &amp;amp; Vanishing Gradients&lt;/strong&gt;: Shows that when real and fake images lie on low-dimensional manifolds with zero overlap, $D_{\text{JS}} = \log 2$ identically (a flat plateau with zero gradient!), explaining why early GANs stalled.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Kantorovich–Rubinstein Duality &amp;amp; WGAN&lt;/strong&gt;: Replaces JSD with Earth Mover’s (Wasserstein-1) distance $W_1(p_{\text{data}}, p_G) = \sup_{|f|&lt;em&gt;L \le 1} \mathbb{E}&lt;/em&gt;{p_{\text{data}}}[f(x)] - \mathbb{E}_{p_G}[f(x)]$, providing smooth linear gradients even across disjoint supports.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Lipschitz Enforcement (WGAN-GP &amp;amp; Spectral Norm)&lt;/strong&gt;: Explains how constraining the discriminator’s gradient norm $|\nabla_{\hat{x}} D(\hat{x})|&lt;em&gt;2 \approx 1$ or bounding layer singular values $\sigma&lt;/em&gt;{\max}(W) = 1$ stabilizes adversarial games.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-jsd-fails-where-wasserstein-1-succeeds-on-parallel-lines&quot;&gt;Worked example: Why JSD Fails Where Wasserstein-1 Succeeds on Parallel Lines&lt;/h3&gt;

&lt;p&gt;Consider two parallel 1D distributions in $\mathbb{R}^2$: real data $p_{\text{data}}$ is uniform on the line $x_1 = 0,\; x_2 \in [0, 1]$, and generated data $p_\theta$ is uniform on the parallel line $x_1 = \theta,\; x_2 \in [0, 1]$ with $\theta &amp;gt; 0$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Jensen–Shannon Divergence $D_{\text{JS}}(p_{\text{data}} | p_\theta)$&lt;/strong&gt;:
For &lt;em&gt;any&lt;/em&gt; $\theta \ne 0$, the two lines have zero overlap, so $D_{\text{JS}}(p_{\text{data}} | p_\theta) = \ln 2 \approx 0.6931$ (constant!). At $\theta = 0$, it jumps discontinuously to $0$.
\(\frac{\partial}{\partial \theta} D_{\text{JS}}(p_{\text{data}} \| p_\theta) = 0 \quad \text{for all } \theta \ne 0.\)
Gradient descent receives &lt;strong&gt;zero signal&lt;/strong&gt; to move $\theta$ toward $0$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Wasserstein-1 Distance $W_1(p_{\text{data}}, p_\theta)$&lt;/strong&gt;:
Moving every point $(\theta, x_2)$ horizontally to $(0, x_2)$ costs distance $|\theta|$, realized by the 1-Lipschitz critic $f(x_1, x_2) = -x_1$:
\(W_1(p_{\text{data}}, p_\theta) = |\theta| \implies \frac{\partial W_1}{\partial \theta} = \operatorname{sign}(\theta) = +1 \quad (\theta &amp;gt; 0).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Moving from JSD to Wasserstein-1 transforms a flat cliff with zero gradient into a clean V-shaped ramp that guides $\theta \to 0$ from any distance.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;generative-adversarial-networks-learning-through-competition&quot;&gt;Generative Adversarial Networks: Learning Through Competition&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://developers.google.com/static/machine-learning/gan/images/gan_diagram.svg&quot; alt=&quot;GAN Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc GAN với Generator và Discriminator. Nguồn: Google Developers&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Generative Adversarial Networks represent one of the most creative and impactful ideas in recent machine learning history. Introduced by Ian Goodfellow and colleagues in 2014, GANs approach generative modeling through an entirely novel paradigm: training two neural networks in competition with each other. A generator network learns to create fake data that looks real, while a discriminator network learns to distinguish real data from the generator’s fakes. As these networks improve through their adversarial game, the generator becomes increasingly skilled at creating realistic outputs, eventually producing samples indistinguishable from real data.&lt;/p&gt;

&lt;p&gt;The elegance and power of this idea is best appreciated by understanding what preceded it. Traditional generative models like Gaussian Mixture Models or Hidden Markov Models required explicit probabilistic formulations and often made restrictive assumptions about data distribution. Variational autoencoders used neural networks but required explicit density models and variational inference. GANs sidestep these complexities entirely. We never explicitly model the probability density \(p(x)\). Instead, we implicitly learn to sample from it through the generator network. This implicit density modeling enables generating high-dimensional, complex data (like realistic images) that would be intractable to model explicitly.&lt;/p&gt;

&lt;p&gt;The adversarial training framework is inspired by game theory, specifically zero-sum games where one player’s gain is another’s loss. The generator tries to fool the discriminator, while the discriminator tries not to be fooled. This creates a natural curriculum: as the discriminator improves at detecting fakes, it provides increasingly challenging training signal to the generator, pushing it to create better fakes. Conversely, as the generator improves, the discriminator must become more discerning. At equilibrium—when the discriminator cannot distinguish real from fake better than random guessing—the generator has learned to perfectly model the data distribution.&lt;/p&gt;

&lt;p&gt;Understanding GANs deeply requires grappling with several conceptual challenges. Training two networks simultaneously in opposition is fundamentally different from standard supervised learning where we optimize a single network. The loss for one network depends on the other network’s parameters, creating a moving target that can lead to instability. Mode collapse—where the generator learns to produce only a few types of outputs rather than capturing the full data diversity—is a persistent challenge. Measuring GAN performance is non-trivial since we can’t simply evaluate likelihood (we don’t have an explicit density model). These challenges make GANs notoriously difficult to train, requiring careful architecture design, loss function choices, and training tricks accumulated through years of research.&lt;/p&gt;

&lt;p&gt;Yet the results speak for themselves. GANs can generate photorealistic faces that don’t exist, transform horses into zebras, create art in specific styles, upscale low-resolution images, and countless other applications. The quality of GAN-generated images often exceeds VAEs and other generative approaches. This practical success, despite training difficulties, has made GANs one of the most active research areas in deep learning, with hundreds of variants proposed to stabilize training, improve quality, or enable new applications. Understanding the original GAN framework provides foundation for appreciating this vast landscape of extensions and applications.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;The mathematical framework of GANs is based on a minimax game between generator and discriminator. Let’s build this up carefully, understanding each component’s role and how they interact.&lt;/p&gt;

&lt;p&gt;The generator \(G\) is a neural network that maps random noise \(\mathbf{z}\) sampled from a simple distribution (typically \(\mathbf{z} \sim \mathcal{N}(0, I)\)) to fake data:&lt;/p&gt;

\[\mathbf{x}_{\text{fake}} = G(\mathbf{z}; \theta_G)\]

&lt;p&gt;where \(\theta_G\) represents generator parameters. The noise vector \(\mathbf{z}\) serves as the source of variation—different noise vectors should produce different fake samples, and the generator learns to map the noise distribution to the data distribution.&lt;/p&gt;

&lt;p&gt;The discriminator \(D\) is a neural network that takes an input \(\mathbf{x}\) (either real data or generator output) and outputs a probability that it’s real:&lt;/p&gt;

\[D(\mathbf{x}; \theta_D) \in [0, 1]\]

&lt;p&gt;where \(\theta_D\) represents discriminator parameters. Typically \(D\) ends with a sigmoid activation: \(D(\mathbf{x}) = \sigma(f_{\theta_D}(\mathbf{x}))\) where \(f\) is the discriminator’s feature extractor (convolutional layers, etc.).&lt;/p&gt;

&lt;p&gt;The training objective is formulated as a minimax game:&lt;/p&gt;

\[\min_G \max_D V(D, G) = \mathbb{E}_{\mathbf{x} \sim p_{\text{data}}}[\log D(\mathbf{x})] + \mathbb{E}_{\mathbf{z} \sim p_z}[\log(1 - D(G(\mathbf{z})))]\]

&lt;p&gt;Let’s parse this carefully. The discriminator wants to maximize \(V\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbb{E}_{\mathbf{x} \sim p_{\text{data}}}[\log D(\mathbf{x})]\): Assign high probability to real data (\(D(\mathbf{x}) \to 1\), so \(\log D(\mathbf{x}) \to 0\))&lt;/li&gt;
  &lt;li&gt;\(\mathbb{E}_{\mathbf{z} \sim p_z}[\log(1 - D(G(\mathbf{z})))]\): Assign low probability to fakes (\(D(G(\mathbf{z})) \to 0\), so \(\log(1-D(G(\mathbf{z}))) \to 0\))&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The generator wants to minimize \(V\), specifically minimize \(\mathbb{E}_{\mathbf{z}}[\log(1 - D(G(\mathbf{z})))]\), making the discriminator assign high probability to its fakes.&lt;/p&gt;

&lt;p&gt;However, in practice, minimizing \(\log(1-D(G(\mathbf{z})))\) causes problems early in training when the generator is poor and \(D(G(\mathbf{z})) \approx 0\). The gradient of \(\log(1-D(G(\mathbf{z})))\) with respect to generator parameters is very small when \(D(G(\mathbf{z}))\) is small, providing weak learning signal exactly when the generator needs to improve most. The solution is a non-saturating variant: instead of minimizing \(\log(1-D(G(\mathbf{z})))\), maximize \(\log D(G(\mathbf{z}))\). These aren’t equivalent—the second provides much stronger gradients when \(D(G(\mathbf{z}))\) is small.&lt;/p&gt;

&lt;p&gt;The training alternates between discriminator and generator updates:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discriminator update&lt;/strong&gt; (maximize \(V\) with respect to \(\theta_D\)):&lt;/p&gt;

\[\theta_D \leftarrow \theta_D + \eta_D \nabla_{\theta_D} \left[\frac{1}{m}\sum_{i=1}^m \log D(\mathbf{x}^{(i)}) + \log(1-D(G(\mathbf{z}^{(i)})))\right]\]

&lt;p&gt;&lt;strong&gt;Generator update&lt;/strong&gt; (minimize \(V\) with respect to \(\theta_G\), using non-saturating objective):&lt;/p&gt;

\[\theta_G \leftarrow \theta_G - \eta_G \nabla_{\theta_G} \left[\frac{1}{m}\sum_{i=1}^m \log D(G(\mathbf{z}^{(i)}))\right]\]

&lt;p&gt;The gradients for the generator pass through the discriminator: \(\nabla_{\theta_G} D(G(\mathbf{z}))\) requires backpropagating through both \(G\) and \(D\). This coupling means generator training depends critically on discriminator providing meaningful gradients—if the discriminator is too perfect (always correctly identifying fakes), gradients vanish; if too poor (can’t distinguish real from fake), gradients are misleading.&lt;/p&gt;

&lt;p&gt;This delicate balance motivates various training strategies. We might train the discriminator \(k\) times per generator update (typically \(k=1\) or \(5\)), ensuring it stays ahead of the generator. We might add instance noise to discriminator inputs early in training, making its task harder and preventing it from becoming too strong too quickly. We might use different learning rates for generator and discriminator (often \(\eta_G &amp;lt; \eta_D\)) to control their relative improvement rates.&lt;/p&gt;

&lt;p&gt;At the theoretical equilibrium where \(p_G = p_{\text{data}}\) (generator distribution equals data distribution), the optimal discriminator is \(D^*(\mathbf{x}) = \frac{p_{\text{data}}(\mathbf{x})}{p_{\text{data}}(\mathbf{x}) + p_G(\mathbf{x})} = 0.5\) everywhere—it cannot distinguish real from fake. At this point, both loss terms equal \(\log(0.5)\), and neither network can improve by changing. This equilibrium corresponds to the generator perfectly modeling the data distribution.&lt;/p&gt;

&lt;p&gt;However, reaching this equilibrium in practice is challenging. The training dynamics can cycle, oscillate, or diverge. Mode collapse occurs when the generator discovers it can fool the discriminator by generating only a subset of the data distribution (modes)—if producing only digit “1” fools the discriminator, why bother learning to generate other digits? Various regularization techniques (minibatch discrimination, unrolled optimization, spectral normalization) address these instabilities, showing that successful GAN training requires understanding the adversarial dynamics deeply, not just implementing the basic algorithm.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;To build intuition for the adversarial training process, imagine a scenario with counterfeit money (generator) and bank inspector (discriminator). Initially, the counterfeiter produces poor fakes—perhaps using a home printer that makes obviously fake bills. The inspector easily identifies these as fake (discriminator outputs near 0 for generator samples). This clear signal tells the counterfeiter what’s wrong—the texture is wrong, colors are off, security features are missing.&lt;/p&gt;

&lt;p&gt;The counterfeiter improves, using better equipment and studying real bills more carefully. Now fakes are harder to detect—maybe they pass casual inspection but fail under UV light. The inspector learns to check UV features (discriminator learns more sophisticated detection). This pushes the counterfeiter to replicate UV features too.&lt;/p&gt;

&lt;p&gt;This arms race continues. Each improvement by one side forces the other to improve. Eventually, the counterfeiter creates bills so convincing that even expert inspection cannot reliably distinguish them from real bills—the equilibrium where \(D(\mathbf{x}) = 0.5\). At this point, the counterfeiter has learned to generate perfect currency.&lt;/p&gt;

&lt;p&gt;The GAN training dynamic follows this pattern. Let’s trace through early training on generating MNIST digits:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iteration 1-10&lt;/strong&gt; (Generator is terrible):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Generator produces noise that vaguely resembles digit shapes&lt;/li&gt;
  &lt;li&gt;Discriminator easily detects fakes (outputs near 0)&lt;/li&gt;
  &lt;li&gt;Strong gradients tell generator: “make sharper edges,” “center the digit,” “use correct aspect ratio”&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Iteration 100-500&lt;/strong&gt; (Generator is improving):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Generator produces digit-like shapes, but wrong proportions or artifacts&lt;/li&gt;
  &lt;li&gt;Discriminator learns subtle features distinguishing real from fake&lt;/li&gt;
  &lt;li&gt;Maybe real 3s have specific curve ratios that fakes miss&lt;/li&gt;
  &lt;li&gt;Generator learns to match these statistics&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Iteration 1000+&lt;/strong&gt; (Approaching equilibrium):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Generator produces convincing digits&lt;/li&gt;
  &lt;li&gt;Discriminator performance approaches 50% accuracy&lt;/li&gt;
  &lt;li&gt;Each generated sample looks like it could be from MNIST&lt;/li&gt;
  &lt;li&gt;Latent space has structure: different \(\mathbf{z}\) produces different digits&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A concrete example with numbers: suppose at some training iteration, we generate a fake digit and the discriminator outputs \(D(G(\mathbf{z})) = 0.3\). The discriminator is somewhat confident this is fake (30% probability of real). The generator’s loss is \(-\log(0.3) = 1.20\). Gradients indicate how to change generator parameters to increase \(D(G(\mathbf{z}))\) toward 1. The generator learns to adjust its outputs to fool this particular discriminator configuration.&lt;/p&gt;

&lt;p&gt;Meanwhile, the discriminator sees both this fake (which it correctly identified with 70% confidence) and real digits (which it should assign high probability). Suppose on a real digit, it outputs \(D(\mathbf{x}_{\text{real}}) = 0.95\)—correctly identifying real data with 95% confidence. Its loss combines both: \(-\log(0.95) - \log(1-0.3) = 0.05 + 0.36 = 0.41\). Gradients tell it how to better separate real from fake distributions.&lt;/p&gt;

&lt;p&gt;The adversarial dynamic is that the generator’s improvement makes the discriminator’s task harder (fakes become more convincing), while the discriminator’s improvement makes the generator’s task harder (must create more realistic fakes to fool a better detector). This mutual improvement drives both toward high capability.&lt;/p&gt;

&lt;p&gt;Mode collapse manifests distinctly. Suppose the generator discovers that producing “1”s consistently fools the discriminator (maybe because “1” is simple and the discriminator hasn’t learned to detect fake “1”s yet). The generator might converge to producing only “1”s or a few “1”-like outputs, ignoring the rest of the digit manifold. The discriminator eventually learns to detect these specific fake “1”s, but by then the generator might have mode-collapsed to a different digit. The training never achieves the equilibrium where all modes are covered. Various techniques address this: minibatch discrimination lets the discriminator detect lack of diversity, unrolled optimization allows the generator to anticipate discriminator’s response, and architectural choices can encourage diversity.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=Gib_kiXgnvA&quot;&gt;The Math Behind Generative Adversarial Networks Clearly Explained!&lt;/a&gt; — Normalized Nerd, English. The minimax objective and why the optimal discriminator recovers a divergence.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, English. The same objective with the two networks drawn.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, English. Mode collapse and unstable training as the theory’s practical consequences.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>14 Generative Adversarial Networks (GANs)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter14/14_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter14/14_00_Introduction</id>
   <content type="html">&lt;p&gt;Legend has it that Generative Adversarial Networks were born in a Montreal bar in 2014, when Ian Goodfellow argued with friends that instead of trying to write down an explicit probability formula for a photograph, you could train two neural networks in an endless game of cat and mouse: a counterfeiter (Generator) trying to forge convincing currency and a detective (Discriminator) trying to spot the fakes. When Goodfellow coded the idea at midnight, it worked on the very first try—launching a decade of photorealistic synthesis and game-theoretic deep learning.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-architecture-of-adversarial-generation&quot;&gt;Key ideas: The Architecture of Adversarial Generation&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Two-Player Minimax Game Theory&lt;/strong&gt;: Frames generative learning as a saddle-point problem $\min_G \max_D V(D, G)$ whose Nash equilibrium occurs when $p_G = p_{\text{data}}$ and $D^*(x) = 1/2$ everywhere.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Implicit Pushforward Sampling&lt;/strong&gt;: Maps low-dimensional noise $z \sim \mathcal{N}(0, I)$ directly to high-dimensional images $G_\theta(z)$ in a single forward pass, bypassing explicit pixel likelihoods and avoiding MSE blur.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Divergence Geometry (JSD vs. Wasserstein)&lt;/strong&gt;: Connects the classical GAN objective to Jensen–Shannon divergence and explains why Wasserstein distance (WGAN) fixes vanishing gradients when $p_{\text{data}}$ and $p_G$ have disjoint supports.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Adversarial Training Dynamics&lt;/strong&gt;: Illuminates why alternating gradient descent can oscillate, collapse onto a few modes, or blow up without architectural stabilizers like spectral normalization, gradient penalties, and balanced update schedules.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-the-optimal-discriminator-dx-at-three-points&quot;&gt;Worked example: Computing the Optimal Discriminator $D^*(x)$ at Three Points&lt;/h3&gt;

&lt;p&gt;For a fixed generator $G$, the optimal discriminator at any point $x$ is $D^*(x) = \frac{p_{\text{data}}(x)}{p_{\text{data}}(x) + p_G(x)}$. Suppose at three locations $x_A, x_B, x_C$, the densities are:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;$x_A$: $p_{\text{data}} = 0.6,\; p_G = 0.2$&lt;/li&gt;
  &lt;li&gt;$x_B$: $p_{\text{data}} = 0.3,\; p_G = 0.3$&lt;/li&gt;
  &lt;li&gt;$x_C$: $p_{\text{data}} = 0.1,\; p_G = 0.5$&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate $D^*(x)$ at each point&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;$D^*(x_A) = \frac{0.6}{0.6 + 0.2} = 0.75$ (looks real; generator should push more mass here).&lt;/li&gt;
      &lt;li&gt;$D^*(x_B) = \frac{0.3}{0.3 + 0.3} = 0.50$ (perfectly indistinguishable!).&lt;/li&gt;
      &lt;li&gt;$D^*(x_C) = \frac{0.1}{0.1 + 0.5} = 0.1667$ (looks fake; generator should pull mass away).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the equilibrium minimax value when $p_G = p_{\text{data}}$ everywhere ($D^*(x) = 0.5$)&lt;/strong&gt;:
\(V(D^*, G^*) = \ln(0.5) + \ln(1 - 0.5) = -2\ln 2 \approx -1.3863\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: The discriminator’s score is literally a density-ratio estimator $\frac{p_{\text{data}}}{p_{\text{data}} + p_G}$, and when training succeeds, the detective is reduced to flipping a fair coin ($0.5$) everywhere.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Generative Adversarial Networks (GANs) pit two networks against each other: a generator creates fake data and a discriminator tries to distinguish real from fake. This adversarial training produces remarkably realistic images. This chapter covers GAN training, loss functions, common architectures (DCGAN, StyleGAN), training challenges, and applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After GAN training, see &lt;strong&gt;14-99 Modern Applications and Updates&lt;/strong&gt; for StyleGAN3, GigaGAN, and when adversarial models still beat diffusion.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, English. Generator and discriminator as a two-player game are this chapter.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Gib_kiXgnvA&quot;&gt;The Math Behind Generative Adversarial Networks Clearly Explained!&lt;/a&gt; — Normalized Nerd, English. The minimax math the friendly introduction is pointing at.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TpMIssRdhco&quot;&gt;What are GANs (Generative Adversarial Networks)?&lt;/a&gt; — IBM Technology, English. A short picture of the same game if you want the cast of characters only.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>13-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter13/13_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter13/13_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;If you open the checkpoint of Stable Diffusion, Flux, Sora, or modern video generators, you will find a surprisingly familiar component right at the entrance and exit: a KL-regularized Variational Autoencoder. Rather than generating pixels directly, today’s frontier generative systems split the problem in two—a VAE handles perceptual compression into a compact continuous latent tensor, while a diffusion or flow-matching Transformer models global semantics in that latent space.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-vaes-in-modern-multimodal-systems-20222026&quot;&gt;Key ideas: VAEs in Modern Multimodal Systems (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Perceptual Latent VAEs (KL-f8 / SDXL / Flux)&lt;/strong&gt;: Uses a very tiny KL weight ($\beta \approx 10^{-6}$) plus LPIPS and PatchGAN losses so the VAE preserves crisp high-frequency textures while keeping latents smoothly Gaussian for downstream diffusion.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Spatiotemporal 3D Causal VAEs for Video&lt;/strong&gt;: Compresses video tensors $(T, H, W, 3)$ across both time (e.g., $4\times$) and space ($8\times \times 8\times$) using causal 3D convolutions so frames can be decoded streamingly without future leakage.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Latent Scaling Factors&lt;/strong&gt;: Normalizes encoded latents by an empirical scale factor $s$ (e.g., $0.18215$ in SD 1.5) so latent variance equals $1.0$, aligning perfectly with standard diffusion noise schedules.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Channel Width vs. Reconstruction Trade-off&lt;/strong&gt;: Explains why modern VAEs increased latent channels from $4$ (SD 1.5) to $16$ (SD3 / Flux)—dramatically improving small text, faces, and fine edges.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-spatiotemporal-compression-factor-of-a-video-vae&quot;&gt;Worked example: Spatiotemporal Compression Factor of a Video VAE&lt;/h3&gt;

&lt;p&gt;Consider a 1-second HD video clip of $T = 25$ frames at resolution $H = 512, W = 512$ with $C = 3$ RGB channels, encoded by a causal 3D VAE with temporal stride $4$ (keeping the first frame separate: $1 + (T-1)/4$), spatial stride $8$, and $C_z = 16$ latent channels.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Raw video tensor size&lt;/strong&gt;:
\(25 \times 512 \times 512 \times 3 = 19{,}660{,}800\text{ scalar values}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compressed latent tensor dimensions&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Temporal frames: $T_z = 1 + \frac{25 - 1}{4} = 7$.&lt;/li&gt;
      &lt;li&gt;Spatial size: $H_z = 512/8 = 64$, $W_z = 512/8 = 64$.&lt;/li&gt;
      &lt;li&gt;Total latent scalars: $7 \times 64 \times 64 \times 16 = 458{,}752$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Overall compression ratio&lt;/strong&gt;:
\(\frac{19{,}660{,}800}{458{,}752} \approx 42.86\times\text{ fewer scalars},\)
and spatiotemporal tokens (with $2 \times 2$ ViT patching) drop to $7 \times 32 \times 32 = 7{,}168$ tokens—small enough for full 3D self-attention on a single GPU.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Modern VAEs are no longer standalone blurry image generators; they are the ultra-efficient perceptual codecs that make megapixel image and video synthesis tractable.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-vaes-as-latents-for-diffusion-video-and-compression&quot;&gt;Optional: VAEs as latents for diffusion, video, and compression&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace ELBO, reparameterization, or the VAE implementation. It shows how the same variational autoencoder became the &lt;strong&gt;codec&lt;/strong&gt; in 2022–2026 generative systems.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The ELBO&lt;/p&gt;

\[\mathcal{L}(\theta,\phi) = \mathbb{E}_{q_\phi(z|x)}[\log p_\theta(x|z)] - D_{\mathrm{KL}}(q_\phi(z|x)\,\|\,p(z))\]

&lt;p&gt;is still the right objective. Products rarely sample “faces from \(z\sim\mathcal{N}(0,I)\)” anymore; they train a VAE so a &lt;strong&gt;second&lt;/strong&gt; model (diffusion or a Transformer) can work in \(z\)-space.&lt;/p&gt;

&lt;h2 id=&quot;1-the-stable-diffusion-vae&quot;&gt;1. The Stable Diffusion VAE&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;Rombach et al., 2022&lt;/a&gt; train a KL-regularized autoencoder (often called &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AutoencoderKL&lt;/code&gt;) whose latent is a downsampled spatial grid, not a single vector. The KL term is the Chapter 13 regularizer; perceptual + adversarial terms keep reconstructions sharp enough for a denoiser. Almost every open text-to-image pipeline still ships this pattern (SD, SDXL, many SD3-class stacks).&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;video-and-3d-latents&quot;&gt;Video and 3D latents&lt;/h3&gt;

&lt;p&gt;Stable Video Diffusion and later video models reuse image VAEs or train &lt;strong&gt;temporal&lt;/strong&gt; VAEs so the expensive denoiser sees fewer tokens. The math is the same encoder–decoder + KL; the engineering is 3D/causal convs.&lt;/p&gt;

&lt;h3 id=&quot;consistency-and-one-step-generators-in-latent-space&quot;&gt;Consistency and one-step generators in latent space&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.01469&quot;&gt;Song et al., 2023&lt;/a&gt; (consistency models) and later latent consistency (LCM) distill a diffusion ODE in the VAE latent. The VAE is frozen; the new work is the sampler. This is why Chapter 13 still matters after diffusion “won.”&lt;/p&gt;

&lt;h3 id=&quot;representation-learning&quot;&gt;Representation learning&lt;/h3&gt;

&lt;p&gt;\(\beta\)-VAE-style disentanglement is less fashionable than in 2018, but &lt;strong&gt;variational&lt;/strong&gt; bottlenecks still appear in world models (DreamerV3, Chapter 21 optional) and compression.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/diffusers&quot;&gt;diffusers&lt;/a&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AutoencoderKL&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AutoencoderTiny&lt;/code&gt; (TAESD).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://huggingface.co/stabilityai&quot;&gt;Stability-AI SD VAE checkpoints&lt;/a&gt; on the Hub.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/openai/consistency_models&quot;&gt;openai/consistency_models&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;High-Resolution Image Synthesis with Latent Diffusion Models (Rombach et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2303.01469&quot;&gt;Consistency Models (Song et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2403.03206&quot;&gt;Scaling Rectified Flow Transformers — SD3 (Esser et al., 2024)&lt;/a&gt; — still a latent autoencoder + flow.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Derive the ELBO and the reparameterization trick first. This lesson only shows &lt;strong&gt;where \(z\) is consumed&lt;/strong&gt; in 2022–2026 products — not a new evidence lower bound.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=J87hffSMB60&quot;&gt;How does Stable Diffusion work? – Latent Diffusion Models EXPLAINED&lt;/a&gt; — AI Coffee Break with Letitia, English. The Stable Diffusion VAE is the deployed descendant this note describes.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, English. The ELBO that VAE still trains, even when it is only a compressor in front of diffusion.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But how do AI images and videos actually work?&lt;/td&gt;
          &lt;td&gt;Guest video by Welch Labs](https://www.youtube.com/watch?v=iv-5mZ_9CPY) — 3Blue1Brown, English. What the diffusion model does with the VAE’s latent.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>13-01 Variational Autoencoders</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter13/13_01_VAE_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter13/13_01_VAE_Fundamentals</id>
   <content type="html">&lt;p&gt;Variational Autoencoders sit at the intersection of Bayesian statistics and deep neural networks. By replacing deterministic bottleneck codes with learned probability distributions, VAEs turn compression into principled density modeling—giving you a single framework that can reconstruct, interpolate, detect anomalies, and synthesize new data.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-roadmap-to-vae-mastery&quot;&gt;Key ideas: Roadmap to VAE Mastery&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Probabilistic Encoder–Decoder Duality&lt;/strong&gt;: Views the encoder $q_\phi(z \mid x)$ as an inference network and the decoder $p_\theta(x \mid z)$ as a generative likelihood model.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — The ELBO Objective&lt;/strong&gt;: Unifies reconstruction fidelity and latent regularization into a single lower bound on $\log p_\theta(x)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Differentiable Sampling&lt;/strong&gt;: Uses the reparameterization trick so standard backpropagation trains stochastic latent layers end-to-end.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Diagnostics &amp;amp; Practical Tuning&lt;/strong&gt;: Connects theoretical failure modes (posterior collapse, blurry MSE reconstructions) directly to code-level remedies (KL annealing, balanced reductions).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-mapping-uniform-grid-coordinates-to-a-2d-gaussian-prior-via-inverse-cdf&quot;&gt;Worked example: Mapping Uniform Grid Coordinates to a 2D Gaussian Prior via Inverse CDF&lt;/h3&gt;

&lt;p&gt;To visualize a 2D VAE latent space cleanly, we sample uniformly spaced quantiles $u \in {0.1, 0.5, 0.9}$ along each axis and map them through the standard normal inverse CDF $\Phi^{-1}(u)$ instead of spacing linearly in $[-3, 3]$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute exact Gaussian quantiles&lt;/strong&gt;:
\(\Phi^{-1}(0.1) \approx -1.2816, \qquad \Phi^{-1}(0.5) = 0.0000, \qquad \Phi^{-1}(0.9) \approx +1.2816.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Form the $3 \times 3$ equal-probability-mass grid&lt;/strong&gt;:
Each cell corresponds to an equal slice of prior probability mass under $\mathcal{N}(0, I_2)$, with corner codes $(\pm 1.2816, \pm 1.2816)$ and center $(0, 0)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare density at corner vs. linear grid corner $(3.0, 3.0)$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;At $(1.2816, 1.2816)$: $p(z) = \frac{1}{2\pi}e^{-(1.2816^2)} \approx 0.0308$.&lt;/li&gt;
      &lt;li&gt;At $(3.0, 3.0)$: $p(z) = \frac{1}{2\pi}e^{-9} \approx 1.96 \times 10^{-5}$ ($1{,}570\times$ sparser—far outside training support!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Sampling latent grids via $\Phi^{-1}(u)$ keeps every decoded visualization inside the high-density region of the prior where the decoder was actually trained.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Variational autoencoders:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Theory&lt;/strong&gt; — ELBO, reparameterization, intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implementation&lt;/strong&gt; — training, sampling, papers, pitfalls&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, English. Before the theory and code split.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. The lecture version of the same graphical model.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vPvnpC0PNVQ&quot;&gt;MaDL - Kullback-Leibler Divergence&lt;/a&gt; — Tübingen Machine Learning, English. The KL term those lessons will not let you skip.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>13-01-02 VAE Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter13/13_01_02_VAE_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter13/13_01_02_VAE_Implementation</id>
   <content type="html">&lt;p&gt;Implementing a VAE in PyTorch looks deceptively short—barely 40 lines of code—yet three subtle details separate a clean generative model from a broken one: predicting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logvar&lt;/code&gt; instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sigma&lt;/code&gt; for numerical stability, matching the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reduction=&apos;sum&apos;&lt;/code&gt; scale between reconstruction loss and KL divergence, and keeping &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reparameterize&lt;/code&gt; deterministic (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;z = mu&lt;/code&gt;) at evaluation time when you want reproducible reconstructions.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-building-a-production-clean-vae-in-pytorch&quot;&gt;Key ideas: Building a Production-Clean VAE in PyTorch&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Log-Variance Parameterization&lt;/strong&gt;: Outputs $\log \sigma^2 \in (-\infty, +\infty)$ from an unconstrained linear layer and recovers $\sigma = \exp(\tfrac{1}{2}\log\sigma^2)$, guaranteeing positivity and preventing gradient explosions near $\sigma = 0$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Consistent Loss Reduction (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sum&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean&lt;/code&gt;)&lt;/strong&gt;: Sums both pixel-level BCE/MSE and latent-dimension KL per sample before averaging across the batch, preserving the true ELBO balance.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — KL Annealing / Warm-Up&lt;/strong&gt;: Gradually ramps the KL weight $\beta$ from $0 \to 1$ during early epochs so the encoder establishes useful latent structure before the prior penalty squeezes it toward $\mathcal{N}(0, I)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Latent Manifold Traversal &amp;amp; Sampling&lt;/strong&gt;: Verifies generalization by sampling fresh $z \sim \mathcal{N}(0, I)$ and plotting 2D grids via inverse Gaussian CDF quantiles $\Phi^{-1}(u)$.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-tracing-tensor-operations--loss-scaling-in-a-mini-batch-of-2-images&quot;&gt;Worked example: Tracing Tensor Operations &amp;amp; Loss Scaling in a Mini-Batch of 2 Images&lt;/h3&gt;

&lt;p&gt;Suppose a batch has $B = 2$ images, each with $D = 784$ pixels and latent size $K = 2$. For sample 1, per-pixel BCE sum is $110.0$ and KL sum is $8.0$. For sample 2, per-pixel BCE sum is $130.0$ and KL sum is $12.0$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Correct ELBO batch loss (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sum&lt;/code&gt; over features, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean&lt;/code&gt; over batch)&lt;/strong&gt;:
\(\mathcal{L}_{\text{correct}} = \frac{(110.0 + 8.0) + (130.0 + 12.0)}{2} = \frac{118.0 + 142.0}{2} = 130.0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Buggy loss (mixing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;F.binary_cross_entropy(..., reduction=&apos;mean&apos;)&lt;/code&gt; with summed KL)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Mean BCE across $2 \times 784 = 1{,}568$ pixels: $\frac{110 + 130}{1568} = 0.1531$.&lt;/li&gt;
      &lt;li&gt;Mean KL per sample: $\frac{8 + 12}{2} = 10.0$.&lt;/li&gt;
      &lt;li&gt;Effective KL weight relative to reconstruction becomes $\beta_{\text{eff}} = 784$! The encoder immediately collapses $\mu \to 0, \sigma \to 1$ to crush the $10.0$ KL term, producing identical blurry gray digits for every input.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Logvar clamping stability check&lt;/strong&gt;: If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logvar = -4.0&lt;/code&gt;, then &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;std = torch.exp(0.5 * (-4.0)) = exp(-2.0) = 0.1353&lt;/code&gt;, safely positive with smooth derivative.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Always verify that reconstruction and KL terms are summed over their respective feature/latent axes before dividing by batch size $B$.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Let’s implement a complete VAE with all mathematical components explicit:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VAE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Variational Autoencoder for MNIST.
    
    Architecture:
    - Encoder: maps images to latent distribution parameters (μ, σ)
    - Sampler: reparameterization trick for backpropagation through sampling
    - Decoder: maps latent codes to reconstructed images
    
    Loss: ELBO = reconstruction + KL divergence
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;VAE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Encoder: outputs parameters of Gaussian distribution
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# We output both μ and log(σ²) rather than σ for numerical stability
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# (σ must be positive, easier to ensure with exp(log σ²))
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Separate layers for mean and log-variance
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# This allows encoder to learn both independently
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc_mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc_logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Decoder: maps latent code to reconstruction
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Output in [0,1] for pixel values
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Encode input to latent distribution parameters.
        
        Returns:
            mu: mean of q(z|x)
            logvar: log variance of q(z|x)
        
        We return log variance instead of variance/std for numerical stability.
        Variance must be positive, so we can ensure this by exponentiating logvar.
        This is more stable than directly predicting σ and squaring it.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc_mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc_logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;reparameterize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Reparameterization trick: z = μ + σ⊙ε where ε ~ N(0,I)
        
        This is THE key innovation making VAEs trainable with backprop.
        Instead of sampling z ~ N(μ,σ²) (not differentiable w.r.t. μ,σ),
        we express z as a deterministic function of μ,σ and external randomness ε.
        
        Gradients can flow through μ and σ to encoder parameters, enabling
        end-to-end training via standard backpropagation.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Compute standard deviation from log variance
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# std = exp(log(σ²) / 2) = exp(logvar / 2)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Sample epsilon from standard normal
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# During training: random. During generation: can use specific ε
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Reparameterized sample: z = μ + σ * ε
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Map latent code to reconstruction&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Full VAE forward pass.
        
        Returns:
            recon: reconstructed input
            mu: latent mean (for KL computation)
            logvar: latent log-variance (for KL computation)
        
        We return mu and logvar separately because we need them to compute
        the KL divergence in the loss function.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reparameterize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Generate new samples by sampling from prior and decoding.
        
        This is how we use the trained VAE for generation:
        1. Sample z ~ N(0, I) (the prior)
        2. Decode to get x
        
        Because we regularized q(z|x) to be close to N(0,I) during training,
        samples from N(0,I) should decode to realistic outputs.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;vae_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    VAE loss: negative ELBO = reconstruction loss + KL divergence
    
    Args:
        recon_x: reconstructed input
        x: original input
        mu: latent mean from encoder
        logvar: latent log-variance from encoder
        beta: weight for KL term (β-VAE uses β≠1 for disentanglement)
    
    The loss has two terms:
    1. Reconstruction: how well we reconstruct input
    2. KL: how much encoder distribution differs from prior
    
    We want to minimize both: good reconstruction AND latent distribution
    close to prior.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Reconstruction loss (binary cross-entropy for images in [0,1])
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Treating each pixel as independent Bernoulli
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;BCE&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binary_cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reduction&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# KL divergence KL(N(μ,σ²) \| N(0,I))
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Has closed form: 0.5 * Σ(μ² + σ² - log(σ²) - 1)
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# We have logvar = log(σ²), so σ² = exp(logvar)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;KLD&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Total loss (negative ELBO)
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Minimizing this is equivalent to maximizing ELBO
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;BCE&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;KLD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;BCE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;KLD&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training VAE
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Variational Autoencoder on MNIST&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Load data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ToTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create VAE
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VAE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;VAE Architecture:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Input dimension: 784 (28×28)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Latent dimension: 20 (compression factor: 39×)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Total parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training loop
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training VAE...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_bce&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_kld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Flatten images
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute loss
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;vae_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;train_bce&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bce&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;train_kld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kld&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Average over batches
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;n_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Per sample
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;avg_bce&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_bce&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;avg_kld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_kld&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Recon = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_bce&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, KL = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_kld&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;VAE Training Complete - Analyzing Results&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test reconstruction
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Encode (using mean, ignoring variance for determinism)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Reconstruct
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Measure reconstruction error
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;recon_error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Test reconstruction MSE: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_error&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Analyze latent space statistics
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Latent space statistics (should be ~N(0,1) due to KL penalty):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (first 5 dims)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Std:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Overall mean magnitude: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Overall std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logvar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate new samples
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generating New Samples from VAE&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Sample from prior N(0,I)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; samples by sampling z ~ N(0,I)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (64, 784)
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Check sample statistics
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated sample mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (should be ~0.5)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated sample std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Reshape for visualization
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;samples_img&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Reshaped for visualization: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_img&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate interpolation
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Latent Space Interpolation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Take two test images
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;img1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;img2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Encode to latent means
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mu1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mu2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Interpolating between two images in latent space:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Interpolate
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mu2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;img_interp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Print every other step
&lt;/span&gt;            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  t=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Generated interpolation image &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Interpolation should be smooth due to latent space regularization!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This is a key advantage of VAE over vanilla autoencoders.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate β-VAE (varying KL weight)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β-VAE: Controlling Disentanglement&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;By varying β (weight on KL term), we control tradeoffs:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  β &amp;lt; 1: Prioritize reconstruction (sharper but less disentangled)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  β = 1: Standard VAE (balanced)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  β &amp;gt; 1: Prioritize latent regularity (more disentangled, blurrier)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;β-VAE with β=4-10 often learns more interpretable latent dimensions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;where each dimension captures one semantic factor (size, rotation, etc.)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;The relationship between VAEs and standard autoencoders illuminates what the probabilistic framework adds. Both use encoder-decoder architectures and reconstruction losses, but VAEs add: (1) probabilistic encodings (distributions rather than points), (2) the KL divergence regularization term, (3) the ability to sample for generation. These differences stem from VAEs being principled probabilistic models optimizing a lower bound on likelihood, while autoencoders are simply dimensionality reduction with a bottleneck. The probabilistic perspective provides theoretical guarantees: VAEs are approximately maximizing data likelihood, ensuring generated samples should be realistic if training succeeds. Autoencoders have no such guarantee—they minimize reconstruction error, which doesn’t directly translate to generating good samples.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;VAEs connect deeply to variational inference, a general technique in Bayesian statistics for approximating intractable posterior distributions. The idea is always the same: we have a model \(p(\mathbf{x}, \mathbf{z})\) but cannot compute $$p(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(exactly, so we approximate it with a simpler distribution\)q(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(from a tractable family (here, factorized Gaussians). We optimize the approximation by maximizing the ELBO, which lower-bounds the quantity we actually care about (log-likelihood). VAEs made variational inference scalable to high-dimensional problems through: (1) using neural networks for\)q\(and\)p$$, providing enormous flexibility, (2) the reparameterization trick enabling gradient-based optimization, (3) stochastic optimization allowing mini-batch training. Understanding VAEs through the variational inference lens connects them to a rich statistical tradition and motivates extensions like importance-weighted VAEs or hierarchical VAEs.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The connection to information theory provides another perspective. The ELBO can be written:&lt;/p&gt;

\[\text{ELBO} = \mathbb{E}_{q_\phi(\mathbf{z}|\mathbf{x})}[\log p_\theta(\mathbf{x}|\mathbf{z})] - KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z}))\]

\[= -H_{q_\phi}(p_\theta(\mathbf{x}|\mathbf{z})) - KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z}))\]

&lt;p&gt;The first term is negative conditional entropy—favoring decoders that confidently reconstruct given latent codes (low uncertainty). The KL term measures information cost of using \(q_\phi\) instead of the prior \(p\). This information-theoretic view suggests VAEs trade off between reconstruction fidelity and compression (low information latent codes), a perspective formalized in the β-VAE framework where we explicitly control this tradeoff with \(\beta\).&lt;/p&gt;

&lt;p&gt;VAEs relate to normalizing flows through their treatment of latent variables. Both use latent variables \(\mathbf{z}\) and learn mappings to data \(\mathbf{x}\). However, flows use invertible, deterministic mappings with tractable Jacobians, enabling exact likelihood. VAEs use flexible neural networks for encoder/decoder but approximate the likelihood through ELBO. Flows provide exact inference but require constrained architectures. VAEs allow flexible architectures but provide approximate inference. This tradeoff shapes their respective application domains: flows for exact density modeling, VAEs for flexible generation with stable training.&lt;/p&gt;

&lt;p&gt;Finally, VAEs connect to representation learning and disentanglement. A disentangled representation has individual latent dimensions corresponding to independent factors of variation (for faces: one dimension for pose, another for lighting, another for identity). VAEs’ factorized Gaussian posterior encourages independence between latent dimensions, and β-VAEs with \(\beta &amp;gt; 1\) further encourage disentanglement by more strongly penalizing KL divergence. Learning disentangled representations is valuable beyond generation: downstream tasks benefit from interpretable, factorized features where we can manipulate specific attributes independently. Understanding how VAE training encourages disentanglement connects to broader questions about what constitutes good representations and how to discover them through unsupervised learning.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.6114&quot;&gt;“Auto-Encoding Variational Bayes” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Diederik P. Kingma, Max Welling&lt;br /&gt;
This foundational paper introduced VAEs and made variational inference practical for deep learning through the reparameterization trick. Kingma and Welling showed that by expressing sampling as \(\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon}\) where \(\boldsymbol{\epsilon} \sim \mathcal{N}(0,I)\), we can backpropagate through stochastic computation, enabling gradient-based optimization of the ELBO. The paper provided clear mathematical derivations, proposed practical implementation details (using Gaussian encoders/decoders, closed-form KL), and demonstrated results on images. VAEs offered several advantages over existing approaches: principled probabilistic framework (unlike autoencoders), stable training (unlike early GANs), and tractable lower bound on likelihood (unlike implicit models). The work influenced thousands of follow-up papers exploring VAE variants, applications, and theoretical properties. Reading this paper, one appreciates both the mathematical sophistication (connecting neural networks to variational inference) and the practical insight (the reparameterization trick) that made the method work.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1606.05908&quot;&gt;“Tutorial on Variational Autoencoders” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Author&lt;/em&gt;: Carl Doersch&lt;br /&gt;
This tutorial paper provided accessible introduction to VAEs for readers without strong background in variational inference. Doersch carefully explained the intuition behind ELBO (why a lower bound is sufficient, what the terms mean), the reparameterization trick (with visual diagrams showing gradient flow), and practical training considerations. The tutorial addressed common confusions (why Gaussian posteriors, what latent space structure means, how to choose hyperparameters) and connected VAEs to related concepts (autoencoders, GANs, Bayesian inference). While not introducing new methods, this tutorial significantly helped VAE adoption by making the framework accessible to practitioners. It exemplifies how clear exposition—explaining not just what equations are but why they make sense—can have major impact on field by lowering barriers to understanding sophisticated techniques.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://openreview.net/forum?id=Sy2fzU9gl&quot;&gt;“β-VAE: Learning Basic Visual Concepts with a Constrained Variational Framework” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Irina Higgins, Loic Matthey, Arka Pal, Christopher Burgess, Xavier Glorot, Matthew Botvinick, Shakir Mohamed, Alexander Lerchner&lt;br /&gt;
This paper introduced β-VAE, a simple modification where the KL term in the loss is weighted by \(\beta &amp;gt; 1\) instead of 1. This seemingly minor change has profound effects on the learned latent representations. Higher β more strongly penalizes KL divergence, encouraging the latent dimensions to be independent (factorized), which often leads to disentangled representations where each dimension captures one interpretable factor of variation. The paper demonstrated that β-VAEs learn to separate factors like shape, size, rotation, and color into different latent dimensions, enabling controlled generation by manipulating specific dimensions. The work connected VAEs to the information bottleneck principle and showed that the right amount of compression (through β) can improve representation quality for downstream tasks. β-VAE has become a standard tool for learning disentangled representations and illustrates how hyperparameters (β) can control qualitative properties of learned representations, not just quantitative metrics like reconstruction error.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1509.00519&quot;&gt;“Importance Weighted Autoencoders” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Yuri Burda, Roger Grosse, Ruslan Salakhutdinov&lt;br /&gt;
This paper improved VAE’s ELBO through importance sampling, creating a tighter lower bound on log-likelihood. Standard VAE uses a single sample from \(q_\phi(\mathbf{z}|\mathbf{x})\) to estimate the ELBO. IWAE uses multiple samples and importance weighting, giving:&lt;/p&gt;

\[\mathcal{L}_{\text{IWAE}} = \mathbb{E}\left[\log \frac{1}{K}\sum_{k=1}^K \frac{p_\theta(\mathbf{x}, \mathbf{z}^{(k)})}{q_\phi(\mathbf{z}^{(k)}|\mathbf{x})}\right]\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;This is a tighter lower bound (approaches true log-likelihood as \(K \to \infty\)) and often generates better samples. The paper showed that the quality improvement comes from better training of the generative model $$p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})\(, though the inference network\)q_\phi$$ might become less accurate. IWAE demonstrates that even with VAE’s solid theoretical foundation, there’s room for improvement through better variational approximations. The importance weighting idea has influenced subsequent work on improving variational bounds and shows how classical statistical techniques (importance sampling) can enhance neural approaches.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1906.00446&quot;&gt;“Generating Diverse High-Fidelity Images with VQ-VAE-2” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ali Razavi, Aaron van den Oord, Oriol Vinyals&lt;br /&gt;
This paper introduced VQ-VAE-2, achieving state-of-the-art sample quality for VAE-based models by using discrete latent representations and hierarchical priors. Instead of continuous Gaussian latents, VQ-VAE uses vector quantization—the encoder outputs indices into a learned codebook, and the decoder receives the corresponding codebook vectors. This discreteness allows using powerful autoregressive priors over the latent codes, dramatically improving sample quality. The hierarchical structure (separate latent codes for global and local structure) enables generating high-resolution images. While more complex than standard VAEs, VQ-VAE-2 demonstrated that VAE-based models could compete with GANs in sample quality while maintaining VAE’s advantages of stable training and latent space structure. The work showed that the VAE framework is flexible enough to accommodate discrete latents, hierarchical structure, and sophisticated priors, pushing VAE performance to new levels.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The most common failure mode in VAE training is posterior collapse, where the encoder learns to ignore the input and output the prior distribution for all inputs: $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x}) \approx p(\mathbf{z}) = \mathcal{N}(0,I)\(regardless of\)\mathbf{x}$$. The KL term becomes zero (good for that term!) but the reconstruction term cannot improve because latent codes contain no information about the input. The decoder learns to generate average images (the mean of the training distribution) regardless of latent code. Symptoms include very low KL divergence (approaching 0) and poor reconstructions. This happens when the decoder is too powerful—it can reconstruct reasonably well without using latent information, so the encoder takes the easy route of outputting the prior to minimize KL.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Solutions include: (1) weakening the decoder (fewer layers/parameters), forcing it to rely on latent codes; (2) KL annealing—start training with β=0 (no KL penalty) and gradually increase to β=1, allowing the encoder to discover useful representations before regularization is applied; (3) free bits—only penalize KL if it’s above a threshold, ensuring latent dimensions maintain minimum information content; (4) better optimization—using higher learning rates for the encoder than decoder, giving it advantage in the competition for capacity. Understanding posterior collapse as an optimization pathology rather than fundamental VAE limitation helps implement these solutions appropriately.&lt;/p&gt;

&lt;p&gt;Choosing the latent dimension involves a tradeoff between expressiveness and disentanglement. Larger latent dimensions can capture more variation (good for reconstruction) but tend to be less disentangled (dimensions become correlated, harder to interpret). Smaller latent dimensions force more compression and often learn more disentangled representations but may not capture all data variation (poor reconstruction). For MNIST, 10-20 dimensions typically suffice. For CelebA faces, 64-256 dimensions are common. Always validate on both reconstruction quality (quantitative) and latent space interpretability (qualitative).&lt;/p&gt;

&lt;p&gt;The choice of β in β-VAE significantly affects outcomes. β=1 is standard VAE, balancing reconstruction and regularization. β&amp;gt;1 (typically 2-10) prioritizes disentanglement, useful when interpretability matters more than perfect reconstruction. β&amp;lt;1 (typically 0.1-0.5) prioritizes reconstruction, useful when generation quality matters more than latent space structure. For representation learning (using VAE features for downstream tasks), β=1-2 often works well. For controllable generation (manipulating specific attributes), β=4-10 provides more disentangled latents. Understanding this knob allows tailoring VAEs to specific application requirements.&lt;/p&gt;

&lt;p&gt;A powerful technique for improving sample quality is using more sophisticated decoder distributions than Gaussian or Bernoulli. Mixture of discretized logistics (modeling pixel values as mixture of binned distributions) captures multi-modality better than single Gaussian. Autoregressive decoders (each pixel predicted conditionally on previous pixels) capture dependencies autoencoders’ factorized assumptions miss. These more expressive decoders often generate sharper samples while maintaining VAE’s stable training. The tradeoff is computational cost—autoregressive decoding is slow. Understanding that decoder choice affects both sample quality and training/generation speed guides appropriate architectural decisions.&lt;/p&gt;

&lt;p&gt;When using VAE latent codes for downstream tasks (classification, clustering), a decision is whether to use the mean \(\boldsymbol{\mu}\) or sample from \(\mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\sigma}^2)\). For deterministic tasks (classification), using mean provides stable features. For tasks requiring uncertainty (active learning, Bayesian inference), sampling reflects the encoder’s uncertainty. For most applications, the mean works well and is standard practice, but understanding that the full distribution is available enables more sophisticated uses when appropriate.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Variational Autoencoders combine neural networks with variational inference to create a principled probabilistic framework for generative modeling with latent variables, optimizing the Evidence Lower BOund on log-likelihood as a tractable surrogate for the intractable true likelihood. The encoder learns to map inputs to distributions over latent codes (parameterized as Gaussian with learned mean and variance), while the decoder learns to reconstruct inputs from latent samples, with both trained jointly through the ELBO objective combining reconstruction accuracy and latent distribution regularization. The reparameterization trick—expressing stochastic sampling as deterministic function of parameters and external randomness—enables backpropagation through sampling, making end-to-end training possible with standard gradient descent. The KL divergence between approximate posterior and prior regularizes the latent space to be continuous, complete, and centered around the prior, ensuring samples from the prior decode to realistic outputs and enabling smooth interpolation between examples. β-VAE extends the framework by weighting the KL term, trading off reconstruction quality for latent disentanglement and enabling learned representations where individual dimensions capture interpretable factors of variation. VAEs provide stable training compared to GANs, explicit latent space structure enabling interpolation and manipulation, and a principled probabilistic framework supporting theoretical analysis, though often producing somewhat blurrier samples than adversarially trained models. Understanding VAEs requires appreciating the interplay between deep learning (neural encoders/decoders), probability theory (latent variable models), and optimization (variational bounds), making them both theoretically rich and practically valuable for generation, representation learning, and semi-supervised learning.&lt;/p&gt;

&lt;p&gt;Variational autoencoders exemplify how bringing together ideas from different fields—neural networks, variational inference, information theory—can create methods more powerful than the sum of their parts.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, English. The sampling path the code has to follow: reparameterize, then decode.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. The implementation pitfalls (posterior collapse, blurry samples) this lesson lists.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vPvnpC0PNVQ&quot;&gt;MaDL - Kullback-Leibler Divergence&lt;/a&gt; — Tübingen Machine Learning, English. The KL piece to check if the loss is only reconstruction.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>13-01-01 VAE Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter13/13_01_01_VAE_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter13/13_01_01_VAE_Theory</id>
   <content type="html">&lt;p&gt;At the heart of Variational Autoencoder theory sits a beautiful identity: the gap between the true data log-likelihood $\log p_\theta(x)$ and the Evidence Lower Bound (ELBO) is &lt;em&gt;exactly&lt;/em&gt; the KL divergence $D_{\text{KL}}(q_\phi(z \mid x) | p_\theta(z \mid x))$ between our approximate encoder and the true intractable posterior. Maximizing the ELBO therefore accomplishes two goals simultaneously—it pushes up the probability of the data &lt;em&gt;and&lt;/em&gt; tightens the encoder’s approximation to Bayes’ rule.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-mathematical-engine-of-vaes&quot;&gt;Key ideas: The Mathematical Engine of VAEs&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Jensen’s Inequality &amp;amp; ELBO Decomposition&lt;/strong&gt;: Derives $\log p_\theta(x) = \mathcal{L}&lt;em&gt;{\text{ELBO}}(\theta, \phi; x) + D&lt;/em&gt;{\text{KL}}(q_\phi(z \mid x) | p_\theta(z \mid x))$, proving $\mathcal{L}&lt;em&gt;{\text{ELBO}} \le \log p&lt;/em&gt;\theta(x)$ with equality iff $q_\phi = p_\theta(\cdot \mid x)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Reconstruction vs. Rate–Distortion Trade-off&lt;/strong&gt;: Interprets the ELBO as $-\text{Distortion} - \text{Rate}$, where the KL term measures how many nats of information $z$ transmits about $x$ beyond the prior $p(z)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Pathwise Derivative Estimator (Reparameterization)&lt;/strong&gt;: Contrasts high-variance score-function (REINFORCE) gradients with low-variance reparameterized gradients $\nabla_\phi \mathbb{E}&lt;em&gt;{\epsilon}[f(g&lt;/em&gt;\phi(\epsilon, x))]$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Posterior Collapse &amp;amp; $\beta$-VAE&lt;/strong&gt;: Explains why an overly expressive decoder can ignore $z$ ($q_\phi(z \mid x) \approx p(z)$, KL $\to 0$) and how weighting KL by $\beta$ trades disentanglement against reconstruction fidelity.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-the-exact-elbo-on-a-2d-latent-code&quot;&gt;Worked example: Computing the Exact ELBO on a 2D Latent Code&lt;/h3&gt;

&lt;p&gt;Suppose an encoder maps an image $x$ to a 2D diagonal Gaussian with $\mu = (0.6, -0.8)$ and $\sigma = (0.5, 1.0)$ (so $\sigma^2 = (0.25, 1.0)$ and $\log\sigma^2 = (-1.3863, 0.0)$). Suppose the decoder’s Bernoulli reconstruction log-likelihood on a 2-pixel target $x = (1, 0)$ with predicted probabilities $\hat{x} = (0.8, 0.2)$ is evaluated below.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Reconstruction term $\log p_\theta(x \mid z)$&lt;/strong&gt;:
\(\log p_\theta(x \mid z) = \ln(0.8) + \ln(1 - 0.2) = 2\ln(0.8) = 2(-0.2231) = -0.4463\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;KL Divergence per latent dimension&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Dim 1: $-\frac{1}{2}\big(1 + (-1.3863) - 0.6^2 - 0.25\big) = -\frac{1}{2}(-0.9963) = 0.4982\text{ nats}$.&lt;/li&gt;
      &lt;li&gt;Dim 2: $-\frac{1}{2}\big(1 + 0.0 - (-0.8)^2 - 1.0\big) = -\frac{1}{2}(-0.64) = 0.3200\text{ nats}$.&lt;/li&gt;
      &lt;li&gt;Total KL $= 0.4982 + 0.3200 = 0.8182\text{ nats}$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Total ELBO and Training Loss&lt;/strong&gt;:
\(\text{ELBO} = \log p_\theta(x \mid z) - D_{\text{KL}} = -0.4463 - 0.8182 = -1.2645\text{ nats} \implies \mathcal{L}_{\text{VAE}} = -\text{ELBO} = 1.2645.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Notice that if you scale the reconstruction loss by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mean&lt;/code&gt; over pixels while &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sum&lt;/code&gt;ming KL over latent dimensions, you inadvertently turn a standard VAE into a $\beta$-VAE with $\beta = 784$—one of the most common implementation bugs!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;variational-autoencoders-probabilistic-generative-models&quot;&gt;Variational Autoencoders: Probabilistic Generative Models&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://lilianweng.github.io/posts/2018-08-12-vae/vae-gaussian.png&quot; alt=&quot;VAE Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc VAE với phân phối xác suất. Nguồn: Lilian Weng’s Blog&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Variational Autoencoders represent a beautiful marriage of variational inference from statistics and neural networks from deep learning, creating a principled probabilistic framework for generative modeling. While standard autoencoders learn deterministic encodings and decodings optimized for reconstruction, VAEs learn probability distributions over latent codes and data, enabling them to generate novel samples by sampling from the learned latent distribution. This probabilistic perspective addresses a fundamental limitation of vanilla autoencoders: their latent spaces can have “holes” where no training examples map, making random sampling produce unrealistic outputs. VAEs regularize the latent space to be continuous and complete, ensuring we can sample from any region and decode to realistic data.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The key insight that makes VAEs work is the Evidence Lower BOund (ELBO), a tractable objective that lower-bounds the intractable log-likelihood we actually want to maximize. Computing \(\log p(\mathbf{x})\) for a latent variable model requires integrating over all possible latent codes \(\mathbf{z}\), which is generally impossible for continuous latent spaces with neural network decoders. VAEs sidestep this by introducing a recognition network (encoder) that approximates the true posterior $$p(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})$$, then optimizing a lower bound that’s tractable. The tightness of this bound depends on how well the encoder approximates the true posterior—better approximation means tighter bound and better model.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Understanding VAEs requires appreciating several sophisticated ideas working together. The reparameterization trick enables backpropagation through stochastic sampling operations, turning an optimization problem that seems to require reinforcement learning into one solvable with standard gradient descent. The KL divergence between the approximate posterior and the prior acts as a regularizer, preventing the latent space from fragmenting into disconnected regions and encouraging smoothness that enables interpolation. The encoder and decoder are trained jointly, creating an architecture where the encoder learns to infer meaningful latent representations while the decoder learns to generate realistic data from these representations.&lt;/p&gt;

&lt;p&gt;The beauty of the VAE framework is its generality. The same basic structure—encoder, latent distribution, decoder, ELBO objective—works for images, text, audio, and other data types, with appropriate choices of encoder/decoder architectures and output distributions. The latent space learned by VAEs has remarkable properties: it’s continuous (nearby latent codes decode to similar outputs), complete (every region contains valid codes), and often interpretable (different latent dimensions capture different factors of variation like pose, color, or shape). These properties make VAEs valuable not just for generation but for representation learning, interpolation, and manipulation of semantic attributes.&lt;/p&gt;

&lt;p&gt;Yet VAEs have characteristic limitations that motivate ongoing research. Samples are often somewhat blurry compared to GANs, a consequence of the reconstruction-based objective and Gaussian assumptions commonly used for the decoder. The prior distribution (typically standard Gaussian) might not match the true aggregate posterior, creating a gap between what the encoder produces and what we sample from during generation. The encoder-decoder architecture creates a potential bottleneck if the latent dimension is too small. Understanding these limitations alongside VAE strengths enables using them appropriately: when you need a principled probabilistic model with tractable training, smooth latent space for interpolation, or explicit density estimation, VAEs excel. When sample quality is paramount and training instability is acceptable, GANs might be preferable.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;The mathematical framework of VAEs is rooted in variational inference, a powerful technique from Bayesian statistics for approximating intractable posterior distributions. Let’s build up the mathematics carefully, understanding why each component is necessary and how they combine to create a trainable generative model.&lt;/p&gt;

&lt;p&gt;We assume data \(\mathbf{x}\) is generated from latent variables \(\mathbf{z}\) through a probabilistic process:&lt;/p&gt;

&lt;p&gt;\(\mathbf{z} \sim p(\mathbf{z})\) (prior distribution, chosen to be simple)&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;$$\mathbf{x} \sim p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})\((likelihood, parameterized by neural network\)\theta$$)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The marginal likelihood of data is:&lt;/p&gt;

\[p_\theta(\mathbf{x}) = \int p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z}) d\mathbf{z}\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;This integral is intractable for continuous \(\mathbf{z}\) with complex $$p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})$$ (neural network decoder). Direct maximum likelihood optimization is impossible because we cannot evaluate the objective we want to maximize.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Variational inference addresses this by introducing an approximate posterior $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\((the encoder, parameterized by\)\phi$$) and deriving a lower bound on log-likelihood. Starting from the log-likelihood and introducing the encoder:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[\log p_\theta(\mathbf{x}) = \log \int p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z}) d\mathbf{z}\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Multiply inside the integral by $$\frac{q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})}{q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})} = 1$$:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[= \log \int q_\phi(\mathbf{z}|\mathbf{x}) \frac{p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})} d\mathbf{z}\]

\[= \log \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}\left[\frac{p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})}\right]\]

&lt;p&gt;By Jensen’s inequality (log is concave):&lt;/p&gt;

\[\geq \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}\left[\log \frac{p_\theta(\mathbf{x}|\mathbf{z}) p(\mathbf{z})}{q_\phi(\mathbf{z}|\mathbf{x})}\right]\]

&lt;p&gt;Rearranging terms:&lt;/p&gt;

\[= \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}[\log p_\theta(\mathbf{x}|\mathbf{z})] - \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}\left[\log \frac{q_\phi(\mathbf{z}|\mathbf{x})}{p(\mathbf{z})}\right]\]

\[= \mathbb{E}_{\mathbf{z} \sim q_\phi(\mathbf{z}|\mathbf{x})}[\log p_\theta(\mathbf{x}|\mathbf{z})] - KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z}))\]

&lt;p&gt;This is the Evidence Lower BOund (ELBO). The first term is reconstruction: how well can we reconstruct \(\mathbf{x}\) from latent codes sampled from the encoder. The second term is a KL divergence between the approximate posterior and the prior, acting as regularization.&lt;/p&gt;

&lt;p&gt;The ELBO provides a tractable training objective. Unlike \(\log p_\theta(\mathbf{x})\) which requires intractable integration, we can estimate the ELBO through sampling:&lt;/p&gt;

\[\mathcal{L}(\theta, \phi; \mathbf{x}) \approx \frac{1}{L}\sum_{l=1}^L \log p_\theta(\mathbf{x}|\mathbf{z}^{(l)}) - KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z}))\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;where $$\mathbf{z}^{(l)} \sim q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(. Often\)L=1$$ suffices (single sample per datapoint).&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;the-reparameterization-trick&quot;&gt;The Reparameterization Trick&lt;/h3&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The remaining challenge is computing gradients with respect to \(\phi\) when the objective involves sampling $$\mathbf{z} \sim q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})$$. Naively, sampling is a non-differentiable operation—we cannot backpropagate through randomness. The reparameterization trick solves this elegantly.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;For Gaussian approximate posterior $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x}) = \mathcal{N}(\boldsymbol{\mu}&lt;em&gt;\phi(\mathbf{x}), \boldsymbol{\sigma}^2&lt;/em&gt;\phi(\mathbf{x}))$$, instead of sampling directly, we:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;ol&gt;
  &lt;li&gt;Sample \(\boldsymbol{\epsilon} \sim \mathcal{N}(0, I)\) (fixed distribution, no parameters)&lt;/li&gt;
  &lt;li&gt;Compute \(\mathbf{z} = \boldsymbol{\mu}_\phi(\mathbf{x}) + \boldsymbol{\sigma}_\phi(\mathbf{x}) \odot \boldsymbol{\epsilon}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;This is equivalent to sampling from $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(but expressed as a deterministic function of\)\phi\(and external randomness\)\boldsymbol{\epsilon}\(. Gradients with respect to\)\phi\(flow through\)\boldsymbol{\mu}&lt;em&gt;\phi\(and\)\boldsymbol{\sigma}&lt;/em&gt;\phi$$, enabling backpropagation.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;For the common case where both $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})\(and\)p(\mathbf{z})$$ are Gaussian, the KL divergence has a closed form:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z})) = KL(\mathcal{N}(\boldsymbol{\mu}, \boldsymbol{\sigma}^2) \| \mathcal{N}(0, I))\]

\[= \frac{1}{2}\sum_{j=1}^{J} \left(\mu_j^2 + \sigma_j^2 - \log \sigma_j^2 - 1\right)\]

&lt;p&gt;where \(J\) is latent dimension. This allows exact computation without sampling, making training more stable.&lt;/p&gt;

&lt;p&gt;The complete VAE loss for a single datapoint becomes:&lt;/p&gt;

\[\mathcal{L}_{\text{VAE}}(\theta, \phi; \mathbf{x}) = \mathbb{E}_{\boldsymbol{\epsilon} \sim \mathcal{N}(0,I)}[\log p_\theta(\mathbf{x}|\boldsymbol{\mu}_\phi(\mathbf{x}) + \boldsymbol{\sigma}_\phi(\mathbf{x}) \odot \boldsymbol{\epsilon})] - \frac{1}{2}\sum_{j=1}^{J} (\mu_j^2 + \sigma_j^2 - \log \sigma_j^2 - 1)\]

&lt;p&gt;Maximizing this (or equivalently minimizing the negative) trains the VAE. The reconstruction term encourages accurate reconstruction while the KL term regularizes the latent space.&lt;/p&gt;

&lt;h3 id=&quot;decoder-output-distribution&quot;&gt;Decoder Output Distribution&lt;/h3&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The choice of $$p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})$$ affects what reconstruction loss we use. For continuous data like images:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Gaussian likelihood&lt;/strong&gt;: $$p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z}) = \mathcal{N}(\mathbf{x}; \boldsymbol{\mu}_\theta(\mathbf{z}), \sigma^2 I)$$&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The negative log-likelihood is proportional to MSE: $$-\log p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z}) \propto |\mathbf{x} - \boldsymbol{\mu}_\theta(\mathbf{z})|^2$$&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Bernoulli likelihood&lt;/strong&gt; (for binary images): Each pixel independent Bernoulli with probability \(\hat{x}_i\) from decoder.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The negative log-likelihood is binary cross-entropy: $$-\log p_\theta(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z}) = -\sum_i [x_i \log \hat{x}_i + (1-x_i)\log(1-\hat{x}_i)]$$&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The decoder network outputs the parameters of these distributions (means for Gaussian, probabilities for Bernoulli), and we sample from them during generation but use the mean/mode during reconstruction for training.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;To understand how VAEs work in practice, let’s trace through generating a new handwritten digit. Suppose we’ve trained a VAE on MNIST with 20-dimensional latent space.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;During training, the VAE saw thousands of “3”s. For each “3” image \(\mathbf{x}\), the encoder computed a Gaussian distribution in latent space: $$q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x}) = \mathcal{N}(\boldsymbol{\mu}&lt;em&gt;\phi(\mathbf{x}), \boldsymbol{\sigma}^2&lt;/em&gt;\phi(\mathbf{x}))\(. The KL penalty in the loss encouraged these distributions to be close to\)\mathcal{N}(0, I)$$, preventing them from spreading arbitrarily far or collapsing to point masses. The result: all “3”s map to overlapping Gaussian distributions in a region of latent space. Different “3”s (thick, thin, slanted) map to slightly different means, but all are close to each other and to the origin.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Similarly, “8”s map to a different but also origin-centered region, “1”s to another, and so on. The latent space self-organizes: different digits occupy different regions, but all regions are near the origin (due to KL penalty), and transitions between regions are smooth (no holes).&lt;/p&gt;

&lt;p&gt;Now for generation. We sample \(\mathbf{z} \sim \mathcal{N}(0, I)\)—just random numbers from a standard Gaussian. Suppose we get \(\mathbf{z} = [0.5, -0.3, 0.1, \ldots]\) (20 numbers). By chance, this \(\mathbf{z}\) falls in the “3” region of latent space. We decode: \(\hat{\mathbf{x}} = \text{decoder}_\theta(\mathbf{z})\). The decoder, having seen many “3”s during training whose latent codes were near this \(\mathbf{z}\), has learned to map this region to “3”-like images. The output is a novel “3”—not a copy of any training example but a new instance following the learned pattern.&lt;/p&gt;

&lt;p&gt;The probabilistic nature provides interesting capabilities. If we sample \(\mathbf{z}\) from exactly \(\mathcal{N}(0, I)\), we get a diverse mix of all digits. If we want only “3”s, we can sample from the region where “3”s tend to map—but we don’t know this region exactly without examining the encoder on “3” training examples. This is a limitation: VAEs don’t provide explicit control over what class to generate unless we condition on class labels or discover class regions post-hoc.&lt;/p&gt;

&lt;p&gt;Interpolation between images works beautifully. Encode two images to get \(\boldsymbol{\mu}_1\) and \(\boldsymbol{\mu}_2\) (using encoder’s means, ignoring variances for determinism). Linearly interpolate:&lt;/p&gt;

\[\mathbf{z}_t = (1-t)\boldsymbol{\mu}_1 + t\boldsymbol{\mu}_2, \quad t \in [0,1]\]

&lt;p&gt;Decode each \(\mathbf{z}_t\) to get interpolated images. Because the VAE regularized the latent space to be smooth (through KL penalty), this interpolation produces coherent images throughout—smoothly morphing from one digit to another. This is unlike vanilla autoencoders where interpolation might produce unrealistic images in unexplored latent regions.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The KL divergence penalty’s role deserves deep understanding. It serves three purposes: (1) regularization preventing overfitting to training examples, (2) ensuring the latent space is continuous and complete for sampling, (3) encouraging disentanglement where different latent dimensions capture independent factors of variation. The KL term $$KL(q_\phi(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x}) | p(\mathbf{z}))$$ can be decomposed:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[KL(q_\phi(\mathbf{z}|\mathbf{x}) \| p(\mathbf{z})) = -H(q_\phi(\mathbf{z}|\mathbf{x})) + H(p(\mathbf{z}), q_\phi(\mathbf{z}|\mathbf{x}))\]

&lt;p&gt;The first term encourages high entropy in \(q_\phi\) (uncertainty), preventing the encoder from collapsing to deterministic encodings (which would make sampling impossible). The second term encourages closeness to the prior \(p(\mathbf{z})\), ensuring the latent space structure matches what we’ll sample from during generation.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, English. Encoder as approximate posterior, decoder as likelihood, ELBO as the objective.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vPvnpC0PNVQ&quot;&gt;MaDL - Kullback-Leibler Divergence&lt;/a&gt; — Tübingen Machine Learning, English. KL(q&lt;/td&gt;
          &lt;td&gt; &lt;/td&gt;
          &lt;td&gt;p) is the regularizer in that ELBO.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. A second derivation if the reparameterization step does not land.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>13 Variational Autoencoders (VAE)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter13/13_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter13/13_00_Introduction</id>
   <content type="html">&lt;p&gt;A vanilla autoencoder is like a meticulous librarian who files every book wherever there happens to be shelf space—great for finding books you already own, terrible if you reach blindly onto a shelf expecting a coherent new novel. In 2013, Kingma &amp;amp; Welling and Rezende et al. solved this by turning the encoder into a &lt;em&gt;probabilistic&lt;/em&gt; map: instead of pinning each image to a single rigid point $z$, a Variational Autoencoder (VAE) maps it to a soft Gaussian cloud pulled gently toward $\mathcal{N}(0, I)$, eliminating dead zones so every random draw from the prior decodes into plausible data.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-foundations-of-variational-autoencoders&quot;&gt;Key ideas: Foundations of Variational Autoencoders&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Variational Inference &amp;amp; the ELBO&lt;/strong&gt;: Replaces the intractable marginal log-likelihood $\log p_\theta(x)$ with a tractable Evidence Lower Bound balancing reconstruction accuracy against prior regularization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Amortized Inference&lt;/strong&gt;: Uses a single neural network $q_\phi(z \mid x)$ to predict posterior parameters $(\mu_\phi(x), \log\sigma^2_\phi(x))$ for any input $x$ in one forward pass, avoiding per-datapoint optimization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — The Reparameterization Trick&lt;/strong&gt;: Separates stochastic sampling $\epsilon \sim \mathcal{N}(0, I)$ from differentiable parameters via $z = \mu + \sigma \odot \epsilon$, allowing exact low-variance backpropagation through random nodes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Latent Space Continuity &amp;amp; Generation&lt;/strong&gt;: Guarantees smooth semantic interpolation and direct ancestral sampling $z \sim \mathcal{N}(0, I) \to x \sim p_\theta(x \mid z)$.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-one-forward-pass-of-a-1d-vae-posterior&quot;&gt;Worked example: One Forward Pass of a 1D VAE Posterior&lt;/h3&gt;

&lt;p&gt;Suppose for an input $x$, our encoder outputs $\mu = 1.0$ and $\log\sigma^2 = 0.0$ (so $\sigma^2 = e^0 = 1.0$, $\sigma = 1.0$), and we draw $\epsilon = -0.5$ from $\mathcal{N}(0, 1)$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Reparameterized latent sample&lt;/strong&gt;:
\(z = \mu + \sigma \cdot \epsilon = 1.0 + 1.0 \cdot (-0.5) = 0.5.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Closed-form KL divergence against standard normal prior $\mathcal{N}(0, 1)$&lt;/strong&gt;:
\(D_{\text{KL}}\big(\mathcal{N}(\mu, \sigma^2) \,\|\, \mathcal{N}(0, 1)\big) = -\frac{1}{2}\big(1 + \log\sigma^2 - \mu^2 - \sigma^2\big) = -\frac{1}{2}(1 + 0 - 1^2 - 1) = 0.5\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient of $z$ with respect to encoder parameters&lt;/strong&gt;:
\(\frac{\partial z}{\partial \mu} = 1, \qquad \frac{\partial z}{\partial \sigma} = \epsilon = -0.5.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Both the KL penalty ($0.5$ nats pulling $\mu$ toward $0$) and the exact pathwise gradients ($\partial z/\partial \mu = 1$, $\partial z/\partial \sigma = -0.5$) are completely analytical and differentiable.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Variational Autoencoders (VAEs) are probabilistic generative models that learn structured latent representations. By combining variational inference with neural networks, VAEs can generate new samples and interpolate smoothly in latent space. This chapter covers the VAE architecture, ELBO objective, reparameterization trick, and applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After the ELBO notes, see &lt;strong&gt;13-99 Modern Applications and Updates&lt;/strong&gt; for VAEs as diffusion/video latents and consistency-model codecs.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, English. A VAE is an autoencoder whose latent is a distribution.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. MIT’s generative lecture places that idea among GANs and diffusion.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pYxNSUDSFH4&quot;&gt;In Statistics, Probability is not Likelihood.&lt;/a&gt; — StatQuest with Josh Starmer, English. Likelihood is the objective the ELBO is a bound on.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;You might think classical autoencoders were retired once diffusion models and LLMs took over—in reality, they quietly became the load-bearing compression layer underneath almost every modern multimodal system. Stable Diffusion does not diffuse pixels; it diffuses inside an autoencoder’s latent space. Audio language models do not predict raw 48 kHz waveforms; they predict discrete tokens emitted by a vector-quantized neural audio codec.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-modern-autoencoders-20222026&quot;&gt;Key ideas: Modern Autoencoders (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Latent Diffusion Codecs&lt;/strong&gt;: Compresses high-resolution RGB images (e.g., $512 \times 512 \times 3$) by a spatial factor of $8\times$ into compact $64 \times 64 \times 4$ latents, cutting quadratic self-attention cost by over $4{,}000\times$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Vector Quantization &amp;amp; Residual VQ (RVQ)&lt;/strong&gt;: Snaps continuous encoder vectors to nearest codebook entries $e_k$, turning images and audio into discrete token streams compatible with autoregressive Transformers.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Masked Autoencoders (MAE)&lt;/strong&gt;: Drops $75\%$ of image patches at the encoder input and reconstructs missing pixels with a lightweight decoder, scaling self-supervised vision pretraining to billion-parameter ViTs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Perceptual &amp;amp; Adversarial Reconstruction Losses&lt;/strong&gt;: Replaces pure pixel MSE (which causes blur) with LPIPS perceptual losses plus PatchGAN discriminators so compressed reconstructions stay razor-sharp.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-compute-savings-of-latent-compression--residual-vector-quantization-bitrate&quot;&gt;Worked example: Compute Savings of Latent Compression &amp;amp; Residual Vector Quantization Bitrate&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Spatial compression savings for a $512 \times 512 \times 3$ image encoded to $64 \times 64 \times 4$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Raw pixel elements: $512 \times 512 \times 3 = 786{,}432$.&lt;/li&gt;
      &lt;li&gt;Latent elements: $64 \times 64 \times 4 = 16{,}384$.&lt;/li&gt;
      &lt;li&gt;Element compression factor: $786{,}432 / 16{,}384 = 48\times$.&lt;/li&gt;
      &lt;li&gt;Sequence length for self-attention ($H \times W$): drops from $262{,}144$ to $4{,}096$ ($64\times$ shorter), reducing $O(N^2)$ attention operations by $64^2 = 4{,}096\times$!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Neural audio codec bitrate (EnCodec / DAC style)&lt;/strong&gt;:
Suppose an encoder produces $f_s = 75$ frames/second, each quantized by $N_q = 8$ residual VQ codebooks of size $K = 1024$ entries ($\log_2 1024 = 10$ bits per codebook).
\(\text{Bitrate} = 75 \text{ frames/s} \times 8 \text{ codebooks} \times 10 \text{ bits} = 6{,}000 \text{ bits/s} = 6.0\text{ kbps}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Modern autoencoders turn prohibitive raw media signals into $48\times$ smaller image latents and $6\text{ kbps}$ discrete audio tokens—making foundation-scale generation computationally feasible.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-autoencoders-as-latents-codecs-and-masked-reconstructors&quot;&gt;Optional: autoencoders as latents, codecs, and masked reconstructors&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace vanilla / denoising / sparse autoencoder theory. It shows how the same encoder–decoder idea is used after 2022: &lt;strong&gt;latent compression for diffusion&lt;/strong&gt;, &lt;strong&gt;neural audio codecs&lt;/strong&gt;, and &lt;strong&gt;masked image modeling&lt;/strong&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The reconstruction objective&lt;/p&gt;

\[\mathcal{L} = \mathbb{E}_{\mathbf{x}}\big\|\mathbf{x} - d_\phi(e_\theta(\mathbf{x}))\big\|^2\]

&lt;p&gt;is still the starting point. Products now care about a &lt;em&gt;structured&lt;/em&gt; latent: quantized, perceptual, or partially masked.&lt;/p&gt;

&lt;h2 id=&quot;1-latents-for-diffusion&quot;&gt;1. Latents for diffusion&lt;/h2&gt;

&lt;p&gt;Stable Diffusion’s first stage is an autoencoder (KL or VQ) that maps a \(512\times512\) image to a small latent grid. Diffusion (Chapter 11 optional, Chapter 13) then runs in that grid. The AE is trained with reconstruction + adversarial + perceptual losses (&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;Rombach et al., 2022&lt;/a&gt;). That is this chapter’s architecture, optimized as a &lt;strong&gt;codec for a second generative model&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;neural-audio-codecs&quot;&gt;Neural audio codecs&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.13438&quot;&gt;Défossez et al., 2022&lt;/a&gt; (EnCodec) and &lt;a href=&quot;https://arxiv.org/abs/2306.06546&quot;&gt;Kumar et al., 2023&lt;/a&gt; (DAC) are residual-vector-quantized autoencoders for waveforms. They sit under AudioLM / MusicGen / many TTS stacks: the AE turns audio into discrete tokens a Transformer can model.&lt;/p&gt;

&lt;h3 id=&quot;masked-autoencoders-mae&quot;&gt;Masked autoencoders (MAE)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2111.06377&quot;&gt;He et al., 2022&lt;/a&gt; mask random patches and reconstruct pixels with a ViT encoder–decoder. This is an AE &lt;em&gt;pretext&lt;/em&gt; (self-supervised; Chapter 16) rather than a generative prior. Mentioned here because the implementation is literally an autoencoder on patches.&lt;/p&gt;

&lt;h3 id=&quot;vector-quantized-aes&quot;&gt;Vector-quantized AEs&lt;/h3&gt;

&lt;p&gt;VQ-VAE / VQGAN remain the discrete bottleneck for image and video tokenizers (Make-A-Video, MAGVIT-v2). The commitment loss from the theory notes is the same; the 2022–2025 work is &lt;strong&gt;better codebooks and lookup-free quantization&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/diffusers&quot;&gt;diffusers&lt;/a&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AutoencoderKL&lt;/code&gt; — SD-style latents.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/encodec&quot;&gt;facebookresearch/encodec&lt;/a&gt; and &lt;a href=&quot;https://github.com/descriptinc/descript-audio-codec&quot;&gt;descriptinc/descript-audio-codec&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/mae&quot;&gt;facebookresearch/mae&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;High-Resolution Image Synthesis with Latent Diffusion Models (Rombach et al., 2022)&lt;/a&gt; — AE as diffusion latent.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2111.06377&quot;&gt;Masked Autoencoders Are Scalable Vision Learners (He et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.13438&quot;&gt;High Fidelity Neural Audio Compression — EnCodec (Défossez et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2306.06546&quot;&gt;High-Fidelity Audio Compression with Improved RVQGAN — DAC (Kumar et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Implement the NumPy/PyTorch autoencoder and the latent-space pitfalls first. This lesson only shows &lt;strong&gt;where those latents go&lt;/strong&gt; in 2022–2026 systems (diffusion, codecs, MAE) — not a new reconstruction derivation.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=J87hffSMB60&quot;&gt;How does Stable Diffusion work? – Latent Diffusion Models EXPLAINED&lt;/a&gt; — AI Coffee Break with Letitia, English. Stable Diffusion’s latent is the autoencoder this note says diffusion now lives in.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, English. The plain autoencoder that latent was generalized from.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But how do AI images and videos actually work?&lt;/td&gt;
          &lt;td&gt;Guest video by Welch Labs](https://www.youtube.com/watch?v=iv-5mZ_9CPY) — 3Blue1Brown, English. The diffusion process that runs in that latent space.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-01 Autoencoder Fundamentals</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_01_Autoencoder_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_01_Autoencoder_Fundamentals</id>
   <content type="html">&lt;p&gt;Long before transformers dominated representation learning, autoencoders proved a deceptively simple principle: you do not need human labels to learn rich internal features if you ask a network to compress and rebuild the world. Understanding both the mathematical foundations (linear PCA equivalence, sparsity, denoising) and the hands-on PyTorch mechanics gives you the conceptual bridge to VAEs, masked image modeling, and modern neural codecs.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-unifying-autoencoder-theory-and-practice&quot;&gt;Key ideas: Unifying Autoencoder Theory and Practice&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Information Bottleneck Principle&lt;/strong&gt;: Forces an encoder $f_\phi: \mathbb{R}^d \to \mathbb{R}^k$ ($k \ll d$) to discard redundant variation and retain only the coordinates needed for reconstruction.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Regularized Families&lt;/strong&gt;: Organizes vanilla, denoising, sparse, and contractive autoencoders as different constraints preventing trivial identity copying.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Representation Geometry&lt;/strong&gt;: Connects bottleneck width and architectural inductive bias (MLP vs. CNN) to cluster separation and interpolation quality.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Bridge to Probabilistic Generation&lt;/strong&gt;: Highlights where deterministic autoencoders stop (unstructured latent holes) and where variational autoencoders begin.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-choosing-bottleneck-dimension-via-explained-variance&quot;&gt;Worked example: Choosing Bottleneck Dimension via Explained Variance&lt;/h3&gt;

&lt;p&gt;Suppose a 4D dataset has covariance eigenvalues $\lambda_1 = 9.0, \lambda_2 = 5.0, \lambda_3 = 0.8, \lambda_4 = 0.2$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Total variance of the data&lt;/strong&gt;:
\(\text{Tr}(\Sigma) = 9.0 + 5.0 + 0.8 + 0.2 = 15.0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Minimum possible MSE of a linear autoencoder with bottleneck $k = 2$&lt;/strong&gt; (by Eckart–Young–Mirsky, equal to the sum of discarded eigenvalues):
\(\text{MSE}_{\min}(k=2) = \frac{\lambda_3 + \lambda_4}{d} = \frac{0.8 + 0.2}{4} = 0.25 \text{ per coordinate (total residual } 1.0\text{)}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Fraction of variance retained&lt;/strong&gt;:
\(\frac{\lambda_1 + \lambda_2}{\text{Tr}(\Sigma)} = \frac{14.0}{15.0} = 93.33\%.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: A linear bottleneck of size $k=2$ captures $93.33\%$ of total variance; any nonlinear autoencoder that beats $\text{MSE} = 0.25$ on this data is demonstrably exploiting curved manifold structure beyond PCA.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Autoencoder fundamentals:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Theory&lt;/strong&gt; — concept overview, math, intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implementation&lt;/strong&gt; — code, latent visualization, papers, pitfalls&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, English. Encoder, bottleneck, and decoder.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, English. The reconstruction loss those three pieces train with.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. Why a deterministic bottleneck is not yet a generative model, the point of the next chapter.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-01-02 Autoencoder Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_01_02_Autoencoder_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_01_02_Autoencoder_Implementation</id>
   <content type="html">&lt;p&gt;Turning autoencoder theory into reliable PyTorch code involves two distinct skills: first, getting the reconstruction loop and denoising corruption pipeline right; second, interrogating the learned latent space to verify that compression actually produced meaningful features rather than a brittle lookup table. This implementation guide splits those two stages cleanly so you can test each in isolation.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-autoencoder-engineering-workflow&quot;&gt;Key ideas: Autoencoder Engineering Workflow&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Core Reconstruction Pipeline&lt;/strong&gt;: Covers dataset normalization, symmetric bottleneck modules, and MSE/BCE optimization loops on MNIST.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Corruption-Based Regularization&lt;/strong&gt;: Demonstrates how adding noise only at the encoder input transforms memorization into manifold projection.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Latent Space Visualization &amp;amp; Morphing&lt;/strong&gt;: Uses 2D bottlenecks and linear interpolation paths to inspect class clustering and manifold smoothness.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Architectural Scaling to Convolutions&lt;/strong&gt;: Transitions from fully connected layers to 2D convolutional bottlenecks suited for spatial image structure.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-comparing-reconstruction-error-for-anomaly-detection&quot;&gt;Worked example: Comparing Reconstruction Error for Anomaly Detection&lt;/h3&gt;

&lt;p&gt;Suppose a trained autoencoder reconstructs normal test images with MSE $\mu_{\text{norm}} = 0.012$ and standard deviation $\sigma_{\text{norm}} = 0.003$. We set an anomaly threshold at $\tau = \mu_{\text{norm}} + 3\sigma_{\text{norm}}$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the decision threshold $\tau$&lt;/strong&gt;:
\(\tau = 0.012 + 3(0.003) = 0.021.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate two incoming 4-pixel toy patches&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Patch A (normal): $x = [0.2, 0.8, 0.8, 0.2]$, $\hat{x} = [0.25, 0.75, 0.85, 0.15]$.
\(\text{MSE}_A = \frac{0.05^2 + 0.05^2 + 0.05^2 + 0.05^2}{4} = 0.0025 &amp;lt; 0.021 \implies \text{Normal}.\)&lt;/li&gt;
      &lt;li&gt;Patch B (anomalous): $x = [0.9, 0.1, 0.9, 0.1]$, $\hat{x} = [0.5, 0.4, 0.5, 0.4]$.
\(\text{MSE}_B = \frac{0.4^2 + 0.3^2 + 0.4^2 + 0.3^2}{4} = \frac{0.16 + 0.09 + 0.16 + 0.09}{4} = 0.125 &amp;gt; 0.021 \implies \text{Anomaly}.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Because the bottleneck was trained exclusively on the normal manifold, out-of-distribution inputs suffer a $50\times$ jump in reconstruction MSE, giving an unsupervised anomaly score with zero labeled defects.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Autoencoder implementation:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Core Implementation&lt;/strong&gt; — training and reconstruction on MNIST&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Latent Space, Papers, and Pitfalls&lt;/strong&gt; — interpolation, 2D viz, related concepts, takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, English. So the code has an architecture to match.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, English. The loss and the latent-space plots the implementation lessons ask for.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, English. The training step you wrap around an encoder and a decoder.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-01-02-02 Latent Space, Papers, and Pitfalls</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_01_02_02_Latent_Space_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_01_02_02_Latent_Space_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Interpolate linearly between the latent code of a handwritten “1” and a handwritten “7” in a standard autoencoder, and you might be surprised: halfway between them, the decoder does not always morph smoothly—it often outputs a ghostly smudge. That single experiment reveals the fundamental limitation of deterministic autoencoders: because nothing constrains the geometry &lt;em&gt;between&lt;/em&gt; encoded training points, the latent space can contain uncharted holes.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-latent-geometry-convolutions-and-failure-modes&quot;&gt;Key ideas: Latent Geometry, Convolutions, and Failure Modes&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Latent Space Interpolation&lt;/strong&gt;: Evaluates $g_\theta((1-\alpha)z_1 + \alpha z_2)$ for $\alpha \in [0, 1]$ to probe whether the learned manifold is convex and smoothly organized or fragmented with dead zones.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Convolutional Encoder–Decoder Spatial Arithmetic&lt;/strong&gt;: Replaces dense layers with strided convolutions and transposed convolutions (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ConvTranspose2d&lt;/code&gt;), preserving 2D translation equivariance and drastically cutting parameter counts.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Unregularized Holes vs. Generative Sampling&lt;/strong&gt;: Explains why you cannot sample a random $z \sim \mathcal{N}(0, I)$ and expect a realistic image from a vanilla autoencoder—motivating the KL prior of VAEs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Representation Diagnostics &amp;amp; Pitfalls&lt;/strong&gt;: Uses 2D latent scatter plots and reconstruction error histograms to diagnose underfitting, posterior fragmentation, and checkerboard artifacts from transposed convolutions.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-tracing-spatial-dimensions-through-a-convolutional-autoencoder&quot;&gt;Worked example: Tracing Spatial Dimensions Through a Convolutional Autoencoder&lt;/h3&gt;

&lt;p&gt;Trace a single MNIST image tensor of shape $(1, 1, 28, 28)$ through a 2-layer strided convolutional encoder (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kernel=3, stride=2, padding=1&lt;/code&gt;) and transposed-convolution decoder (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kernel=3, stride=2, padding=1, output_padding=1&lt;/code&gt;).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Encoder spatial formula&lt;/strong&gt;: $H_{\text{out}} = \left\lfloor \frac{H_{\text{in}} + 2p - k}{s} \right\rfloor + 1$.
    &lt;ul&gt;
      &lt;li&gt;Conv1 ($1 \to 32$ channels): $\lfloor (28 + 2 - 3)/2 \rfloor + 1 = \lfloor 13.5 \rfloor + 1 = 14 \implies (1, 32, 14, 14)$.&lt;/li&gt;
      &lt;li&gt;Conv2 ($32 \to 64$ channels): $\lfloor (14 + 2 - 3)/2 \rfloor + 1 = \lfloor 6.5 \rfloor + 1 = 7 \implies (1, 64, 7, 7)$.&lt;/li&gt;
      &lt;li&gt;Flattened feature size: $64 \times 7 \times 7 = 3{,}136 \to \text{Linear} \to d_z = 2$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decoder transposed-convolution formula&lt;/strong&gt;: $H_{\text{out}} = (H_{\text{in}} - 1)s - 2p + k + \text{output_padding}$.
    &lt;ul&gt;
      &lt;li&gt;Deconv1 ($64 \to 32$): $(7 - 1)\cdot 2 - 2 + 3 + 1 = 14 \implies (1, 32, 14, 14)$.&lt;/li&gt;
      &lt;li&gt;Deconv2 ($32 \to 1$): $(14 - 1)\cdot 2 - 2 + 3 + 1 = 28 \implies (1, 1, 28, 28)$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Latent midpoint check&lt;/strong&gt;: If $z^{(1)} = (-1.2, 0.8)$ and $z^{(2)} = (2.8, -0.4)$, the $\alpha = 0.25$ interpolant is:
\(z_{0.25} = 0.75(-1.2, 0.8) + 0.25(2.8, -0.4) = (-0.9 + 0.7,\; 0.6 - 0.1) = (-0.2,\; 0.5).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Verifying &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output_padding=1&lt;/code&gt; prevents off-by-one shape crashes ($27 \times 27$ vs. $28 \times 28$), and testing midpoint codes like $(-0.2, 0.5)$ immediately reveals whether the decoder generalizes across empty latent regions.&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Demonstrate latent space interpolation
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Latent Space Interpolation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Take two different digits
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;idx1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Interpolate between first and sixth test image
&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;img1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;img2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;idx2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Encode both
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Interpolating between two test images:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Image 1 latent code mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Image 2 latent code mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Interpolate in latent space
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generating &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; intermediate images by interpolation:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_steps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;img_interp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_interp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Step &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (t=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;): Decoded image shape &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;img_interp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;In a visual display, you&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;d see smooth morphing from digit to digit.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This demonstrates the latent space has learned meaningful structure!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate dimensionality reduction visualization (2D latent space)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training 2D Autoencoder for Visualization&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Autoencoder with 2D latent space for visualization&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2D latent for plotting!
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_2d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer_2d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training 2D autoencoder (extreme compression: 784 → 2)...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;optimizer_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Visualize latent space
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Encoding test set into 2D latent space...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;latent_codes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;labels_all&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;latent_codes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels_all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;latent_codes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;concatenate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_codes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;labels_all&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;concatenate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels_all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Latent space coordinates shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_codes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (10000, 2)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;In a scatter plot, different digits would cluster in 2D space.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This demonstrates autoencoders learn meaningful representations!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Digit 0s in one region, 1s in another, etc.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Implement convolutional autoencoder for images:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Convolutional autoencoder for images.
    
    Uses conv layers in encoder (spatial downsampling through striding)
    and transposed convolutions in decoder (upsampling).
    Much more parameter-efficient than fully connected for images.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Encoder: downsample with conv layers
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# 28×28×1 → 14×14×32 → 7×7×64 → flatten → latent_dim
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 28→14
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 14→7
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Decoder: upsample with transposed conv
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# latent_dim → 7×7×64 → 14×14×32 → 28×28×1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder_linear&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder_conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ConvTranspose2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 7→14
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ConvTranspose2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 14→28
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder_linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reshape to feature maps
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Convolutional Autoencoder for Images&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;conv_ae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;conv_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Total parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Quick training
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer_conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training convolutional autoencoder...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Keep 2D structure for conv layers
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;optimizer_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Convolutional autoencoder trained!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Benefits: Fewer parameters, better image reconstructions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;The conv structure provides inductive bias for spatial data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Autoencoders connect deeply to principal component analysis (PCA), a classical dimensionality reduction technique. A linear autoencoder with MSE loss learns to project data onto the subspace spanned by the top \(k\) principal components—exactly what PCA does. This equivalence reveals that autoencoders generalize PCA by allowing nonlinear encoder and decoder functions. Where PCA finds the best linear \(k\)-dimensional subspace, autoencoders find the best nonlinear \(k\)-dimensional manifold. For data with nonlinear structure (like images where meaningful variations are rotations, scalings, deformations—all nonlinear), autoencoders can capture structure that PCA misses. Understanding this connection helps appreciate autoencoders as nonlinear dimension reduction and motivates their use when linear methods fail.&lt;/p&gt;

&lt;p&gt;The relationship to representation learning and transfer learning is profound. Autoencoders trained on large unlabeled datasets learn general features that often transfer well to supervised tasks. In the pre-ImageNet era, greedy layer-wise pre-training using stacked autoencoders was crucial for training deep networks. Each layer was trained as an autoencoder on features from the previous layer, progressively learning hierarchical representations. While ReLU, batch normalization, and better initialization have made this pre-training less necessary for supervised learning, the core idea—that unsupervised learning on plentiful unlabeled data can provide useful initializations for supervised tasks with limited labels—remains important and has evolved into modern self-supervised learning approaches.&lt;/p&gt;

&lt;p&gt;Autoencoders connect to information theory through the information bottleneck principle. The latent representation \(\mathbf{z}\) should capture information about \(\mathbf{x}\) relevant for reconstruction while discarding irrelevant details. Information theory quantifies this through mutual information: maximize \(I(\mathbf{x}; \mathbf{z})\) (information about input preserved in latent) while minimizing \(I(\mathbf{z}; \text{noise})\) or constraining \(I(\mathbf{z})\) (complexity of latent representation). Variational autoencoders make this connection explicit by introducing a KL divergence term that regularizes the latent distribution. Understanding autoencoders through information theory provides principled ways to think about what makes a good representation.&lt;/p&gt;

&lt;p&gt;The evolution from autoencoders to variational autoencoders (VAEs) and generative adversarial networks (GANs) shows how addressing limitations drives innovation. Standard autoencoders learn to reconstruct but don’t explicitly model the data distribution, limiting their generative ability. VAEs add a probabilistic framework, treating the encoder as computing a distribution over latent codes and adding a regularization term that shapes this distribution to be well-behaved (typically standard Gaussian). This enables principled sampling and interpolation. GANs take a completely different approach, using adversarial training instead of reconstruction, often generating sharper, more realistic samples. Each approach has strengths: autoencoders are simple and stable to train, VAEs provide principled probabilistic framework, GANs generate highest quality samples. Understanding autoencoders provides the foundation for appreciating these more sophisticated generative models.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.science.org/doi/10.1126/science.1127647&quot;&gt;“Reducing the Dimensionality of Data with Neural Networks” (2006)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Geoffrey E. Hinton, Ruslan Salakhutdinov&lt;br /&gt;
This seminal Science paper demonstrated that deep autoencoders could learn much better dimensionality reduction than PCA or shallow autoencoders. Hinton and Salakhutdinov introduced greedy layer-wise pre-training: train each layer as an autoencoder (actually a restricted Boltzmann machine in their case) on features from the previous layer, stacking them to build deep representations. This pre-training followed by fine-tuning enabled training networks much deeper than was previously possible (this was before ReLU and modern initialization techniques). The paper showed impressive results on visualizing high-dimensional data and compressing images, demonstrating that deep learning could learn hierarchical representations through unsupervised learning. This work was influential in the deep learning renaissance of the late 2000s, showing that depth mattered and that unsupervised pre-training could unlock it. While modern supervised learning doesn’t require autoencoder pre-training (thanks to ReLU, batch norm, and better initialization), the insights about hierarchical representation learning and unsupervised feature extraction remain important.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.cs.toronto.edu/~larocheh/publications/icml-2008-denoising-autoencoders.pdf&quot;&gt;“Extracting and Composing Robust Features with Denoising Autoencoders” (2008)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Pascal Vincent, Hugo Larochelle, Yoshua Bengio, Pierre-Antoine Manzagol&lt;br /&gt;
This paper introduced denoising autoencoders and provided theoretical justification for why they learn better representations than vanilla autoencoders. The key insight is that by corrupting inputs and training to reconstruct the clean originals, we force the network to learn the data manifold’s structure rather than merely memorizing examples. The corruption acts as regularization, preventing the network from learning the identity function even with large latent dimensions. The paper showed both theoretically and empirically that denoising autoencoders learn representations robust to input corruption, making features more useful for downstream tasks like classification. The denoising framework has influenced many subsequent methods—masked language modeling in BERT can be viewed as denoising, and many self-supervised approaches corrupt inputs and train networks to predict or reconstruct the original. This paper established corruption-and-reconstruction as a powerful unsupervised learning paradigm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://www.iro.umontreal.ca/~lisa/pointeurs/ICML2011_explicit_invariance.pdf&quot;&gt;“Contractive Auto-Encoders: Explicit Invariance During Feature Extraction” (2011)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Salah Rifai, Pascal Vincent, Xavier Muller, Xavier Glorot, Yoshua Bengio&lt;br /&gt;
This paper proposed contractive autoencoders, which add a penalty on the Frobenius norm of the encoder’s Jacobian. The objective becomes:&lt;/p&gt;

\[\mathcal{L} = \|\mathbf{x} - \hat{\mathbf{x}}\|^2 + \lambda \|J_f(\mathbf{x})\|_F^2\]

&lt;p&gt;where \(J_f(\mathbf{x}) = \frac{\partial f(\mathbf{x})}{\partial \mathbf{x}}\) is the encoder’s Jacobian. This penalty encourages the encoder to be insensitive to small variations in input—the latent representation should change slowly as we perturb the input slightly. The intuition is that meaningful features should be robust to small input changes (like slight translations or noise). The paper showed that contractive autoencoders learn representations with better invariance properties than vanilla or denoising autoencoders, though at computational cost of computing and regularizing the Jacobian. The work deepened theoretical understanding of what makes good representations and provided tools for encouraging specific desirable properties (invariance, sparsity, etc.) through regularization.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.6114&quot;&gt;“Auto-Encoding Variational Bayes” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Diederik P. Kingma, Max Welling&lt;br /&gt;
While introducing VAEs (covered in next chapter), this paper fundamentally changed how we think about autoencoders by providing a probabilistic framework. The authors showed that autoencoders can be viewed as learning to maximize a lower bound on the data likelihood, connecting them to principled probabilistic modeling. The variational framework addresses standard autoencoders’ limitation: the latent space might have holes where no training examples map, making sampling unreliable. VAEs regularize the latent space to follow a known distribution (typically standard Gaussian), ensuring we can sample anywhere and decode to realistic outputs. The paper’s reparameterization trick—sampling through a differentiable operation—enabled training via backpropagation. VAEs became enormously influential, spawning numerous variants and applications in generative modeling, semi-supervised learning, and representation learning. Understanding vanilla autoencoders is prerequisite to appreciating VAEs’ probabilistic sophistication and the additional guarantees it provides.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1511.05644&quot;&gt;“Adversarial Autoencoders” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Alireza Makhzani, Jonathon Shlens, Navdeep Jaitly, Ian Goodfellow, Brendan Frey&lt;br /&gt;
This paper combined autoencoders with adversarial training, using a discriminator to enforce that the latent code distribution matches a prior (like standard Gaussian) rather than using a KL divergence penalty (as VAEs do). The adversarial training makes the latent space match the prior more closely than VAE’s KL penalty while maintaining autoencoder’s reconstruction objective. The paper demonstrated that this hybrid approach can generate high-quality samples while being more flexible than VAEs in choice of latent prior (not limited to factorized Gaussians). Adversarial autoencoders showed how ideas from different frameworks (autoencoders, VAEs, GANs) could be combined, leading to models with complementary strengths. The work exemplifies the productive cross-pollination of ideas in deep learning—techniques developed for one purpose (adversarial training for GANs) proving useful when combined with other frameworks (autoencoders).&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;The most common failure mode in autoencoders is using too large a latent dimension, undermining the compression objective. With latent dimension approaching input dimension, the network can learn to pass information through nearly unchanged, discovering no meaningful structure. The symptom is perfect reconstructions but useless latent codes—they’re overcomplete and redundant. The solution is to aggressively reduce latent dimension or add other constraints (sparsity, denoising, contractive penalty). A useful heuristic: start with latent dimension 10-20× smaller than input dimension, then experiment. For MNIST (784 dimensions), try 32-64 latent dimensions. For higher-resolution images, the compression factor can be larger.&lt;/p&gt;

&lt;p&gt;Forgetting to normalize inputs causes training instability and poor reconstructions. If pixel values span [0, 255], reconstruction errors are hundreds of times larger than for normalized [0,1] values, leading to huge gradients and exploding losses. Always normalize inputs to [0,1] (dividing by 255) or standardize to mean 0, std 1. Match the decoder’s output activation to the normalization scheme: sigmoid for [0,1], tanh for [-1,1], linear for standardized. This ensures the decoder can actually produce values in the correct range.&lt;/p&gt;

&lt;p&gt;Using MSE loss for images seems intuitive but has a subtle issue: MSE weights all pixels equally, but human perception doesn’t work this way. A single misaligned pixel can cause large MSE even if the reconstruction looks perfect to humans. Conversely, blurry reconstructions (averaging pixels) can have low MSE while looking poor perceptually. For applications where perceptual quality matters, consider perceptual losses—measure distance in feature space of a pre-trained network like VGG rather than pixel space. Features from deep layers capture high-level structure (shapes, objects) that correlate better with human perception than pixel-wise distances.&lt;/p&gt;

&lt;p&gt;A powerful trick for better latent spaces is adding explicit regularization beyond just dimensionality reduction. Sparse autoencoders add L1 penalty on latent activations, encouraging most dimensions to be zero most of the time. This forces specialization—each latent dimension captures a specific aspect of variation. Variational autoencoders add KL divergence to a prior, ensuring smooth, continuous latent space. Contractive autoencoders penalize the encoder Jacobian, encouraging invariance to input perturbations. Understanding these regularization options allows tailoring autoencoders to specific desiderata—sparsity for interpretability, smoothness for interpolation, robustness for downstream tasks.&lt;/p&gt;

&lt;p&gt;When using autoencoders for pre-training (less common now but still useful in low-data regimes), a key decision is whether to fine-tune the encoder, decoder, or both. For classification, typically freeze the decoder (we only need encoder features) and add a classification head on the latent representation, fine-tuning only this head and optionally the encoder. For generation tasks, we might freeze the encoder (if we have good latent codes) and fine-tune only the decoder. For domain adaptation, fine-tuning both often works best. The choice depends on whether encoder features, decoder generation, or both need task-specific adaptation.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Autoencoders learn efficient data representations by training to reconstruct inputs through a lower-dimensional bottleneck, forcing compression of high-dimensional data into compact latent codes that capture essential structure. The encoder maps inputs to latent representations while the decoder reconstructs inputs from latent codes, with both trained jointly using reconstruction loss (MSE for continuous data, cross-entropy for binary). The bottleneck dimension controls the compression-fidelity tradeoff, with smaller latent dimensions forcing more aggressive compression and potentially more meaningful feature learning. Denoising autoencoders corrupt inputs before encoding but train to reconstruct clean originals, learning robust features that capture data structure rather than memorizing examples. The latent space in well-trained autoencoders has semantic structure, with nearby points corresponding to similar inputs and smooth interpolation enabling morphing between examples. Autoencoders serve multiple purposes: dimensionality reduction for visualization or downstream tasks, feature learning for transfer learning, denoising to remove corruption, and as foundations for more sophisticated generative models. Understanding autoencoders provides essential background for variational autoencoders and other generative approaches while demonstrating core principles of unsupervised representation learning that pervade modern self-supervised methods.&lt;/p&gt;

&lt;p&gt;The autoencoder framework exemplifies a recurring theme in machine learning: learning through reconstruction, where we force models to discover structure by requiring them to recreate data through constraints or transformations that make trivial solutions impossible.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, English. A latent code that only reconstructs can still be useless to sample from.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=9zKuYvjFFS8&quot;&gt;Variational Autoencoders&lt;/a&gt; — Arxiv Insights, English. The variational fix for that pitfall, which is the next chapter rather than a patch in this one.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=J87hffSMB60&quot;&gt;How does Stable Diffusion work? – Latent Diffusion Models EXPLAINED&lt;/a&gt; — AI Coffee Break with Letitia, English. A modern latent space that is actually sampled, so the pitfall has a destination.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12-01-02-01 Autoencoder Core Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_01_02_01_Autoencoder_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_01_02_01_Autoencoder_Core_Code</id>
   <content type="html">&lt;p&gt;When you build a PyTorch autoencoder for MNIST from scratch, the subtle bugs are rarely syntax errors—they are architectural mismatches. Use a ReLU on the final decoder layer when your pixels live in $[0, 1]$ and your loss will stall; feed noisy images to both the input &lt;em&gt;and&lt;/em&gt; target of a denoising autoencoder and you will teach the network to preserve static instead of removing it. Walking carefully through tensor shapes, activation ranges, and corruption targets turns abstract equations into clean, debuggable code.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-engineering-autoencoders-in-pytorch&quot;&gt;Key ideas: Engineering Autoencoders in PyTorch&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Symmetric Encoder–Decoder Tensor Flow&lt;/strong&gt;: Maps flattened $28 \times 28 = 784$-dimensional images down through bottleneck layers ($784 \to 256 \to 64 \to d_z$) and symmetrically back to $784$, balancing parameter count and compression ratio.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Output Activation &amp;amp; Loss Pairing&lt;/strong&gt;: Matches &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Sigmoid&lt;/code&gt; outputs in $[0, 1]$ with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BCELoss&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MSELoss&lt;/code&gt;, versus &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tanh&lt;/code&gt; outputs in $[-1, 1]$ with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MSELoss&lt;/code&gt;, preventing saturation and range clipping.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Denoising Corruption Pipeline&lt;/strong&gt;: Injects Gaussian or masking noise on-the-fly (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x_noisy = torch.clamp(x + noise, 0, 1)&lt;/code&gt;) while computing loss strictly against the &lt;em&gt;clean&lt;/em&gt; target &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Optimization &amp;amp; Reconstruction Monitoring&lt;/strong&gt;: Tracks per-pixel MSE and visual side-by-side reconstructions across epochs to verify that the bottleneck captures global shape rather than mean-gray averages.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-parameter-count-and-compression-ratio-of-an-mnist-mlp-autoencoder&quot;&gt;Worked example: Parameter Count and Compression Ratio of an MNIST MLP Autoencoder&lt;/h3&gt;

&lt;p&gt;Consider an encoder &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;784 -&amp;gt; 256 -&amp;gt; 64 -&amp;gt; 16&lt;/code&gt; and symmetric decoder &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;16 -&amp;gt; 64 -&amp;gt; 256 -&amp;gt; 784&lt;/code&gt; (all linear layers with biases).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compression ratio at the bottleneck&lt;/strong&gt;:
\(\text{Compression Ratio} = \frac{784}{16} = 49\times \quad (\text{keeping only } 2.04\% \text{ of input dimensionality}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Encoder parameter count&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Layer 1 ($784 \to 256$): $784 \times 256 + 256 = 200{,}704 + 256 = 200{,}960$.&lt;/li&gt;
      &lt;li&gt;Layer 2 ($256 \to 64$): $256 \times 64 + 64 = 16{,}384 + 64 = 16{,}448$.&lt;/li&gt;
      &lt;li&gt;Layer 3 ($64 \to 16$): $64 \times 16 + 16 = 1{,}024 + 16 = 1{,}040$.&lt;/li&gt;
      &lt;li&gt;Total encoder parameters: $200{,}960 + 16{,}448 + 1{,}040 = 218{,}448$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decoder parameter count&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;$16 \times 64 + 64 = 1{,}088$; $\; 64 \times 256 + 256 = 16{,}640$; $\; 256 \times 784 + 784 = 201{,}488$.&lt;/li&gt;
      &lt;li&gt;Total decoder parameters: $219{,}216$; grand total $= 437{,}664$ parameters ($\approx 1.67\text{ MB}$ in FP32).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Over $91\%$ of the network’s parameters live in the first and last $784 \leftrightarrow 256$ layers—which is why switching to convolutional encoders/decoders dramatically improves parameter efficiency on images.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Let’s implement autoencoders from scratch with complete training pipeline:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Autoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Standard autoencoder with fully connected layers.
    
    Architecture: Input → Encoder → Latent (bottleneck) → Decoder → Reconstruction
    
    The bottleneck forces compression - input dimensions &amp;gt; latent dimensions.
    The network must learn efficient encoding of data structure.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        input_dim: flattened input size (28*28=784 for MNIST)
        latent_dim: bottleneck dimension (compression factor = input_dim/latent_dim)
        
        We&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ll use symmetric encoder-decoder architecture with progressively
        decreasing then increasing dimensions: 784 → 256 → 128 → 32 → 128 → 256 → 784
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Autoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Encoder: progressively compress
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# No activation - let latent be unbounded
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Decoder: progressively decompress
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Sigmoid for pixel values in [0,1]
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Map input to latent representation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Reconstruct from latent code&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Full autoencoder: encode then decode&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decode&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DenoisingAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Denoising autoencoder: trained to reconstruct clean data from corrupted input.
    
    The corruption process forces learning robust features that capture
    data structure rather than memorizing training examples. Results in
    better features for downstream tasks.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;DenoisingAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Same architecture as vanilla autoencoder
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Additional regularization
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;add_noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Corrupt input with noise.
        
        For MNIST, we&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ll use Gaussian noise and clip to [0,1].
        Other corruption types: masking (zero out pixels),
        salt-and-pepper, or adversarial perturbations.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;noisy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clamp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;noisy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Training: corrupt input, encode corrupted, decode to clean.
        
        Key difference from vanilla: we add noise to input before encoding
        but compute loss against original clean input. This trains the
        network to denoise.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Corrupt input
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x_noisy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;add_noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Encode corrupted input
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_noisy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Decode (should reconstruct clean input, not noisy input!)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_noisy&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Load MNIST for demonstration
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Autoencoders on MNIST&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Data loading
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Compose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ToTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train vanilla autoencoder
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Training Vanilla Autoencoder (latent_dim=32)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Autoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer_ae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MSELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Flatten images: (batch, 1, 28, 28) → (batch, 784)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Training Denoising Autoencoder (latent_dim=32, noise=0.3)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DenoisingAutoencoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noise_factor&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer_dae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward pass (adds noise internally)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;noisy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Loss: reconstruct CLEAN data from NOISY input
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;optimizer_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;optimizer_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test and visualize
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Testing Reconstructions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Get test batch
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;next&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;iter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Vanilla autoencoder
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;recon_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_ae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Denoising autoencoder (add noise for testing too)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;test_noisy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;add_noise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;recon_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Compute reconstruction errors
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mse_ae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mse_dae&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mse_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vanilla AE reconstruction MSE: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mse_ae&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Denoising AE reconstruction MSE: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mse_dae&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Visualize some reconstructions
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;n_display&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Displaying first &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_display&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; test images with reconstructions...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Reshape for visualization
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;originals&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_display&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;recon_ae_imgs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;recon_ae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_display&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;recon_dae_imgs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;recon_dae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_display&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;28&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cpu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Print shapes (would display in actual notebook)
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Original shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;originals&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Reconstructions shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;recon_ae_imgs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;## Video tham khảo
&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xem&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trước&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;What&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;are&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Autoencoders&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;](&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;https&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;www&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;youtube&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;com&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;watch&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;qiUEgSCyY5o&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;err&quot;&gt;—&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;IBM&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Technology&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;English&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;The&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;two&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;module&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;the&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;core&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;code&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;should&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;have&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;PyTorch&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Tutorial&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;06&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Training&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Pipeline&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;](&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;https&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;www&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;youtube&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;com&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;watch&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;VVDHU_TWwUg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;err&quot;&gt;—&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Patrick&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Loeber&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;English&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;once&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;encode&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decode&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Lecture&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;|&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Generative&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;](&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;https&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;www&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;youtube&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;com&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;watch&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;WoItGTWV54&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;err&quot;&gt;—&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Stanford&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;University&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;School&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;of&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Engineering&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;English&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;What&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;healthy&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;reconstruction&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;looks&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;so&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bug&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;visible&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</content>
 </entry>
 
 <entry>
   <title>12-01-01 Autoencoder Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_01_01_Autoencoder_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_01_01_Autoencoder_Theory</id>
   <content type="html">&lt;p&gt;At first glance, training a neural network to output its own input looks like the most pointless objective in machine learning—an identity function $f(x) = x$ achieves zero loss immediately. The entire theoretical richness of autoencoders lies in &lt;em&gt;breaking&lt;/em&gt; that trivial solution: by imposing bottlenecks, injecting noise, penalizing average neuron activation, or shrinking the encoder’s Jacobian, we force the network to internalize the statistical regularities of the data distribution.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mathematical-theory-of-autoencoders&quot;&gt;Key ideas: Mathematical Theory of Autoencoders&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Empirical Risk &amp;amp; Reconstruction Geometry&lt;/strong&gt;: Connects MSE loss to Gaussian log-likelihood and Binary Cross-Entropy to Bernoulli log-likelihood, showing how the choice of reconstruction loss encodes assumptions about pixel noise.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Eckart–Young–Mirsky Theorem &amp;amp; Linear Autoencoders&lt;/strong&gt;: Proves why a linear autoencoder with bottleneck width $k$ recovers the top-$k$ singular subspace of the data matrix $X$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Sparse &amp;amp; Contractive Regularization&lt;/strong&gt;: Adds KL-divergence sparsity penalties $D_{\text{KL}}(\rho | \hat{\rho}_j)$ on hidden activations or Frobenius-norm penalties $|J_f(x)|_F^2$ on the encoder Jacobian to make representations locally invariant to small perturbations.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Denoising Score Connection&lt;/strong&gt;: Reveals that a Denoising Autoencoder trained with Gaussian corruption $\tilde{x} = x + \sigma\epsilon$ learns a vector field $g(f(\tilde{x})) - \tilde{x} \propto \nabla_{\tilde{x}} \log p_\sigma(\tilde{x})$, foreshadowing modern score-based diffusion models.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-sparse-kl-penalty-and-contractive-jacobian-norm&quot;&gt;Worked example: Computing Sparse KL Penalty and Contractive Jacobian Norm&lt;/h3&gt;

&lt;p&gt;Suppose a single-layer sigmoid encoder $z = \sigma(Wx)$ has weight vector $w = [2.0,\, -1.0]$ for one hidden neuron. Across a mini-batch, this neuron’s average activation is $\hat{\rho} = 0.40$, while our target sparsity level is $\rho = 0.05$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Bernoulli KL Sparsity Penalty $D_{\text{KL}}(\rho | \hat{\rho})$&lt;/strong&gt;:
\(D_{\text{KL}}(0.05 \| 0.40) = 0.05\ln\frac{0.05}{0.40} + 0.95\ln\frac{0.95}{0.60}\)
\(= 0.05\ln(0.125) + 0.95\ln(1.5833) = 0.05(-2.0794) + 0.95(0.4595) = -0.1040 + 0.4365 = 0.3325\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Contractive Jacobian Penalty $|J_f(x)|_F^2$ at a point where $z = 0.5$&lt;/strong&gt;:
For a sigmoid unit, $\frac{\partial z}{\partial x_j} = z(1 - z)\,w_j$. At $z = 0.5$, $z(1-z) = 0.25$.
\(J_f(x) = [0.25 \cdot 2.0,\; 0.25 \cdot (-1.0)] = [0.50,\; -0.25].\)
\(\|J_f(x)\|_F^2 = 0.50^2 + (-0.25)^2 = 0.25 + 0.0625 = 0.3125.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Both penalties act as geometric brakes on capacity—the sparsity term pushes the average firing rate down toward $5\%$, while the contractive term directly shrinks sensitivity to input jitter.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;autoencoders-learning-efficient-representations&quot;&gt;Autoencoders: Learning Efficient Representations&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/2/28/Autoencoder_structure.png/600px-Autoencoder_structure.png&quot; alt=&quot;Autoencoder Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc Autoencoder với encoder và decoder. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Autoencoders represent a fundamentally different paradigm in neural network training compared to the supervised learning we’ve studied so far. Instead of learning to map inputs to labeled outputs, autoencoders learn to reconstruct their inputs through an information bottleneck. This seemingly circular task—predicting the input from itself—becomes meaningful when we constrain the network to pass information through a lower-dimensional hidden layer called the latent space or code. By forcing the network to compress and then decompress the input, we compel it to learn efficient representations that capture the essential structure of the data while discarding noise and irrelevant details.&lt;/p&gt;

&lt;p&gt;The power of autoencoders lies not in the reconstruction itself but in what they learn during the process. The encoder learns to extract the most important features from high-dimensional data and compress them into a compact representation. The decoder learns to generate realistic data from these compressed representations. The latent space that emerges has remarkable properties: nearby points in latent space often correspond to semantically similar inputs, and we can interpolate smoothly between points to generate novel, realistic examples. These properties make autoencoders valuable for dimensionality reduction, denoising, anomaly detection, feature learning for downstream tasks, and as building blocks for more sophisticated generative models.&lt;/p&gt;

&lt;p&gt;Understanding autoencoders requires appreciating the interplay between capacity and constraint. If the latent dimension equals or exceeds the input dimension, the network can simply learn the identity function, copying inputs through unchanged—useless for learning meaningful structure. The bottleneck—making the latent dimension smaller than the input—forces the network to make choices about what to preserve. With a 784-dimensional input image compressed to 32 latent dimensions, the network cannot possibly encode every pixel independently. It must discover higher-level features like edges, shapes, and textures that compactly represent the image’s essential content. This compression isn’t arbitrary but learned from data, adapting to the specific structure present in the training distribution.&lt;/p&gt;

&lt;p&gt;The historical significance of autoencoders extends beyond their practical applications. They were among the first successful unsupervised learning methods in deep learning, demonstrating that neural networks could learn meaningful representations without labeled data. This influenced the development of pre-training strategies that enabled training deeper networks in the pre-ReLU era. Modern self-supervised learning and contrastive methods can be seen as descendants of autoencoder ideas—learning representations by predicting or reconstructing parts of the input from other parts. The autoencoder framework also introduced the encoder-decoder architecture pattern that has proven enormously influential, appearing in sequence-to-sequence models, variational autoencoders, and generative adversarial networks.&lt;/p&gt;

&lt;p&gt;Yet autoencoders have important limitations that motivate more sophisticated generative models. Standard autoencoders learn to compress and reconstruct training data but don’t necessarily learn a good generative model—the latent space might have “holes” where no training examples map, making random sampling produce unrealistic outputs. They don’t explicitly model the data distribution, limiting their theoretical guarantees. And the reconstruction loss, while intuitive, might not capture perceptual similarity (two images can be pixel-wise different yet perceptually similar, or pixel-wise similar yet perceptually different). These limitations led to variational autoencoders (which model distributions explicitly), generative adversarial networks (which use adversarial training instead of reconstruction loss), and perceptual losses (which measure similarity in feature space rather than pixel space). Understanding vanilla autoencoders provides the foundation for appreciating these more advanced techniques.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;The mathematical framework of autoencoders is elegantly simple yet rich in implications. An autoencoder consists of two neural networks composed sequentially: an encoder \(f_\phi\) parameterized by \(\phi\) and a decoder \(g_\theta\) parameterized by \(\theta\). Given input \(\mathbf{x} \in \mathbb{R}^{d}\), the encoder produces a latent representation:&lt;/p&gt;

\[\mathbf{z} = f_\phi(\mathbf{x}) \in \mathbb{R}^{k}\]

&lt;p&gt;where \(k &amp;lt; d\) enforces the bottleneck (though we’ll discuss cases where this isn’t strictly required). The decoder reconstructs from the latent representation:&lt;/p&gt;

\[\hat{\mathbf{x}} = g_\theta(\mathbf{z}) = g_\theta(f_\phi(\mathbf{x})) \in \mathbb{R}^{d}\]

&lt;p&gt;The training objective minimizes reconstruction error:&lt;/p&gt;

\[\mathcal{L}(\mathbf{x}, \hat{\mathbf{x}}) = \|\mathbf{x} - \hat{\mathbf{x}}\|^2\]

&lt;p&gt;for continuous data (mean squared error), or:&lt;/p&gt;

\[\mathcal{L}(\mathbf{x}, \hat{\mathbf{x}}) = -\sum_{i=1}^{d} [x_i \log(\hat{x}_i) + (1-x_i)\log(1-\hat{x}_i)]\]

&lt;p&gt;for binary data (binary cross-entropy, treating each dimension as independent Bernoulli).&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The choice of loss function embodies assumptions about the data and noise model. MSE assumes Gaussian noise: we’re modeling $$p(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z}) = \mathcal{N}(\mathbf{x}; g_\theta(\mathbf{z}), \sigma^2 I)\(, and minimizing MSE is equivalent to maximum likelihood under this assumption. Binary cross-entropy assumes Bernoulli noise: each pixel is independently binary with probability\)\hat{x}_i$$. For images with continuous values in [0,1], this is actually modeling each pixel as a probability, which seems odd but works reasonably in practice. More sophisticated approaches use perceptual losses based on feature distances in pre-trained networks, better capturing perceptual similarity.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The bottleneck dimension \(k\) is the key hyperparameter controlling the compression-fidelity tradeoff. Very small \(k\) (like 2-3 dimensions) creates extreme compression, forcing the network to capture only the most essential variations in data. This is useful for visualization (we can plot the 2D latent space) but may lose important details. Moderate \(k\) (32-128 dimensions for image datasets) balances compression and reconstruction quality. Large \(k\) (approaching input dimension) reduces compression pressure but might not learn interesting structure.&lt;/p&gt;

&lt;p&gt;Interestingly, even with \(k \geq d\) (no dimensional bottleneck), we can force meaningful learning through other constraints. Sparse autoencoders add a sparsity penalty to the latent activations:&lt;/p&gt;

\[\mathcal{L}_{\text{sparse}} = \|\mathbf{x} - \hat{\mathbf{x}}\|^2 + \lambda \sum_{j=1}^{k} KL(\rho \| \hat{\rho}_j)\]

&lt;p&gt;where \(\rho\) is a target sparsity level (e.g., 0.05) and \(\hat{\rho}_j\) is the average activation of latent unit \(j\) over the training set. The KL divergence penalty encourages most latent units to be inactive (near zero) most of the time, forcing different units to specialize in different patterns. This creates a sparse, distributed representation even without dimensional bottleneck.&lt;/p&gt;

&lt;p&gt;Denoising autoencoders corrupt the input \(\mathbf{x}\) with noise to create \(\tilde{\mathbf{x}}\) but train to reconstruct the original:&lt;/p&gt;

\[\mathcal{L} = \|\mathbf{x} - g_\theta(f_\phi(\tilde{\mathbf{x}}))\|^2\]

&lt;p&gt;The corruption process might add Gaussian noise, mask random pixels, or add salt-and-pepper noise. This forces the encoder to learn robust features invariant to the noise type, and the decoder to learn to “fill in” corrupted regions based on uncorrupted context. Denoising autoencoders often learn better features than vanilla autoencoders because the denoising task requires understanding data structure, not just memorizing training examples.&lt;/p&gt;

&lt;p&gt;The latent space geometry deserves careful analysis. In a well-trained autoencoder on image data, nearby points in latent space typically correspond to perceptually similar images. We can interpolate linearly between two latent codes \(\mathbf{z}_1\) and \(\mathbf{z}_2\):&lt;/p&gt;

\[\mathbf{z}_t = (1-t)\mathbf{z}_1 + t\mathbf{z}_2, \quad t \in [0,1]\]

&lt;p&gt;and decode \(g_\theta(\mathbf{z}_t)\) to generate intermediate images. For well-behaved autoencoders, this produces smooth transitions (morphing one face into another, for example). However, standard autoencoders don’t guarantee good interpolation—there might be “holes” in latent space where no training examples map, and interpolating through these holes produces unrealistic reconstructions. Variational autoencoders address this by explicitly regularizing the latent space to be continuous and well-behaved.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;To build concrete intuition for how autoencoders learn representations, let’s trace through training on MNIST digits. Suppose we compress 28×28=784 pixel images to 32-dimensional latent codes.&lt;/p&gt;

&lt;p&gt;Initially, with random weights, the encoder produces meaningless latent codes and the decoder generates random noise as reconstruction. The reconstruction error is enormous—we’re trying to match 784 pixel values but getting essentially random outputs. Gradients via backpropagation indicate how to adjust encoder and decoder weights to reduce this error.&lt;/p&gt;

&lt;p&gt;As training progresses, the encoder learns to extract increasingly meaningful features. Early on, it might learn that certain pixels tend to be dark (in the background) versus light (in digit strokes), encoding this as latent dimensions representing average brightness in different regions. This primitive encoding already allows better reconstruction than random noise—the decoder learns to generate images with appropriate overall brightness patterns.&lt;/p&gt;

&lt;p&gt;With more training, the encoder discovers edge patterns. Certain latent dimensions become active when the digit has vertical strokes (1, 4, 7), others for curves (0, 6, 8, 9), others for horizontal segments (2, 3, 5, 7). The decoder learns to reconstruct digit-like images from these edge indicators. Reconstructions now capture the general shape of digits, though details might be blurry.&lt;/p&gt;

&lt;p&gt;Eventually, the 32 latent dimensions self-organize into a meaningful representation space. Dimensions might encode: digit identity (roughly which digit), stroke thickness, slant, size, position in image. This learned representation emerges purely from the reconstruction objective—we never told the network what features to learn, only to compress and reconstruct accurately.&lt;/p&gt;

&lt;p&gt;Consider what happens when we encode several “3”s from the training set. Their latent codes cluster together in the 32D latent space because they share structure (similar edges, curves, topology). Different “3”s (thick, thin, slanted) map to slightly different but nearby latent points. Meanwhile, “8”s cluster in a different region of latent space—they share the topological structure (two loops) that “3”s lack. The latent space has self-organized to reflect digit categories and variations within categories, all without any labels.&lt;/p&gt;

&lt;p&gt;Now for the interpolation test. Encode a “3” to get \(\mathbf{z}_3\) and encode an “8” to get \(\mathbf{z}_8\). Decode intermediate points:&lt;/p&gt;

&lt;p&gt;\(\mathbf{z}_{0.0} = \mathbf{z}_3 \to\) decodes to “3”&lt;br /&gt;
\(\mathbf{z}_{0.25} = 0.75\mathbf{z}_3 + 0.25\mathbf{z}_8 \to\) decodes to “3 with hint of 8”&lt;br /&gt;
\(\mathbf{z}_{0.5} = 0.5\mathbf{z}_3 + 0.5\mathbf{z}_8 \to\) decodes to ambiguous digit&lt;br /&gt;
\(\mathbf{z}_{0.75} = 0.25\mathbf{z}_3 + 0.75\mathbf{z}_8 \to\) decodes to “8 with hint of 3”&lt;br /&gt;
\(\mathbf{z}_{1.0} = \mathbf{z}_8 \to\) decodes to “8”&lt;/p&gt;

&lt;p&gt;If interpolation is smooth, we see gradual morphing. If there are discontinuities, we might get unrealistic outputs at intermediate points. This interpolation quality is a diagnostic for whether the latent space is well-structured.&lt;/p&gt;

&lt;p&gt;Denoising autoencoders add an interesting twist. Suppose we corrupt a “7” by randomly zeroing 20% of pixels. The corrupted image is ambiguous—it could be a damaged “7” or possibly a “1”. The denoising autoencoder must use context (uncorrupted pixels) to infer the most likely original digit. This requires understanding digit structure, not just memorizing pixel patterns. The encoder learns to extract robust features despite corruption, and the decoder learns to generate complete digits from partial evidence. The learned representations are often more useful for downstream tasks than those from vanilla autoencoders because they’re forced to capture semantic structure rather than low-level pixel statistics.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, English. Reconstruction as the training signal, with no labels.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, English. The undercomplete versus overcomplete distinction the theory section needs.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. The information-bottleneck view of the same objective.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>12 Autoencoders</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter12/12_00_Introduction</id>
   <content type="html">&lt;p&gt;How can you compress a 784-pixel handwritten digit down to just 16 numbers and still reconstruct it faithfully—without anyone ever telling you what digit it is? That bottleneck puzzle is the soul of the autoencoder. By forcing information through a narrow corridor, an autoencoder cannot afford to memorize pixel-by-pixel noise; it is forced to discover the hidden geometry—stroke slant, loop thickness, and digit identity—that actually governs the data.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-architecture-of-autoencoders&quot;&gt;Key ideas: The Architecture of Autoencoders&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Low-Rank Projections &amp;amp; PCA Equivalence&lt;/strong&gt;: Establishes that a linear autoencoder with MSE loss spans the exact same subspace as Principal Component Analysis (PCA), giving a concrete linear-algebra baseline before adding nonlinearities.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Nonlinear Manifold Compression&lt;/strong&gt;: Uses deep encoders $z = f_\phi(x)$ and decoders $\hat{x} = g_\theta(z)$ to unfold curved data manifolds that linear PCA cannot capture.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Regularization Against the Identity Trap&lt;/strong&gt;: Explains why overcomplete autoencoders (where $\dim(z) \ge \dim(x)$) trivially copy inputs unless constrained by sparsity, noise corruption (denoising), or Jacobian penalties (contractive).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Latent Space Structure &amp;amp; Downstream Utility&lt;/strong&gt;: Connects compressed representations $z$ to anomaly detection (via reconstruction error), visualization, and modern neural codecs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-linear-bottleneck-compression-on-a-3d-data-point&quot;&gt;Worked example: Linear Bottleneck Compression on a 3D Data Point&lt;/h3&gt;

&lt;p&gt;Consider an input vector $x = [2,\, 4,\, 2]^\top \in \mathbb{R}^3$ passed through a 1-dimensional linear bottleneck with tied weights $w = \frac{1}{\sqrt{6}}[1,\, 2,\, 1]^\top$ (note $|w|_2 = 1$).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Encode to scalar latent code $z = w^\top x$&lt;/strong&gt;:
\(z = \frac{1}{\sqrt{6}}(1\cdot 2 + 2\cdot 4 + 1\cdot 2) = \frac{12}{\sqrt{6}} = 2\sqrt{6} \approx 4.899.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decode back to $\mathbb{R}^3$ via $\hat{x} = w z$&lt;/strong&gt;:
\(\hat{x} = \frac{1}{\sqrt{6}}\begin{bmatrix}1\\2\\1\end{bmatrix} \cdot 2\sqrt{6} = \begin{bmatrix}2\\4\\2\end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Now perturb the input with off-manifold noise $x_{\text{noisy}} = [3,\, 4,\, 1]^\top$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;New latent code: $z’ = \frac{1}{\sqrt{6}}(3 + 8 + 1) = \frac{12}{\sqrt{6}} = 2\sqrt{6}$ (identical!).&lt;/li&gt;
      &lt;li&gt;Reconstruction: $\hat{x}’ = [2,\, 4,\, 2]^\top$, with MSE $= \frac{1}{3}[(3-2)^2 + 0^2 + (1-2)^2] = \frac{2}{3} \approx 0.667$.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: The bottleneck annihilates the component orthogonal to the learned manifold ($[1, 0, -1]^\top$), automatically denoising the signal and flagging out-of-distribution deviations via higher reconstruction error.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Autoencoders learn efficient data representations through unsupervised learning. They compress input data into a lower-dimensional latent space and reconstruct it. This chapter covers vanilla autoencoders, denoising autoencoders, sparse autoencoders, and applications in dimensionality reduction, denoising, and anomaly detection.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After autoencoder theory, see &lt;strong&gt;12-99 Modern Applications and Updates&lt;/strong&gt; for diffusion latents, neural audio codecs, and masked autoencoders.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qiUEgSCyY5o&quot;&gt;What are Autoencoders?&lt;/a&gt; — IBM Technology, English. An autoencoder compresses and reconstructs, which is this chapter.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, English. Where that bottleneck sits among other generative models.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. The 2024 lecture’s autoencoder segment, before it moves on to VAEs.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Between 2020 and 2026, generative modeling underwent a tectonic shift: unstable adversarial games gave way to denoising diffusion models and flow matching, which turn generation into solving a smooth differential equation from Gaussian noise to data. Rather than replacing likelihood theory, these modern engines directly generalize it—connecting score matching, variational lower bounds, and continuous normalizing flows into one unified framework.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-diffusion-score-matching-and-flow-matching&quot;&gt;Key ideas: Diffusion, Score Matching, and Flow Matching&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Forward Corruption &amp;amp; Reverse Denoising (DDPM)&lt;/strong&gt;: Gradually adds Gaussian noise to data $x_0 \to x_t$ via a closed-form kernel, then trains a neural network $\epsilon_\theta(x_t, t)$ to predict the noise and reverse the Markov chain.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Score Functions &amp;amp; Langevin Dynamics&lt;/strong&gt;: Interprets denoising as estimating the Stein score $\nabla_x \log p_t(x)$—the vector field pointing uphill toward higher data density—without ever computing the partition function $Z$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Conditional Flow Matching (Rectified Flows)&lt;/strong&gt;: Replaces curved stochastic diffusion paths with straight-line linear interpolants $x_t = (1-t)x_0 + t x_1$ and regresses a velocity field $v_\theta(x_t, t)$ directly onto $x_1 - x_0$, enabling high-quality generation in far fewer ODE steps.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Classifier-Free Guidance (CFG)&lt;/strong&gt;: Steers conditional generation by extrapolating between conditional and unconditional predictions, trading diversity for sharper prompt adherence.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-one-exact-flow-matching-training--sampling-step-in-2d&quot;&gt;Worked example: One Exact Flow-Matching Training &amp;amp; Sampling Step in 2D&lt;/h3&gt;

&lt;p&gt;Suppose a 2D data point is $x_1 = (4.0, 2.0)$, sampled noise is $x_0 = (0.0, -2.0)$, and we sample time $t = 0.25$ along the linear interpolant $x_t = (1 - t)x_0 + t x_1$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the noisy interpolant $x_t$&lt;/strong&gt;:
\(x_{0.25} = 0.75\,(0.0, -2.0) + 0.25\,(4.0, 2.0) = (0.0, -1.5) + (1.0, 0.5) = (1.0,\; -1.0).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the exact target velocity $u_t = \frac{dx_t}{dt} = x_1 - x_0$&lt;/strong&gt;:
\(u_t = (4.0 - 0.0,\; 2.0 - (-2.0)) = (4.0,\; 4.0).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate the Flow Matching MSE loss&lt;/strong&gt; if our network predicts $v_\theta(x_{0.25}, 0.25) = (3.5, 4.5)$:
\(\mathcal{L}_{\text{FM}} = \|v_\theta - u_t\|_2^2 = (3.5 - 4.0)^2 + (4.5 - 4.0)^2 = 0.25 + 0.25 = 0.50.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Take one Euler ODE sampling step from $x_{0.25}$ with step size $\Delta t = 0.25$&lt;/strong&gt;:
\(x_{0.50} = x_{0.25} + \Delta t \cdot v_\theta(x_{0.25}, 0.25) = (1.0, -1.0) + 0.25(3.5, 4.5) = (1.875,\; 0.125).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Unlike GANs, training reduces to simple regression on straight velocity vectors, and because the true path is linear, even coarse Euler steps stay close to the exact trajectory.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-generative-modeling-after-gans--diffusion-and-flow-matching&quot;&gt;Optional: generative modeling after GANs — diffusion and flow matching&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace the likelihood / MLE / evaluation fundamentals in this chapter, and it does &lt;strong&gt;not&lt;/strong&gt; steal the VAE or GAN chapters. It records the 2022–2026 shift: &lt;strong&gt;score-based diffusion&lt;/strong&gt; and &lt;strong&gt;flow matching&lt;/strong&gt; became the default generative families for images (and then video/audio).&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The core idea of the chapter still holds: a generative model is a distribution \(p_\theta(\mathbf{x})\) you can sample and, ideally, score. What changed is &lt;em&gt;which&lt;/em&gt; \(p_\theta\) products ship.&lt;/p&gt;

&lt;h2 id=&quot;1-denoising-diffusion-landscape&quot;&gt;1. Denoising diffusion (landscape)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2006.11239&quot;&gt;Ho et al., 2020&lt;/a&gt; (DDPM) and the 2022 latent-diffusion wave (&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;Rombach et al., 2022&lt;/a&gt;, Stable Diffusion) train a denoiser \(\boldsymbol{\epsilon}_\theta(\mathbf{x}_t, t)\) on a forward noising process. The usual simplified loss is&lt;/p&gt;

\[\mathcal{L} = \mathbb{E}_{t,\mathbf{x}_0,\boldsymbol{\varepsilon}}\big\|\boldsymbol{\varepsilon} - \boldsymbol{\varepsilon}_\theta(\mathbf{x}_t, t)\big\|^2, \quad
\mathbf{x}_t = \sqrt{\bar{\alpha}_t}\,\mathbf{x}_0 + \sqrt{1-\bar{\alpha}_t}\,\boldsymbol{\varepsilon}.\]

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2212.09748&quot;&gt;Peebles &amp;amp; Xie, 2023&lt;/a&gt; (DiT) put that denoiser on a Transformer; &lt;a href=&quot;https://arxiv.org/abs/2403.03206&quot;&gt;Esser et al., 2024&lt;/a&gt; (SD3) move toward flow-matching / rectifier objectives in latent space.&lt;/p&gt;

&lt;h2 id=&quot;2-flow-matching&quot;&gt;2. Flow matching&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.02747&quot;&gt;Lipman et al., 2023&lt;/a&gt; train a vector field \(v_\theta(\mathbf{x}, t)\) along a probability path between noise and data. A simple linear path \(\mathbf{x}_t = (1-t)\mathbf{z} + t\mathbf{x}\) yields the regression&lt;/p&gt;

\[\mathcal{L}_{\mathrm{FM}} = \mathbb{E}_{t,\mathbf{x},\mathbf{z}}\big\| v_\theta(\mathbf{x}_t, t) - (\mathbf{x} - \mathbf{z}) \big\|^2.\]

&lt;p&gt;This is the 2023–2025 “cleaner ODE” story that many new image/video models advertise (Stable Diffusion 3, Flux-class systems).&lt;/p&gt;

&lt;h2 id=&quot;3-concrete-applications&quot;&gt;3. Concrete applications&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Text-to-image / video&lt;/strong&gt;: Stable Diffusion, SDXL, SD3, commercial video diffusion.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Data science&lt;/strong&gt;: synthetic tabular/image augmentation when privacy forbids real samples (still evaluate with the FID / density ideas from this chapter).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Do not skip AE/GAN&lt;/strong&gt;: autoencoders (Chapter 12) became the &lt;em&gt;latent&lt;/em&gt; of diffusion; GANs (Chapter 14) remain for faces, inversion, and fast one-step generators.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-widely-used-software&quot;&gt;4. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/diffusers&quot;&gt;Hugging Face diffusers&lt;/a&gt; — DDPM, LDM, flow-matching pipelines.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/Stability-AI/sd3&quot;&gt;Stability-AI / SD3&lt;/a&gt; and &lt;a href=&quot;https://github.com/black-forest-labs/flux&quot;&gt;black-forest-labs/flux&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/openai/guided-diffusion&quot;&gt;openai/guided-diffusion&lt;/a&gt; — the 2022 reference trainer.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-citations-20222026&quot;&gt;5. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2112.10752&quot;&gt;High-Resolution Image Synthesis with Latent Diffusion Models (Rombach et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2212.09748&quot;&gt;Scalable Diffusion Models with Transformers — DiT (Peebles &amp;amp; Xie, 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2210.02747&quot;&gt;Flow Matching for Generative Modeling (Lipman et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2403.03206&quot;&gt;Scaling Rectified Flow Transformers for High-Resolution Image Synthesis (Esser et al., 2024)&lt;/a&gt; — SD3.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;6-how-this-complements-the-core-notes&quot;&gt;6. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Learn MLE, implicit vs explicit density, and the toy GAN in this chapter first. Diffusion and flow matching are the &lt;strong&gt;update to the family tree&lt;/strong&gt;, not a replacement for those definitions. Details of VAEs and GANs stay in Chapters 13–14.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=firXjwZ_6KI&quot;&gt;Flow-Matching vs Diffusion Models explained side by side&lt;/a&gt; — AI Coffee Break with Letitia, English. Flow matching beside denoising diffusion is the 2022–2026 landscape this note draws.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But how do AI images and videos actually work?&lt;/td&gt;
          &lt;td&gt;Guest video by Welch Labs](https://www.youtube.com/watch?v=iv-5mZ_9CPY) — 3Blue1Brown, English. How a diffusion model actually turns noise into an image, including classifier-free guidance.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=J87hffSMB60&quot;&gt;How does Stable Diffusion work? – Latent Diffusion Models EXPLAINED&lt;/a&gt; — AI Coffee Break with Letitia, English. Latent diffusion, the practical form those ideas shipped in.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-01 Generative Models - Core Concepts</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_01_Generative_Models_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_01_Generative_Models_Fundamentals</id>
   <content type="html">&lt;p&gt;Every major breakthrough in modern AI—from GPT’s next-token prediction to Stable Diffusion’s image synthesis—grows from a single root: learning a probability distribution over complex objects. Before diving into specialized architectures like VAEs, GANs, or diffusion models, mastering the shared mathematical vocabulary of likelihood, latent variables, and distribution divergences gives you a compass that works across the entire generative landscape.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-core-pillars-of-generative-fundamentals&quot;&gt;Key ideas: Core Pillars of Generative Fundamentals&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Joint vs. Conditional Modeling&lt;/strong&gt;: Contrasts discriminative models $p_\theta(y \mid x)$ with generative models $p_\theta(x)$ or $p_\theta(x, y)$, clarifying why generative models enable sampling, anomaly detection, and imputation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — The Likelihood–Sampling Trade-off&lt;/strong&gt;: Maps out why autoregressive models give exact likelihoods at slow sequential sampling cost, while implicit models sample fast without tractable densities.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Latent-Space Geometry&lt;/strong&gt;: Introduces continuous and discrete latent codes $z$ as compressed semantic coordinates that explain observable high-dimensional variation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Experimental Verification&lt;/strong&gt;: Pairs theoretical definitions with toy PyTorch experiments so abstract concepts like mode dropping and KL asymmetry are anchored in concrete code.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-marginal-likelihood-via-bayes-rule-on-a-discrete-latent-model&quot;&gt;Worked example: Computing Marginal Likelihood via Bayes’ Rule on a Discrete Latent Model&lt;/h3&gt;

&lt;p&gt;Suppose a simple generative model has a binary latent variable $z \in {0, 1}$ with prior $p(z=0) = 0.6$, $p(z=1) = 0.4$, and emits a scalar $x$ with conditional densities $p(x \mid z=0) = 0.2$ and $p(x \mid z=1) = 0.8$ at an observed point $x^*$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the joint probabilities $p(x^&lt;em&gt;, z) = p(x^&lt;/em&gt; \mid z)\,p(z)$&lt;/strong&gt;:
\(p(x^*, z=0) = 0.2 \times 0.6 = 0.12, \qquad p(x^*, z=1) = 0.8 \times 0.4 = 0.32.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Marginalize out $z$ to obtain the data likelihood $p(x^*)$&lt;/strong&gt;:
\(p(x^*) = p(x^*, z=0) + p(x^*, z=1) = 0.12 + 0.32 = 0.44.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Infer the posterior distribution $p(z \mid x^*)$ via Bayes’ rule&lt;/strong&gt;:
\(p(z=1 \mid x^*) = \frac{0.32}{0.44} = \frac{8}{11} \approx 0.7273, \qquad p(z=0 \mid x^*) = \frac{3}{11} \approx 0.2727.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Even though $z=0$ had the higher prior ($0.6$), the evidence $x^*$ shifts posterior belief decisively to $z=1$ ($72.7\%$). When $z$ becomes a 128-dimensional continuous vector, that innocent sum turns into an intractable integral—setting up the exact motivation for VAEs in Chapter 13.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Generative models fundamentals:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Theory&lt;/strong&gt; — concept overview, math, intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implementation&lt;/strong&gt; — code, papers, pitfalls, takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. The split between density models and implicit samplers.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, English. The same split in the CS231n lecture this block follows.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, English. An autoregressive model, the first implementation in the block.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-01-02 Generative Models Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_01_02_Generative_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_01_02_Generative_Implementation</id>
   <content type="html">&lt;p&gt;Knowing the math of generative models on a whiteboard is only half the craft; the real intuition arrives the moment you train two competing paradigms—an explicit autoregressive density estimator and an implicit adversarial generator—on the same synthetic dataset and watch how differently their losses behave. This roadmap bridges theory into working PyTorch code, guiding you from exact mixture likelihoods to adversarial pitfalls and diagnostic checks.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-from-generative-equations-to-running-code&quot;&gt;Key ideas: From Generative Equations to Running Code&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Synthetic Benchmark Design&lt;/strong&gt;: Uses low-dimensional multi-modal distributions (like 8 Gaussians on a circle) where ground-truth density and mode locations are known analytically, making every failure mode visually and numerically transparent.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Explicit Conditional Implementation&lt;/strong&gt;: Translates $p_\theta(x_1)p_\theta(x_2 \mid x_1)$ into differentiable PyTorch modules with mixture parameters and stable log-likelihood loss.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Implicit Adversarial Training Loops&lt;/strong&gt;: Implements alternating discriminator/generator updates, highlighting why optimizer state, learning-rate balance, and gradient flow govern stability.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Quantitative Model Comparison&lt;/strong&gt;: Establishes disciplined evaluation habits—comparing held-out negative log-likelihood where available alongside mode-counting diagnostics for implicit models.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-designing-the-8-gaussian-circle-geometry&quot;&gt;Worked example: Designing the 8-Gaussian Circle Geometry&lt;/h3&gt;

&lt;p&gt;Let us compute the exact coordinates of the 8 Gaussian centers arranged on a circle of radius $R = 2.0$ at angles $\theta_k = \frac{2\pi k}{8} = \frac{\pi k}{4}$ for $k = 0, \dots, 7$, each with isotropic standard deviation $\sigma = 0.1$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Center coordinates $c_k = (R\cos\theta_k,\, R\sin\theta_k)$&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;$k = 0$: $(2.000,\; 0.000)$&lt;/li&gt;
      &lt;li&gt;$k = 1$: $(2\cos 45^\circ,\; 2\sin 45^\circ) = (\sqrt{2},\; \sqrt{2}) \approx (1.414,\; 1.414)$&lt;/li&gt;
      &lt;li&gt;$k = 2$: $(0.000,\; 2.000)$&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Minimum distance between adjacent mode centers&lt;/strong&gt;:
\(d_{\text{adj}} = 2R\sin\left(\frac{\pi}{8}\right) = 4 \times 0.3827 \approx 1.531.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mode separation in standard deviations&lt;/strong&gt;:
\(\frac{d_{\text{adj}}}{\sigma} = \frac{1.531}{0.1} = 15.31\sigma.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Because adjacent clusters sit more than $15\sigma$ apart, a unimodal Gaussian or an independent factorized model cannot bridge them without dumping huge probability mass in the empty interior—making this benchmark an ideal litmus test for both autoregressive and GAN implementations.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Generative models implementation:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Autoregressive Model&lt;/strong&gt; — toy mixture data and AR training&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Toy GAN, Papers, and Pitfalls&lt;/strong&gt; — comparison demos, metrics, takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, English. The autoregressive code path.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, English. The toy GAN the second code lesson trains.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. Which of the two you are implementing, so the losses do not get mixed.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-01-02-02 Toy GAN, Papers, and Pitfalls</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_01_02_02_Toy_GAN_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_01_02_02_Toy_GAN_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Run a toy GAN on a ring of eight Gaussians and you will witness one of the most famous pathologies in deep learning unfold in real time: instead of covering all eight islands, the generator often discovers one island that fools the discriminator and piles every single sample onto that one spot. Watching an autoregressive model and a GAN side-by-side on the exact same 2D ring turns abstract textbook warnings—mode collapse, vanishing gradients, and likelihood-vs-realism gaps—into something you can measure in five seconds.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-implicit-gans-mode-collapse-and-diagnostics&quot;&gt;Key ideas: Implicit GANs, Mode Collapse, and Diagnostics&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Implicit Pushforward Distributions&lt;/strong&gt;: Defines $p_G$ not by a density formula, but by transforming noise $z \sim \mathcal{N}(0, I)$ through a deterministic map $x = G_\theta(z)$, making sampling $O(1)$ forward pass while sacrificing exact likelihood.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Adversarial Minimax Dynamics&lt;/strong&gt;: Contrasts single-objective gradient descent (MLE) with two-player zero-sum optimization $\min_G \max_D V(D, G)$, where simultaneous gradient updates can orbit or collapse rather than converge.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Mode Coverage vs. Sample Precision&lt;/strong&gt;: Distinguishes &lt;em&gt;precision&lt;/em&gt; (are generated points near real data?) from &lt;em&gt;recall&lt;/em&gt; (are all real modes represented?), exposing why visual sharpness alone hides catastrophic mode dropping.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Empirical Failure Diagnostics&lt;/strong&gt;: Connects diagnostic scripts (counting covered modes, tracking discriminator saturation $D(x) \to 1$, comparing held-out NLL) to practical debugging in larger generative pipelines.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-quantifying-mode-collapse-and-discriminator-saturation&quot;&gt;Worked example: Quantifying Mode Collapse and Discriminator Saturation&lt;/h3&gt;

&lt;p&gt;Suppose our 8-Gaussian ring has centers $c_1, \dots, c_8$, and we draw $N = 800$ samples from a trained toy GAN. Counting samples within radius $r = 0.5$ of each center yields:
\(\text{counts} = [380,\, 390,\, 0,\, 0,\, 0,\, 0,\, 0,\, 0], \quad \text{and } 30 \text{ samples fall outside all } 8 \text{ disks.}\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mode Coverage (Recall at mode level)&lt;/strong&gt;:
Only $2$ out of $8$ modes have non-zero support, so $\text{Mode Coverage} = 2/8 = 25\%$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sample Precision (in-manifold fraction)&lt;/strong&gt;:
$(380 + 390) / 800 = 770 / 800 = 96.25\%$ of generated samples look “realistic” (right on top of true clusters), even though $75\%$ of the true distribution is completely missing!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Discriminator Saturation Gradient Check&lt;/strong&gt;:
If the discriminator outputs $D(G(z)) = 0.01$ on a fake sample, compare the original minimax generator gradient weight versus the non-saturating heuristic:
    &lt;ul&gt;
      &lt;li&gt;Minimax loss $\mathcal{L}_G = \log(1 - D(G(z)))$ has derivative $\frac{\partial \mathcal{L}_G}{\partial D} = -\frac{1}{1 - 0.01} \approx -1.01$, which multiplied by sigmoid derivative $D(1-D) = 0.0099$ gives logit gradient magnitude $\approx 0.010$ (vanishing!).&lt;/li&gt;
      &lt;li&gt;Non-saturating loss $\mathcal{L}_G^{\text{NS}} = -\log D(G(z))$ has derivative $-\frac{1}{D} = -100$, multiplied by $D(1-D) = 0.0099$ gives logit gradient magnitude $1 - D = 0.99$ (strong learning signal!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: High sample realism ($96.25\%$) can coexist with severe mode collapse ($25\%$ coverage), and switching to $-\log D(G(z))$ restores a $99\times$ stronger gradient when the generator is weak.&lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# 2. Simple GAN for comparison
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Training GAN (Implicit Density)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyGenerator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Simple generator for 2D data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Output 2D points
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyDiscriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Simple discriminator for 2D data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LeakyReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LeakyReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;gen&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyGenerator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;latent_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;disc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ToyDiscriminator&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;gen_optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0002&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;betas&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;disc_optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0002&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;betas&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BCELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training GAN on mixture of Gaussians...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Train discriminator
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# k discriminator steps per generator step
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Real data
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;batch_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,))]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_d_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Fake data
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;labels_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_d_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;loss_d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss_d_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss_d_fake&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss_d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;disc_optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Train generator
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;labels_real_for_g&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss_g&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels_real_for_g&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;loss_g&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;gen_optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: D_loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;G_loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss_g&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;D(real) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;D(fake) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate samples
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;z_sample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;samples_gan&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gen&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GAN generated &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_gan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; samples&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Checking mode coverage (samples should cluster around 8 centers)...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Check if GAN covers all modes (mode collapse detection)
# For each true center, count nearby generated samples
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_centers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;distances&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_gan&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;nearby&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;distances&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Mode &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (center &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nearby&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; nearby samples&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_gan&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt; 
       &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_centers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✓ GAN covers all modes successfully!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✗ Mode collapse detected - some modes have few/no samples&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generative Modeling Comparison&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Autoregressive Model:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Exact likelihood computable&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Stable training&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Sequential generation (slow)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Strong ordering assumptions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GAN:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Fast parallel generation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Often high sample quality&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - No explicit likelihood&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Training can be unstable&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Mode collapse risk&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;VAE (next chapter):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Explicit latent space&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Stable training&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  + Fast generation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Samples sometimes blurry&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Demonstrate likelihood-based evaluation:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Evaluating Generative Model Quality&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# For autoregressive model, we can compute exact likelihood
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Test set (held-out data from same distribution)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;data_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_mixture_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;data_test_tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Compute log-likelihood on test set
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;test_log_probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_test_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;avg_test_ll&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_log_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Autoregressive Model Test Log-Likelihood: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_test_ll&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Higher is better - model assigns high probability to test data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Generate and evaluate (samples should have similar likelihood to real data)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;samples_ar_eval&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;samples_log_probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_ar_eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;avg_sample_ll&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;samples_log_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated Samples Log-Likelihood: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_sample_ll&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Should be similar to test LL if model is good&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_test_ll&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;avg_sample_ll&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✓ Small difference (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;) indicates good model!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✗ Large difference (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diff&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;) indicates issues&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# For GAN, we can&apos;t compute likelihood, so we use proxy metrics
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GAN Evaluation (without explicit likelihood):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Visual inspection (do samples look realistic?)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Mode coverage (do samples span all modes?)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Diversity (are samples varied or repetitive?)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Discriminator score (should be ~0.5 for good generator)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;disc_scores_real&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_test_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;disc_scores_fake&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;disc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_gan&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Discriminator scores:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Real data: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;disc_scores_real&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (should be ~1.0 if D is good)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Generated: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;disc_scores_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (should be ~0.5 at equilibrium)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;disc_scores_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;disc_scores_fake&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;✓ Generator successfully fools discriminator!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Generative models connect to density estimation, a classical problem in statistics where we try to estimate probability density functions from samples. Traditional methods like kernel density estimation or parametric fitting (Gaussian mixture models) work well in low dimensions but scale poorly to high dimensions due to the curse of dimensionality. Neural network-based generative models overcome this by learning hierarchical features that capture data structure rather than explicitly representing density in raw input space. A deep generative model effectively performs density estimation in a learned feature space where data structure is simpler, then maps back to input space. This perspective helps appreciate why deep generative models succeed where classical methods fail.&lt;/p&gt;

&lt;p&gt;The relationship to unsupervised and self-supervised learning is profound. Generative models learn representations without labels, discovering structure purely from data patterns. The features learned during generative modeling often transfer well to downstream supervised tasks—autoencoders provide good initializations, GAN discriminators learn useful features, VAE encoders create meaningful latent spaces. This connects to the broader theme that large-scale unsupervised pre-training (like BERT or GPT language modeling, which are generative tasks) followed by supervised fine-tuning often outperforms purely supervised learning, especially in limited-data regimes. Understanding generative models provides insight into why unsupervised learning works and what representations emerge from generative objectives.&lt;/p&gt;

&lt;p&gt;Generative models connect to data augmentation through their ability to generate synthetic training examples. For imbalanced datasets (many examples of common classes, few of rare classes), generative models can synthesize additional minority class examples. For expensive-to-label data (medical images requiring expert annotation), generated examples can augment limited labeled sets. However, care is required: if the generative model hasn’t learned the true distribution accurately, synthetic examples might introduce bias. Best practice is to validate that generated examples aid rather than hurt downstream task performance.&lt;/p&gt;

&lt;p&gt;The evolution of evaluation metrics for generative models reflects ongoing challenges in measuring quality and diversity. Early GANs used human evaluation (time-consuming, not reproducible) or binary classifier tests (can a classifier distinguish real from fake?). Inception Score and FID provided automated metrics but have known biases and failure modes. Recent work explores learned perceptual metrics (measuring distance in learned feature spaces), precision-recall tradeoffs (quantifying quality vs diversity separately), and likelihood-based methods (for models that provide likelihoods). Understanding that no single metric is perfect guides practitioners to use multiple complementary evaluations rather than optimizing for any single metric.&lt;/p&gt;

&lt;p&gt;Finally, generative models connect to the fundamental question of what neural networks learn. By training networks to generate complex data like images or text, we’re essentially asking: what patterns, structures, and regularities exist in this data, and can networks discover them automatically? The fact that neural networks can learn to generate photorealistic faces, coherent paragraphs, or valid molecular structures demonstrates they’re capturing deep statistical regularities, not just memorizing. This learning of latent structure has implications beyond generation—it suggests neural networks are discovering representations that reflect genuine structure in the world, not just fitting training data.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-06.pdf&quot;&gt;“A tutorial on Energy-Based Learning” (2006)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Author&lt;/em&gt;: Yann LeCun&lt;br /&gt;
While not specifically about modern generative models, this tutorial established the energy-based framework that underlies much generative modeling. LeCun showed how many learning problems can be formulated as learning energy functions that assign low energy to correct/realistic outputs and high energy to incorrect/unrealistic ones. Generative models fit this framework: they learn energy landscapes where data has low energy. The tutorial covered Boltzmann machines, contrastive divergence, and other techniques that influenced later work on deep generative models. Understanding energy-based models provides theoretical foundation for why certain training procedures (like contrastive divergence or score matching) work and connects generative modeling to statistical physics and probabilistic inference. While modern generative models often use different training procedures (backpropagation with reparameterization for VAEs, adversarial training for GANs), the energy-based perspective remains valuable for understanding what these models are fundamentally doing.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://proceedings.mlr.press/v15/larochelle11a.html&quot;&gt;“NADE: The Neural Autoregressive Distribution Estimator” (2011)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Hugo Larochelle, Iain Murray&lt;br /&gt;
This paper introduced NADE, an efficient autoregressive model that tractably computes \(p(\mathbf{x}) = \prod_i p(x_i|\mathbf{x}_{&amp;lt;i})\) using neural networks for the conditionals. The key innovation was weight sharing: rather than training separate networks for each conditional, NADE uses a single neural network with shared parameters, making it efficient and preventing overfitting. The paper demonstrated that autoregressive models could compete with more complex approaches like restricted Boltzmann machines while providing exact likelihood computation and stable training. NADE influenced subsequent autoregressive models like PixelRNN/PixelCNN (for images) and WaveNet (for audio), establishing autoregressive modeling as a viable approach for complex, high-dimensional data. The work showed that explicit density modeling—directly parameterizing \(p(\mathbf{x})\)—was practical for deep learning, not just classical statistics.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.6114&quot;&gt;“Auto-Encoding Variational Bayes” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Diederik P. Kingma, Max Welling&lt;br /&gt;
This foundational paper introduced Variational Autoencoders, combining variational inference with neural networks to create a scalable framework for generative modeling with latent variables. The key contribution was the reparameterization trick: instead of sampling \(\mathbf{z} \sim q(\mathbf{z}|\mathbf{x})\) (which isn’t differentiable with respect to \(q\)’s parameters), rewrite sampling as \(\mathbf{z} = \mu + \sigma \odot \boldsymbol{\epsilon}\) where \(\boldsymbol{\epsilon} \sim \mathcal{N}(0, I)\). This deterministic function of parameters (\(\mu, \sigma\)) and external randomness (\(\boldsymbol{\epsilon}\)) enables backpropagation through sampling, making variational inference trainable via gradient descent. The paper showed VAEs could learn meaningful latent representations and generate novel samples while providing a principled probabilistic framework (unlike GANs which were concurrent but more heuristic initially). VAEs influenced countless subsequent works and established that latent variable models could scale to complex data through careful algorithm design. The ELBO objective and reparameterization trick have become fundamental tools in probabilistic deep learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1406.2661&quot;&gt;“Generative Adversarial Networks” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ian Goodfellow et al.&lt;br /&gt;
The GAN paper revolutionized generative modeling by introducing adversarial training as an alternative to maximum likelihood. By framing generation as a game between generator and discriminator, GANs enabled learning implicit density models that generate high-quality samples without requiring explicit density computation or intractable integrals. The paper’s theoretical analysis—showing that at Nash equilibrium, the generator recovers the data distribution—provided foundation while empirical results demonstrated practical viability. GANs spawned enormous subsequent research addressing training stability, mode collapse, and architecture design, becoming one of the most influential ideas in modern machine learning. The adversarial framework has been applied beyond generation to domain adaptation, robust training, and semi-supervised learning, demonstrating how a novel training paradigm can impact the field broadly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1912.02762&quot;&gt;“Normalizing Flows for Probabilistic Modeling and Inference” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: George Papamakarios, Eric Nalisnick, Danilo Jimenez Rezende, Shakir Mohamed, Balaji Lakshminarayanan&lt;br /&gt;
This comprehensive review unified normalizing flows—generative models based on invertible transformations—explaining their theoretical foundations and practical implementations. Flows learn bijective mappings \(\mathbf{x} = f(\mathbf{z})\) where \(\mathbf{z}\) has simple density (Gaussian) and \(f\) is invertible with tractable Jacobian determinant. This enables exact likelihood computation (unlike GANs) and fast sampling (unlike autoregressive models). The paper covered the landscape of flow architectures (coupling flows, autoregressive flows, continuous flows), their theoretical properties, and applications. Flows are less commonly used than VAEs or GANs for image generation but excel in tasks requiring exact density (anomaly detection, compression) or specific structure (molecular generation where validity constraints matter). Understanding flows completes the generative modeling picture, showing the tradeoff space between likelihood tractability, sampling efficiency, and architectural flexibility.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;The most fundamental mistake in generative modeling is evaluating models solely on training set likelihood or reconstruction quality. A model that memorizes training examples achieves perfect training likelihood but generates no novel examples—it fails as a generative model despite optimizing the objective perfectly. Symptoms include generated samples being near-identical to training examples and poor test set likelihood. Detection requires checking nearest neighbors in training set for each generated sample (if always very close, likely memorization) and evaluating on held-out data. Prevention includes proper regularization (weight decay, dropout), using validation set for model selection, and architectures that encourage generalization (bottlenecks in autoencoders, discriminator in GANs forcing novelty).&lt;/p&gt;

&lt;p&gt;Choosing inappropriate reconstruction losses causes perceptual mismatches between what the model optimizes and what humans care about. Pixel-wise MSE treats all pixels equally, but human vision is non-uniform—we’re more sensitive to structure and edges than to smooth regions. An MSE-optimal reconstruction might be blurry (averaging out details) while looking poor perceptually. Conversely, a reconstruction with slightly shifted edges (high MSE) might look perceptually similar. Solutions include perceptual losses (measuring distance in feature space of a pre-trained network like VGG), adversarial losses (using a discriminator to judge realism), or structured losses (measuring gradient similarity, not just pixel similarity). Understanding that loss functions embody assumptions about what’s important guides appropriate choices for specific applications.&lt;/p&gt;

&lt;p&gt;For latent variable models, choosing latent dimensionality involves subtle tradeoffs. Too small (2-3 dimensions) enables visualization but may not capture data complexity, causing poor reconstructions. Too large (approaching input dimension) enables perfect reconstruction but may not learn meaningful structure—the model might use each latent dimension for one input dimension, learning identity mapping. The right size depends on data complexity and desired compression. A useful heuristic: start with 10-20× compression, adjust based on reconstruction quality and downstream task performance. For MNIST (784 dimensions), try 32-64 latent dimensions. For ImageNet (224×224×3), try 512-2048.&lt;/p&gt;

&lt;p&gt;When generating samples, the sampling temperature often significantly affects quality-diversity tradeoffs. For autoregressive models or VAEs where we sample from learned distributions, we can scale logits by temperature before softmax:&lt;/p&gt;

\[p(x_i | \mathbf{x}_{&amp;lt;i}) = \text{softmax}(\mathbf{z}_i / T)\]

&lt;p&gt;Low temperature (\(T &amp;lt; 1\)) makes the distribution sharper—more confident, less diverse. High temperature (\(T &amp;gt; 1\)) makes it more uniform—more diverse but potentially less realistic. Temperature provides a post-training knob for trading off quality and diversity without retraining. Understanding this tradeoff helps generate samples appropriate for different applications.&lt;/p&gt;

&lt;p&gt;A powerful technique for improving sample quality is rejection sampling: generate multiple samples, score them with a discriminator or classifier, keep only high-scoring ones. This filters generated samples for quality at the cost of efficiency (must generate more samples than needed). For applications where quality matters more than generation speed (creating artwork, designing molecules), rejection sampling provides an easy win. Understanding that we can post-process generated samples—not just use whatever the model produces—expands the toolkit for practical applications.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Generative models learn to understand and reproduce data distributions, enabling creation of novel, realistic samples from learned patterns. The three main paradigms—autoregressive models providing explicit sequential density factorization, variational autoencoders using latent variables with variational inference, and generative adversarial networks training through adversarial competition—make different tradeoffs between likelihood tractability, sampling efficiency, training stability, and sample quality. Maximum likelihood provides a principled training objective connecting to information theory through KL divergence, though it requires tractable density evaluation or lower bounds. Latent variable models introduce compressed representations capturing factors of variation, enabling fast sampling and interpretable manipulation, though requiring careful inference procedures. Evaluation of generative models is challenging, requiring multiple metrics (likelihood when available, Inception Score, FID, human evaluation) and domain-specific validation rather than single numbers. Applications span data augmentation, super-resolution, style transfer, drug discovery, and creative tools, with choice of approach depending on whether we need likelihood estimation, controlled generation, sample quality, or training stability. Understanding generative modeling deeply means appreciating both the statistical foundations (probability theory, density estimation, variational inference) and the deep learning implementations (neural architectures, training algorithms, practical tricks) that make learning complex distributions tractable.&lt;/p&gt;

&lt;p&gt;Generative models demonstrate that neural networks can discover and internalize the statistical structure underlying complex data, learning representations that enable not just recognition but creation—a capability that edges closer to what we might consider genuine understanding.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=Gib_kiXgnvA&quot;&gt;The Math Behind Generative Adversarial Networks Clearly Explained!&lt;/a&gt; — Normalized Nerd, English. The minimax objective is the toy GAN’s loss.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8L11aMN5KY8&quot;&gt;A Friendly Introduction to Generative Adversarial Networks (GANs)&lt;/a&gt; — Luis Serrano Academy, English. A friendlier pass over the same two-player game before you code it.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=TpMIssRdhco&quot;&gt;What are GANs (Generative Adversarial Networks)?&lt;/a&gt; — IBM Technology, English. A picture of generator versus discriminator if the math video stalls.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11-01-02-01 Autoregressive Model Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_01_02_01_Autoregressive_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_01_02_01_Autoregressive_Code</id>
   <content type="html">&lt;p&gt;Before writing a single line of PyTorch for an autoregressive model, picture drawing a 2D point $(x_1, x_2)$ from a ring of eight Gaussian islands. If you try to predict $x_1$ and $x_2$ independently, you get a blurry square grid of 64 phantom islands. The chain rule of probability breaks that curse with surgical elegance: first sample the horizontal coordinate $x_1$ from a multimodal mixture, then ask a neural network—conditioned on the exact $x_1$ you just drew—where the vertical coordinate $x_2$ is allowed to land.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-implementing-autoregressive-density-models&quot;&gt;Key ideas: Implementing Autoregressive Density Models&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Probability Chain Rule Factorization&lt;/strong&gt;: Decomposes any joint density into exact conditionals $p_\theta(x_1, \dots, x_d) = \prod_{i=1}^d p_\theta(x_i \mid x_{&amp;lt;i})$, guaranteeing a normalized density with zero partition-function approximation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Mixture Density Parameterization&lt;/strong&gt;: Models each conditional $p_\theta(x_i \mid x_{&amp;lt;i})$ as a weighted mixture of logistics or Gaussians so a single input $x_1$ can map to multiple valid $x_2$ modes (e.g., top and bottom of a circle).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Log-Sum-Exp Numerical Stability&lt;/strong&gt;: Evaluates $\log \sum_{k=1}^K \pi_k p_k(x)$ in log-space via &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.logsumexp&lt;/code&gt; so tiny probabilities never underflow to zero during backpropagation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Teacher Forcing vs. Sequential Ancestral Sampling&lt;/strong&gt;: Explains why training evaluates all conditionals in parallel using ground-truth prefixes, whereas generation must step sequentially from $x_1$ to $x_d$.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-evaluating-a-2-component-conditional-mixture-density&quot;&gt;Worked example: Evaluating a 2-Component Conditional Mixture Density&lt;/h3&gt;

&lt;p&gt;Suppose at $x_1 = 0$, the ring of Gaussians has two vertical modes at $x_2 = +2$ and $x_2 = -2$. Our autoregressive network outputs mixture weights $\pi = (0.5, 0.5)$, means $\mu = (+2.0, -2.0)$, and equal standard deviations $\sigma = (0.5, 0.5)$. Let us compute the exact log-likelihood of a real observation $x_2 = 2.0$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Component 1 log-density at $x_2 = 2.0$&lt;/strong&gt;:
\(\log \mathcal{N}(2.0; 2.0, 0.5^2) = -\frac{1}{2}\log(2\pi) - \log(0.5) - \frac{(2.0 - 2.0)^2}{2(0.25)} = -0.9189 + 0.6931 - 0 = -0.2258.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Component 2 log-density at $x_2 = 2.0$&lt;/strong&gt;:
\(\log \mathcal{N}(2.0; -2.0, 0.5^2) = -0.9189 + 0.6931 - \frac{16}{0.5} = -0.2258 - 32.0 = -32.2258.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Combine via Log-Sum-Exp with $\log \pi_k = \log(0.5) = -0.6931$&lt;/strong&gt;:
\(a_1 = -0.6931 - 0.2258 = -0.9189, \qquad a_2 = -0.6931 - 32.2258 = -32.9189.\)
\(\log p_\theta(x_2=2.0 \mid x_1=0) = a_1 + \log\big(1 + e^{a_2 - a_1}\big) = -0.9189 + \log(1 + e^{-32}) \approx -0.9189\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Because $e^{-32} \approx 1.27 \times 10^{-14}$, the distant mode contributes virtually zero gradient, while &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;logsumexp&lt;/code&gt; keeps the computation completely free of numerical underflow.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Let’s implement different generative modeling approaches on a toy dataset to understand their mechanics:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate toy data: mixture of 8 Gaussians in a circle
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_mixture_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Generate 2D data from mixture of 8 Gaussians arranged in a circle.
    
    This toy dataset lets us visualize learned distributions and compare
    different generative modeling approaches. Each Gaussian represents a
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mode&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; - generative models should learn to generate from all modes.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n_modes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;radius&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.02&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Angles for modes evenly spaced around circle
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;thetas&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_modes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;endpoint&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Centers of Gaussians
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;centers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;radius&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;radius&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;thetas&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Sample from mixture
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Choose mode uniformly
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;mode_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_modes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Sample from chosen Gaussian
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;sample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mode_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;centers&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate training data
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generative Models on Toy 2D Dataset&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;data_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_centers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_mixture_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; samples from 8 Gaussian modes&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Data shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (10000, 2)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mode centers:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_centers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# 1. Simple Autoregressive Model
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;AutoregressiveModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Simple 2D autoregressive model: p(x) = p(x2|x1) * p(x1)
    
    Models p(x1) as mixture of logistics, p(x2|x1) as conditional mixture.
    Demonstrates explicit density modeling - we can compute p(x) exactly.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# p(x1): mixture of logistics
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Parameter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Parameter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_scales&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Parameter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# p(x2|x1): neural network outputting mixture parameters
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x2_net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# logits, means, scales for mixture
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;log_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Compute log p(x) = log p(x1) + log p(x2|x1)
        
        This is what makes it an explicit density model - we can evaluate
        probability of any point, enabling maximum likelihood training.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# log p(x1): log mixture of logistics
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;logits_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, n_components)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;means_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scales_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_scales&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Logistic log-prob for each component
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;means_1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scales_1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;log_probs_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;functional&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softplus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scales_1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Mixture log-prob using log-sum-exp
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;log_p_x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_probs_1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; \
                   &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits_1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# log p(x2|x1): conditional mixture
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;x2_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;logits_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;means_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scales_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;z_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;means_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scales_2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;log_probs_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;functional&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softplus&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scales_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;log_p_x2_given_x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_probs_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; \
                            &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;logsumexp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Total log-prob
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_p_x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_p_x2_given_x1&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Generate samples: first sample x1, then x2|x1
        
        Demonstrates sequential generation - characteristic of autoregressive.
        Exact sampling from learned distribution.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Sample x1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;probs_1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;components&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;multinomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;probs_1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;replacement&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_means&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scales&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1_scales&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Logistic samples (approximately using Gaussian)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;means&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scales&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Sample x2|x1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;x2_net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Sample component for each x1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;logits_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;probs_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;components_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;multinomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;probs_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Get parameters for chosen components
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;means_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;components_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scales_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;components_2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;means_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scales_2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train autoregressive model
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Training Autoregressive Model (Explicit Density)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;AutoregressiveModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_components&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ar_optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Shuffle data
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randperm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Mini-batch training
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute negative log-likelihood
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;log_probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Negative log-likelihood
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;ar_optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;ar_optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: NLL = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate samples
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;samples_ar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ar_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_ar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; samples&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sample mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;samples_ar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Data mean:   &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;## Video tham khảo
&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xem&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trước&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;The&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;spelled&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;intro&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;to&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;language&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;modeling&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;building&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;makemore&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;](&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;https&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;//&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;www&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;youtube&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;com&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;watch&lt;/span&gt;&lt;span class=&quot;err&quot;&gt;?&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;PaCmpygFfXo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;err&quot;&gt;—&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Andrej&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Karpathy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;English&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Next&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;character&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;prediction&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;the&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;autoregressive&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;this&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lesson&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;codes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;
&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Let&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s build GPT: from scratch, in code, spelled out.](https://www.youtube.com/watch?v=kCc8FmEb1nY) — Andrej Karpathy, English. The same factorization inside a transformer, once the bigram model is too small.
- [Sequence-to-Sequence (seq2seq) Encoder-Decoder Neural Networks, Clearly Explained!!!](https://www.youtube.com/watch?v=L8HKweZIOmg) — StatQuest with Josh Starmer, English. Sequence-to-sequence as the conditional version of that product of probabilities.
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</content>
 </entry>
 
 <entry>
   <title>11-01-01 Generative Models Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_01_01_Generative_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_01_01_Generative_Theory</id>
   <content type="html">&lt;p&gt;Every time a neural network synthesizes a photorealistic face or composes a Bach chorale, it is solving one of the hardest inverse problems in statistics: given a finite cloud of points scattered inside a million-dimensional space, infer the exact probability density that produced them. Early theorists realized that choosing &lt;em&gt;how&lt;/em&gt; to measure closeness to $p_{\text{data}}$—forward KL, reverse KL, or integral probability metrics—dramatically changes whether a model hedges its bets with blurry averages or commits sharply to a few modes.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-foundations-of-generative-theory&quot;&gt;Key ideas: Foundations of Generative Theory&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Maximum Likelihood &amp;amp; Forward KL Minimization&lt;/strong&gt;: Shows that $\arg\max_\theta \mathbb{E}&lt;em&gt;{x \sim p&lt;/em&gt;{\text{data}}}[\log p_\theta(x)]$ is equivalent to minimizing $D_{\text{KL}}(p_{\text{data}} | p_\theta)$, which strongly penalizes placing zero mass where data exists (“mode-covering” behavior).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Explicit vs. Implicit Density Taxonomy&lt;/strong&gt;: Divides generative models into tractable explicit densities (autoregressive models, normalizing flows), approximate explicit densities (VAEs, EBMs), and implicit samplers (GANs) that generate $x = G_\theta(z)$ without evaluating $p_\theta(x)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Marginalization &amp;amp; Intractable Partition Functions&lt;/strong&gt;: Explains why summing or integrating over latent variables $p_\theta(x) = \int p_\theta(x \mid z)p(z)\,dz$ or normalizing energies $Z(\theta) = \int e^{-E_\theta(x)}\,dx$ is computationally intractable in high dimensions, motivating variational bounds and score matching.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Statistical Divergences &amp;amp; Fréchet Distance&lt;/strong&gt;: Connects distribution geometry to evaluation metrics such as Bits Per Dimension (BPD) and Fréchet Inception Distance (FID), which approximates feature clouds as multivariate Gaussians.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-exact-forward-kl-bpd-and-1d-fréchet-distance&quot;&gt;Worked example: Computing Exact Forward KL, BPD, and 1D Fréchet Distance&lt;/h3&gt;

&lt;p&gt;Consider a 1D continuous data distribution $p_{\text{data}} = \mathcal{N}(\mu_1 = 2, \sigma_1^2 = 1)$ and a learned generative model $p_\theta = \mathcal{N}(\mu_2 = 0, \sigma_2^2 = 4)$ (so $\sigma_1 = 1, \sigma_2 = 2$).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Exact Forward KL Divergence $D_{\text{KL}}(p_{\text{data}} | p_\theta)$&lt;/strong&gt;:
For two 1D Gaussians,
\(D_{\text{KL}}\big(\mathcal{N}(\mu_1,\sigma_1^2) \,\|\, \mathcal{N}(\mu_2,\sigma_2^2)\big) = \ln\frac{\sigma_2}{\sigma_1} + \frac{\sigma_1^2 + (\mu_1 - \mu_2)^2}{2\sigma_2^2} - \frac{1}{2}.\)
Substituting $\mu_1=2, \sigma_1=1, \mu_2=0, \sigma_2=2$:
\(D_{\text{KL}} = \ln(2) + \frac{1 + (2 - 0)^2}{2 \cdot 4} - \frac{1}{2} = 0.6931 + \frac{5}{8} - 0.5 = 0.6931 + 0.125 = 0.8181\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convert excess coding cost to bits&lt;/strong&gt;:
\(\frac{0.8181}{\ln 2} \approx 1.180\text{ extra bits per scalar dimension}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;1D Fréchet Distance (the exact scalar form of FID)&lt;/strong&gt;:
\(\text{FD}^2 = (\mu_1 - \mu_2)^2 + (\sigma_1 - \sigma_2)^2 = (2 - 0)^2 + (1 - 2)^2 = 4 + 1 = 5.0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Notice how $D_{\text{KL}}$ penalizes variance mismatch logarithmically and mean error scaled by $1/\sigma_2^2$, whereas Fréchet Distance penalizes mean and standard-deviation shifts symmetrically in Euclidean space.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;generative-models-learning-to-create&quot;&gt;Generative Models: Learning to Create&lt;/h1&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Generative models represent a fundamental shift in how we think about machine learning. While discriminative models learn to map inputs to outputs—classifying images into categories, translating sentences between languages, or predicting stock prices from historical data—generative models learn to understand and reproduce the underlying structure of data itself. They ask a more ambitious question: given examples of some data distribution, can we learn to generate new, realistic samples from that distribution? This capability opens remarkable possibilities: creating photorealistic images of people who don’t exist, composing music in the style of Bach, designing molecules with desired properties, or augmenting limited datasets with synthetic examples.&lt;/p&gt;

&lt;p&gt;Understanding why generative modeling matters requires appreciating what’s fundamentally different about generation versus discrimination. A discriminative classifier for dog breeds learns features sufficient to distinguish breeds—the shape of ears, coat patterns, size. It doesn’t need to understand how these features combine to form a coherent dog, or what makes a dog anatomically plausible versus impossible. A generative model must learn deeper structure: how pixels organize into textures, how textures form objects, how objects compose into scenes, and crucially, what combinations are realistic versus unrealistic. This deeper understanding means generative models often learn richer representations than discriminative models, making them valuable even when generation itself isn’t the end goal.&lt;/p&gt;

&lt;p&gt;The mathematical framework for generative models is rooted in probability theory and statistical modeling. We assume data \(\mathbf{x}\) comes from some unknown distribution \(p_{\text{data}}(\mathbf{x})\). Our goal is to learn a model distribution \(p_{\text{model}}(\mathbf{x}; \theta)\) parameterized by \(\theta\) (neural network weights) that approximates \(p_{\text{data}}\). If we succeed, sampling from \(p_{\text{model}}\) should produce data indistinguishable from samples from \(p_{\text{data}}\). This probabilistic framing connects generative models to maximum likelihood estimation, variational inference, and other foundational concepts in statistics, while the use of neural networks for the model provides unprecedented flexibility in the functional forms we can represent.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Different generative modeling approaches make different tradeoffs between sample quality, training stability, theoretical guarantees, and computational requirements. Autoregressive models like PixelCNN explicitly model $$p(\mathbf{x}) = \prod_i p(x_i&lt;/td&gt;
      &lt;td&gt;x_{&amp;lt;i})\(, decomposing generation into sequential conditional distributions. They provide exact likelihoods and stable training but generate slowly (one pixel at a time). Variational autoencoders introduce latent variables\)\mathbf{z}\(and model\)p(\mathbf{x}) = \int p(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})p(\mathbf{z})d\mathbf{z}\(, optimizing a tractable lower bound on likelihood. They enable fast sampling and provide a principled probabilistic framework but often generate somewhat blurry samples. Generative adversarial networks sidestep explicit density modeling entirely, using adversarial training to learn a generator that implicitly samples from\)p_{\text{data}}$$. They often produce the sharpest, most realistic samples but suffer from training instability and mode collapse.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The practical applications of generative models extend far beyond novelty. In computer vision, they enable data augmentation (generating additional training examples), super-resolution (upscaling low-resolution images), inpainting (filling missing regions), and style transfer (applying artistic styles to photographs). In natural language processing, they power text generation, machine translation through generative seq2seq models, and data augmentation for low-resource languages. In drug discovery, they generate molecular structures with desired properties. In creative applications, they assist artists and designers. In anomaly detection, they identify outliers by measuring how well they fit the learned distribution. Understanding generative models opens this vast application space while providing insights into data structure that benefit even purely discriminative tasks.&lt;/p&gt;

&lt;p&gt;Yet generative modeling is fundamentally harder than discriminative learning in several ways. The space of possible outputs is exponentially larger than the space of labels (\(2^{784}\) possible MNIST images vs 10 labels). The learned distribution must capture complex dependencies between output dimensions (pixels aren’t independent—nearby pixels are correlated, object parts must be anatomically coherent). Evaluation is challenging—we can’t simply compute accuracy as we can for classification. And generation requires understanding not just what separates classes but what makes examples realistic, a higher bar of understanding. These challenges make generative modeling an active research area where major innovations continue to emerge regularly.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;The mathematical foundation of generative models rests on probability theory, likelihood estimation, and information theory. Let’s build these concepts systematically to understand what we’re optimizing when training generative models and why different approaches lead to different algorithms.&lt;/p&gt;

&lt;h3 id=&quot;probability-density-and-the-data-distribution&quot;&gt;Probability Density and the Data Distribution&lt;/h3&gt;

&lt;p&gt;We assume our training data \(\{\mathbf{x}^{(1)}, \ldots, \mathbf{x}^{(m)}\}\) consists of independent samples from some unknown distribution \(p_{\text{data}}(\mathbf{x})\). For images, \(\mathbf{x}\) might be \(28 \times 28 = 784\) dimensional (MNIST) or \(224 \times 224 \times 3 = 150,528\) dimensional (ImageNet). The distribution \(p_{\text{data}}\) assigns probability density to each possible \(\mathbf{x}\), with high density for realistic images (actual digits, photographs of objects) and low or zero density for unrealistic ones (random noise, anatomically impossible scenes).&lt;/p&gt;

&lt;p&gt;Our goal is to learn a parametric model \(p_{\text{model}}(\mathbf{x}; \theta)\) that approximates \(p_{\text{data}}\). The parameters \(\theta\) (neural network weights) should be set such that the model assigns high probability to training examples and, by generalization, to held-out examples from the same distribution. The standard approach is maximum likelihood estimation:&lt;/p&gt;

\[\theta^* = \arg\max_\theta \prod_{i=1}^{m} p_{\text{model}}(\mathbf{x}^{(i)}; \theta)\]

&lt;p&gt;Taking logarithms (for numerical stability and mathematical convenience):&lt;/p&gt;

\[\theta^* = \arg\max_\theta \sum_{i=1}^{m} \log p_{\text{model}}(\mathbf{x}^{(i)}; \theta) = \arg\max_\theta \frac{1}{m}\sum_{i=1}^{m} \log p_{\text{model}}(\mathbf{x}^{(i)}; \theta)\]

&lt;p&gt;The average log-likelihood \(\frac{1}{m}\sum_{i=1}^{m} \log p_{\text{model}}(\mathbf{x}^{(i)}; \theta)\) approximates the expected log-likelihood under the data distribution:&lt;/p&gt;

\[\mathbb{E}_{\mathbf{x} \sim p_{\text{data}}}[\log p_{\text{model}}(\mathbf{x}; \theta)]\]

&lt;p&gt;Maximizing this expectation is equivalent to minimizing the Kullback-Leibler divergence between data and model distributions:&lt;/p&gt;

\[KL(p_{\text{data}} \| p_{\text{model}}) = \mathbb{E}_{\mathbf{x} \sim p_{\text{data}}}[\log p_{\text{data}}(\mathbf{x}) - \log p_{\text{model}}(\mathbf{x}; \theta)]\]

&lt;p&gt;Since \(p_{\text{data}}\) is fixed, minimizing KL divergence is equivalent to maximizing expected log-likelihood. This connects maximum likelihood to information theory and provides a principled measure of how well our model approximates the true distribution.&lt;/p&gt;

&lt;h3 id=&quot;explicit-vs-implicit-density-models&quot;&gt;Explicit vs Implicit Density Models&lt;/h3&gt;

&lt;p&gt;The challenge in generative modeling is that for high-dimensional data, explicitly defining \(p_{\text{model}}(\mathbf{x}; \theta)\) that’s both flexible (can approximate complex distributions) and tractable (we can actually compute it and optimize it) is difficult.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Explicit density models&lt;/strong&gt; directly parameterize \(p_{\text{model}}(\mathbf{x}; \theta)\):&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Autoregressive models&lt;/em&gt; use the chain rule to factorize density:&lt;/p&gt;

\[p(\mathbf{x}) = p(x_1) p(x_2|x_1) p(x_3|x_1, x_2) \cdots p(x_d|x_1, \ldots, x_{d-1}) = \prod_{i=1}^{d} p(x_i|\mathbf{x}_{&amp;lt;i})\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Each conditional $$p(x_i&lt;/td&gt;
      &lt;td&gt;\mathbf{x}_{&amp;lt;i})\(is modeled with a neural network. This is exact—we can compute\)p(\mathbf{x})\(for any\)\mathbf{x}$$—but generation is slow (must generate dimensions sequentially) and the conditional independence assumptions might be restrictive.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;em&gt;Flow-based models&lt;/em&gt; use invertible transformations \(\mathbf{x} = f(\mathbf{z})\) where \(\mathbf{z} \sim p_{\mathbf{z}}\) is simple (Gaussian). The change of variables formula gives:&lt;/p&gt;

\[p_{\mathbf{x}}(\mathbf{x}) = p_{\mathbf{z}}(f^{-1}(\mathbf{x})) \left|\det \frac{\partial f^{-1}}{\partial \mathbf{x}}\right|\]

&lt;p&gt;This is exact and allows both density evaluation and fast sampling, but requires carefully designed architectures to ensure invertibility and tractable Jacobian determinants.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implicit density models&lt;/strong&gt; define a stochastic procedure for sampling without explicitly specifying \(p_{\text{model}}(\mathbf{x})\):&lt;/p&gt;

&lt;p&gt;&lt;em&gt;GANs&lt;/em&gt; learn a generator \(G: \mathcal{Z} \to \mathcal{X}\) such that if \(\mathbf{z} \sim p_{\mathbf{z}}\) then \(G(\mathbf{z})\) has distribution approximating \(p_{\text{data}}\). We never compute \(p_{\text{model}}\) but can sample efficiently. Training uses adversarial objective instead of likelihood.&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;em&gt;VAEs&lt;/em&gt; partially explicit: they model $$p(\mathbf{x}&lt;/td&gt;
      &lt;td&gt;\mathbf{z})\(explicitly but marginalize over latent\)\mathbf{z}$$ using variational approximation. They maximize a lower bound on log-likelihood (ELBO) instead of likelihood itself.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The choice between explicit and implicit, between different model families, depends on priorities: do we need exact likelihood (for anomaly detection, compression)? Do we need fast sampling (for real-time generation)? Do we prioritize sample quality over training stability? Understanding these tradeoffs guides model selection for specific applications.&lt;/p&gt;

&lt;h3 id=&quot;latent-variable-models&quot;&gt;Latent Variable Models&lt;/h3&gt;

&lt;p&gt;Many generative models introduce latent variables \(\mathbf{z}\) representing hidden factors of variation. The generative process becomes:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Sample latent code: \(\mathbf{z} \sim p(\mathbf{z})\) (typically \(\mathcal{N}(0, I)\))&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Generate data: $$\mathbf{x} \sim p(\mathbf{x}&lt;/td&gt;
          &lt;td&gt;\mathbf{z}; \theta)$$&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The marginal distribution is:&lt;/p&gt;

\[p(\mathbf{x}; \theta) = \int p(\mathbf{x}|\mathbf{z}; \theta) p(\mathbf{z}) d\mathbf{z}\]

&lt;p&gt;This framework is powerful because latent variables can represent interpretable factors (for faces: pose, lighting, expression, identity) and low-dimensional latent spaces can capture high-dimensional data manifolds. The challenge is that computing the integral for exact likelihood requires integrating over all possible latent codes, which is intractable for continuous \(\mathbf{z}\). Different generative models address this differently:&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;VAEs use variational inference, introducing an encoder $$q(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x}; \phi)\(that approximates the posterior\)p(\mathbf{z}&lt;/td&gt;
      &lt;td&gt;\mathbf{x})$$ and optimizing the Evidence Lower BOund (ELBO):&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[\log p(\mathbf{x}; \theta) \geq \mathbb{E}_{\mathbf{z} \sim q(\mathbf{z}|\mathbf{x}; \phi)}[\log p(\mathbf{x}|\mathbf{z}; \theta)] - KL(q(\mathbf{z}|\mathbf{x}; \phi) \| p(\mathbf{z}))\]

&lt;p&gt;This lower bound is tractable—we can estimate it via sampling and optimize it via backpropagation through the reparameterization trick.&lt;/p&gt;

&lt;p&gt;GANs bypass the likelihood computation entirely, directly training the generator \(G(\mathbf{z}; \theta)\) to produce samples indistinguishable from data through adversarial training. We never compute \(p(\mathbf{x})\) but implicitly learn to sample from it.&lt;/p&gt;

&lt;h3 id=&quot;evaluation-metrics&quot;&gt;Evaluation Metrics&lt;/h3&gt;

&lt;p&gt;Evaluating generative models is challenging because we care about distribution matching, not just performance on specific examples. Several metrics have been proposed:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Log-likelihood&lt;/strong&gt; (when computable): Measures how well the model assigns probability to test data. Higher is better. However, high likelihood doesn’t guarantee good samples (a model memorizing training data has perfect likelihood on training set).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Inception Score&lt;/strong&gt; (IS): Generates samples, classifies them with Inception network, computes:&lt;/p&gt;

\[IS = \exp(\mathbb{E}_{\mathbf{x} \sim p_G}[KL(p(y|\mathbf{x}) \| p(y))])\]

&lt;p&gt;Measures both quality (samples should be confidently classified) and diversity (should cover all classes). Higher is better, but IS has issues (biased toward ImageNet classes, doesn’t detect memorization).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Fréchet Inception Distance&lt;/strong&gt; (FID): Compares statistics of real and generated samples in Inception feature space, treating them as Gaussians and computing:&lt;/p&gt;

\[FID = \|\mu_r - \mu_g\|^2 + \text{Tr}(\Sigma_r + \Sigma_g - 2(\Sigma_r \Sigma_g)^{1/2})\]

&lt;p&gt;Lower FID indicates closer distributions. More reliable than IS but still imperfect (assumes Gaussian features).&lt;/p&gt;

&lt;p&gt;Understanding these metrics’ limitations is as important as using them. They correlate with perceptual quality but aren’t perfect. Visual inspection remains crucial. For specific applications, domain-specific metrics (face identity preservation for face generation, molecular validity for drug design) often matter more than generic metrics.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;To build intuition for generative models, let’s think about learning to generate handwritten digits. Imagine you’ve never seen the digit “3” but have seen thousands of other digits. Could you invent a plausible “3”? Probably not—you lack understanding of what makes a valid digit, what “3” specifically looks like, how strokes connect.&lt;/p&gt;

&lt;p&gt;Now suppose you see thousands of examples of each digit including “3”. You could learn: “3” has two rounded parts, typically connected, orientation upright, strokes smooth. With this understanding, you could generate novel “3”s—not copies of training examples but new variations following the learned pattern. This is what generative models do, but discovered automatically from data rather than described verbally.&lt;/p&gt;

&lt;p&gt;Consider the different approaches to this task:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Autoregressive approach&lt;/strong&gt;: Generate the digit pixel by pixel, left-to-right, top-to-bottom. At each position, predict the pixel value conditioned on all previous pixels. This ensures each pixel is consistent with preceding ones (if the top already looks like “3”, continue that pattern). The sequential generation provides strong guidance but is slow—784 sequential decisions for MNIST.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;VAE approach&lt;/strong&gt;: Learn a latent space where different regions correspond to different digits and variations. To generate a “3”, sample a latent code from the “3 region” (learned during training) and decode it through the decoder network. The latent space provides efficient generation (sample once, decode once) and enables interpolation (smoothly morph between digits). However, the reconstruction-based training might produce blurry samples because pixel-wise MSE doesn’t capture perceptual quality well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GAN approach&lt;/strong&gt;: Train a generator to fool a discriminator that’s trying to detect fakes. The generator learns whatever mapping from noise to images makes the discriminator unable to detect fakes. This adversarial training doesn’t require explicit pixel-wise reconstruction, allowing the generator to prioritize perceptual realism over exact pixel matching. The result is often sharper, more realistic samples, though training can be unstable and mode collapse might occur (generator only learns to create certain types of “3”s).&lt;/p&gt;

&lt;p&gt;Let’s trace through a concrete example with a simple toy dataset: 2D points forming two clusters (representing two modes of a distribution). The true distribution \(p_{\text{data}}\) is a mixture of two Gaussians:&lt;/p&gt;

\[p_{\text{data}}(\mathbf{x}) = 0.5 \mathcal{N}(\mathbf{x}; [2, 2], I) + 0.5 \mathcal{N}(\mathbf{x}; [-2, -2], I)\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Autoregressive model&lt;/strong&gt;: Models $$p(x_2&lt;/td&gt;
      &lt;td&gt;x_1)p(x_1)\(. For the first mode centered at [2, 2], it learns\)p(x_1) \approx \mathcal{N}(2, 1)\(and\)p(x_2&lt;/td&gt;
      &lt;td&gt;x_1) \approx \mathcal{N}(2, 1)\((roughly independent since we&apos;re using Gaussians, but could learn correlations). Generation: sample\)x_1 \sim p(x_1)\(, then\)x_2 \sim p(x_2&lt;/td&gt;
      &lt;td&gt;x_1)$$.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;VAE&lt;/strong&gt;: Introduces latent \(z \in \mathbb{R}\). Learns that \(z &amp;lt; 0\) maps to mode at [-2, -2] and \(z &amp;gt; 0\) maps to mode at [2, 2]. To generate, sample \(z \sim \mathcal{N}(0, 1)\), decode to \(\mathbf{x}\). The latent space smoothly varies from one mode to another.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;GAN&lt;/strong&gt;: Generator learns to map 1D noise \(z\) to 2D points such that the discriminator (which sees both real samples from the two Gaussians and generated samples) cannot distinguish real from fake. The generator might learn a nonlinear function that maps \(z \in [-3, 0]\) to the first mode and \(z \in [0, 3]\) to the second mode.&lt;/p&gt;

&lt;p&gt;Each approach successfully generates from both modes if trained properly, but they differ in how they represent the distribution, training stability, and generation procedure. Understanding these differences through simple examples builds intuition for their behavior on complex data like images.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. Fitting p_model to p_data is the theory lesson’s goal.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, English. Autoregressive factorization, latent variables, and adversarial training as three answers to that goal.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pYxNSUDSFH4&quot;&gt;In Statistics, Probability is not Likelihood.&lt;/a&gt; — StatQuest with Josh Starmer, English. Likelihood is not a probability of the parameters; the lesson’s objective depends on that distinction.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>11 Generative Models Introduction</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter11/11_00_Introduction</id>
   <content type="html">&lt;p&gt;Imagine trying to prove you truly understand Rembrandt’s brushwork. A critic can tell a genuine Rembrandt from a forgery in seconds—that is &lt;em&gt;discriminative&lt;/em&gt; modeling—but a master apprentice can sit before a blank canvas and paint a new portrait that belongs in the same gallery. Richard Feynman famously wrote on his final blackboard, &lt;em&gt;“What I cannot create, I do not understand.”&lt;/em&gt; Generative modeling is deep learning’s attempt to take Feynman literally: instead of merely drawing decision boundaries between classes, we learn the full probability landscape $p_{\text{data}}(x)$ from which real images, waveforms, molecules, and sentences are drawn.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-architecture-of-generative-modeling&quot;&gt;Key ideas: The Architecture of Generative Modeling&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 1 — Probability Measures &amp;amp; Density Estimation&lt;/strong&gt;: Studies how real-world high-dimensional data concentrates on thin, low-dimensional manifolds inside $\mathbb{R}^d$. In this chapter, it frames the core goal: approximating an unknown distribution $p_{\text{data}}(x)$ with a parameterized family $p_\theta(x)$.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 2 — Information Theory &amp;amp; Divergences&lt;/strong&gt;: Quantifies the distance between two probability distributions via Kullback–Leibler divergence $D_{\text{KL}}(p_{\text{data}} | p_\theta)$ and Jensen–Shannon divergence. It explains why maximizing log-likelihood is mathematically identical to minimizing forward KL divergence.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 3 — Latent-Variable Factorizations&lt;/strong&gt;: Introduces unobserved variables $z$ that explain high-level structure (pose, lighting, speaker identity) so complex joint densities $p_\theta(x) = \int p_\theta(x \mid z)p(z)\,dz$ become tractable to model and sample.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pillar 4 — Sample Quality vs. Likelihood Evaluation&lt;/strong&gt;: Bridges statistical fit (bits-per-dimension, negative log-likelihood) with perceptual realism (FID, Inception Score), explaining why a model with great likelihood can still produce blurry samples and vice versa.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-discriminative-vs-generative-probability-on-a-2-pixel-binary-image&quot;&gt;Worked example: Discriminative vs. Generative Probability on a 2-Pixel Binary Image&lt;/h3&gt;

&lt;p&gt;Suppose our “images” have just two binary pixels $(x_1, x_2) \in {0, 1}^2$, and an empirical dataset of 4 images contains: $(0,0), (0,0), (1,1), (1,1)$.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Empirical data distribution $p_{\text{data}}(x_1, x_2)$&lt;/strong&gt;:
\(p_{\text{data}}(0,0) = 0.5, \quad p_{\text{data}}(1,1) = 0.5, \quad p_{\text{data}}(0,1) = p_{\text{data}}(1,0) = 0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Factorized independent model $q_{\text{ind}}(x_1, x_2) = q(x_1)q(x_2)$&lt;/strong&gt;:
Each marginal has $q(x_i=1) = 0.5$, so $q_{\text{ind}}$ assigns probability $0.25$ to all four states—wasting half its probability mass on impossible patterns $(0,1)$ and $(1,0)$. Its average negative log-likelihood (NLL) in bits is:
\(\text{NLL}(q_{\text{ind}}) = -\frac{1}{2}\log_2(0.25) - \frac{1}{2}\log_2(0.25) = 2.0\text{ bits/image}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Autoregressive generative model $p_\theta(x_1, x_2) = p_\theta(x_1)\,p_\theta(x_2 \mid x_1)$&lt;/strong&gt;:
Setting $p_\theta(x_1=1)=0.5$ and $p_\theta(x_2=1 \mid x_1=1)=0.9$, $p_\theta(x_2=0 \mid x_1=0)=0.9$ yields $p_\theta(0,0) = p_\theta(1,1) = 0.5 \times 0.9 = 0.45$.
\(\text{NLL}(p_\theta) = -\log_2(0.45) \approx 1.152\text{ bits/image}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Modeling conditional dependencies cuts the coding cost from $2.0$ bits down to $1.152$ bits (approaching the true entropy $H(p_{\text{data}}) = 1.0$ bit) and ensures $90\%$ of generated samples obey the pixel correlation.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Generative models learn to create new data samples similar to training data. This chapter introduces the fundamentals of generative modeling, probability distributions, maximum likelihood estimation, and evaluation metrics. These concepts form the foundation for autoencoders, VAEs, and GANs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After the generative-model fundamentals, see &lt;strong&gt;11-99 Modern Applications and Updates&lt;/strong&gt; for the shift to diffusion and flow matching (VAE/GAN details stay in later chapters).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 13&lt;/td&gt;
          &lt;td&gt;Generative Models](https://www.youtube.com/watch?v=5WoItGTWV54) — Stanford University School of Engineering, English. Stanford’s generative-model lecture is the map of this chapter (autoregressive, latent, adversarial).&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Dmm4UG-6jxA&quot;&gt;MIT 6.S191 (2024): Deep Generative Modeling&lt;/a&gt; — Alexander Amini, English. MIT’s 2024 version of that map, closer to the models this course still treats as current.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=XepXtl9YKwc&quot;&gt;Maximum Likelihood, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Likelihood is the objective several of those models still maximize.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;For nearly a decade, AdamW sat virtually unchallenged atop deep learning optimization—yet training 100B+ parameter LLMs exposed its two biggest costs: &lt;strong&gt;16 bytes/parameter&lt;/strong&gt; of optimizer state memory and purely diagonal (coordinate-wise) preconditioning that ignores matrix structure across weight rows and columns. Between 2023 and 2025, a new wave of optimizers challenged that status quo: &lt;strong&gt;Lion&lt;/strong&gt; (discovered via symbolic program search, using sign updates and cutting optimizer memory in half), &lt;strong&gt;Sophia&lt;/strong&gt; (lightweight diagonal Hessian clipping), and &lt;strong&gt;Muon&lt;/strong&gt; (orthogonalizing 2D weight-matrix momentum updates via Newton–Schulz iterations for dramatically faster LLM pretraining).&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-beyond-adamw--the-20232025-optimizer-frontier&quot;&gt;Key ideas: Beyond AdamW — The 2023–2025 Optimizer Frontier&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Sign-Based Memory Compression (Lion, 2023)&lt;/strong&gt;: Replaces Adam’s second-moment buffer &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;v&lt;/code&gt; entirely by taking \(\operatorname{sign}(\beta_1 m_{t-1} + (1 - \beta_1) g_t)\)—halving optimizer memory (only 1 momentum buffer) while requiring ~\(3\times\text{–}10\times\) smaller learning rates and larger weight decay.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Second-Order Curvature Approximation (Sophia, 2023)&lt;/strong&gt;: Periodically estimates the diagonal Hessian \(h_t\) (via Hutchinson’s or Gauss–Newton estimators) and clips the update \(\operatorname{clip}(m_t / \max(h_t, \epsilon), -1, 1)\), accelerating along flat directions while braking aggressively on sharp curvature.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matrix-Aware Orthogonalization (Muon, 2024)&lt;/strong&gt;: Recognizes that linear-layer weights \(W \in \mathbb{R}^{m \times n}\) are &lt;strong&gt;matrices&lt;/strong&gt;, not unstructured vectors. Applying fast &lt;strong&gt;Newton–Schulz&lt;/strong&gt; iterations to the momentum matrix \(M_t\) approximates its polar factor \(U V^\top\) (setting all singular values to \(1\)), updating every spectral direction at equal speed!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hybrid Production Recipes&lt;/strong&gt;: Frontier training runs increasingly pair Muon for hidden 2D weight matrices with AdamW for 1D biases, LayerNorm gains, and token embeddings—combining spectral speed with scalar stability.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-orthogonalizing-a-momentum-matrix-muon-rescues-small-singular-directions&quot;&gt;Worked example: Why Orthogonalizing a Momentum Matrix (Muon) Rescues Small Singular Directions&lt;/h3&gt;

&lt;p&gt;Suppose a \(2 \times 2\) weight layer has momentum matrix \(M = \begin{bmatrix} 10 &amp;amp; 0 \\ 0 &amp;amp; 0.1 \end{bmatrix}\) (singular values \(\sigma_1 = 10, \sigma_2 = 0.1\) — a \(100:1\) anisotropy!).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standard Momentum update&lt;/strong&gt; (\(\Delta W = -\eta M\) with \(\eta = 0.01\)):
\(\Delta W_{\text{mom}} = \begin{bmatrix} -0.10 &amp;amp; 0 \\ 0 &amp;amp; -0.001 \end{bmatrix}.\)
Direction 2 moves \(100\times\) slower than Direction 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Muon polar orthogonalization&lt;/strong&gt; (SVD \(M = U \Sigma V^\top \implies \operatorname{orth}(M) = U V^\top\)):
    &lt;ul&gt;
      &lt;li&gt;Here \(U = I, V = I, \Sigma = \operatorname{diag}(10, 0.1)\), so \(U V^\top = \begin{bmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{bmatrix}\).&lt;/li&gt;
      &lt;li&gt;Muon update (\(\eta = 0.01\)):
\(\Delta W_{\text{Muon}} = -0.01 \begin{bmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{bmatrix} = \begin{bmatrix} -0.01 &amp;amp; 0 \\ 0 &amp;amp; -0.01 \end{bmatrix}.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;One-step Newton–Schulz check&lt;/strong&gt;: Starting from normalized \(X_0 = M / \|M\|_F \approx \operatorname{diag}(0.99995, 0.0099995)\), the iteration \(X_{k+1} = \frac{3}{2} X_k - \frac{1}{2} X_k^3\) rapidly inflates tiny singular values toward \(1\) using only fast GPU matrix multiplications—no expensive SVD required!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-adamw-and-the-20232025-optimizer-wave-lion-sophia-muon&quot;&gt;Optional: AdamW and the 2023–2025 optimizer wave (Lion, Sophia, Muon)&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace momentum / RMSprop / Adam theory. The core notes already mention AdamW; this lesson covers what became standard &lt;em&gt;after&lt;/em&gt; AdamW, and when to stay with AdamW.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;AdamW is still the default in Hugging Face and most LLM trainers:&lt;/p&gt;

\[m_t = \beta_1 m_{t-1} + (1-\beta_1) g_t, \quad
v_t = \beta_2 v_{t-1} + (1-\beta_2) g_t^2,\]

\[\theta \leftarrow \theta - \eta \frac{\hat{m}_t}{\sqrt{\hat{v}_t}+\varepsilon} - \eta\lambda \theta.\]

&lt;p&gt;The last term is &lt;strong&gt;decoupled&lt;/strong&gt; weight decay (not L2 inside the adaptive step). Everything below is an alternative or a specialized upgrade.&lt;/p&gt;

&lt;h2 id=&quot;1-lion-2023&quot;&gt;1. Lion (2023)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2302.06675&quot;&gt;Chen et al., 2023&lt;/a&gt; (symbolic search at Google) keep only the &lt;strong&gt;sign&lt;/strong&gt; of an interpolated momentum:&lt;/p&gt;

\[\theta \leftarrow \theta - \eta\,\mathrm{sign}(\beta_1 m + (1-\beta_1)g) - \eta\lambda\theta.\]

&lt;p&gt;Memory is lower than Adam (no second moment). Used in some vision and distillation jobs; less universal than AdamW for LLMs.&lt;/p&gt;

&lt;h2 id=&quot;2-sophia-2023&quot;&gt;2. Sophia (2023)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.14342&quot;&gt;Liu et al., 2023&lt;/a&gt; estimate a diagonal Hessian (via Hutchinson or a clipped Gauss–Newton) and precondition:&lt;/p&gt;

\[\theta \leftarrow \theta - \eta \cdot \mathrm{clip}\!\left(\frac{\hat{m}_t}{\max\{\gamma \hat{h}_t, \varepsilon\}}\right).\]

&lt;p&gt;Reported to cut GPT-style steps versus AdamW at similar quality. Still a research optimizer in most open trainers.&lt;/p&gt;

&lt;h2 id=&quot;3-muon-2024&quot;&gt;3. Muon (2024)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://kellerjordan.github.io/posts/muon/&quot;&gt;Jordan et al., 2024&lt;/a&gt; apply SGD-momentum to &lt;strong&gt;hidden matrices&lt;/strong&gt;, then orthogonalize the update with a few Newton–Schulz iterations (a cheap polar-factor approximation). Embeddings and LM heads typically stay on AdamW. &lt;a href=&quot;https://arxiv.org/abs/2502.16982&quot;&gt;Moonshot / Kimi, 2025&lt;/a&gt; report scaled LLM training with Muon. This is the most-discussed &lt;em&gt;new&lt;/em&gt; matrix optimizer of 2024–2025.&lt;/p&gt;

&lt;h2 id=&quot;4-concrete-applications-and-software&quot;&gt;4. Concrete applications and software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Stay on AdamW&lt;/strong&gt; for a first LLM or ConvNeXt run (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.optim.AdamW&lt;/code&gt;, fused CUDA kernels in Apex / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lion&lt;/strong&gt;: &lt;a href=&quot;https://github.com/lucidrains/lion-pytorch&quot;&gt;lucidrains/lion-pytorch&lt;/a&gt;; some &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timm&lt;/code&gt; recipes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sophia&lt;/strong&gt;: &lt;a href=&quot;https://github.com/Liuhongwei95/Sophia&quot;&gt;Liuhongwei95/Sophia&lt;/a&gt; (paper code).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Muon&lt;/strong&gt;: &lt;a href=&quot;https://github.com/KellerJordan/Muon&quot;&gt;KellerJordan/Muon&lt;/a&gt; and the &lt;a href=&quot;https://github.com/KellerJordan/modded-nanogpt&quot;&gt;modded-nanogpt&lt;/a&gt; speedrun.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Schedule-free AdamW&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2405.15682&quot;&gt;Defazio et al., 2024&lt;/a&gt;) — removes explicit warmup/cosine for some workloads.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-citations-20222026&quot;&gt;5. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2302.06675&quot;&gt;Symbolic Discovery of Optimization Algorithms — Lion (Chen et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.14342&quot;&gt;Sophia: A Scalable Stochastic Second-order Optimizer (Liu et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://kellerjordan.github.io/posts/muon/&quot;&gt;Muon (Jordan et al., 2024)&lt;/a&gt; — hidden-layer orthogonalized momentum.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2502.16982&quot;&gt;Muon is Scalable for LLM Training (Liu et al., 2025)&lt;/a&gt; — Kimi/Moonshot scale report.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2405.15682&quot;&gt;The Road Less Scheduled (Defazio et al., 2024)&lt;/a&gt; — schedule-free AdamW.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;6-how-this-complements-the-core-notes&quot;&gt;6. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Learn Adam and the Rosenbrock comparison first. This lesson only adds &lt;strong&gt;post-AdamW&lt;/strong&gt; methods used in 2023–2026 papers and speedruns — it does not replace the optimizer implementations in this chapter.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, English. Lion, Sophia, and Muon are later members of the momentum/Adam family this video lines up.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, English. Adam is the update those 2023–2024 methods are measured against.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 7&lt;/td&gt;
          &lt;td&gt;Training Neural Networks II](https://www.youtube.com/watch?v=_JB0AO7QxSA) — Stanford University School of Engineering, English. The training-lecture context for why a new optimizer is a small change next to data and schedule.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-98 Interviews Practice (optimizers)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Optimization questions are a favorite stress test in ML interviews because they expose whether you understand &lt;em&gt;why&lt;/em&gt; training recipes work rather than blindly copying &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Adam(lr=1e-3)&lt;/code&gt; from a tutorial. Can you explain on a whiteboard why Adam’s bias correction matters specifically at \(t = 1\), why AdamW fixes a genuine bug in L2-regularized Adam, or why warmup stabilizes early Transformer updates? These five prompts drill the exact intuition interviewers look for.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-core-interview-competency-pillars-for-optimizers&quot;&gt;Key ideas: Core Interview Competency Pillars for Optimizers&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Momentum &amp;amp; Ravine Geometry&lt;/strong&gt;: Explaining how exponential velocity averaging cancels alternating orthogonal gradients across steep canyon walls while compounding parallel descent components.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adam Bias Correction &amp;amp; Stability&lt;/strong&gt;: Proving from \(m_t = (1-\beta_1)\sum \beta_1^{t-i} g_i\) why dividing by \((1 - \beta^t)\) prevents zero-bias distortion during early steps.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adam vs. AdamW Decoupling&lt;/strong&gt;: Showing why L2 weight decay inside Adam gets divided by \(\sqrt{\hat{v}_t}\) and loses uniformity across parameters.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Warmup &amp;amp; Generalization Trade-offs&lt;/strong&gt;: Articulating why warmup prevents early large-variance adaptive jumps and when SGD + Momentum still competes with AdamW.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-quick-whiteboard-proof-of-adams-bias-correction-factor&quot;&gt;Worked example: Quick Whiteboard Proof of Adam’s Bias Correction Factor&lt;/h3&gt;

&lt;p&gt;Suppose the true gradient is a constant \(g_1 = g_2 = \dots = g_t = g\), and we initialize \(m_0 = 0\) with \(m_t = \beta m_{t-1} + (1 - \beta) g_t\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Expand the geometric series&lt;/strong&gt;:
\(m_t = (1 - \beta) g \sum_{k=0}^{t-1} \beta^k.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply the finite geometric sum formula&lt;/strong&gt; (\(\sum_{k=0}^{t-1} \beta^k = \frac{1 - \beta^t}{1 - \beta}\)):
\(m_t = (1 - \beta) g \cdot \frac{1 - \beta^t}{1 - \beta} = (1 - \beta^t)\, g.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Numerical check at \(t = 1\) with \(\beta = 0.999\)&lt;/strong&gt;:
\(m_1 = (1 - 0.999)\, g = 0.001\, g \quad (\text{off by a factor of } 1{,}000\times!).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact fix&lt;/strong&gt;: Dividing by \((1 - \beta^t)\) recovers \(\hat{m}_t = \frac{m_t}{1 - \beta^t} = g\) identically for every \(t \ge 1\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-interview-practice--optimizers&quot;&gt;Optional: interview practice — optimizers&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace momentum, RMSprop, or Adam theory. After those notes, use this drill, then open &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for solved items on adaptive methods, hyperparameters, and training dynamics.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Book themes for this chapter (study in the PDF, not here):&lt;/strong&gt; optimization algorithms (including Adam-family updates), hyperparameter choices, and the training subsection of the expanded deep-learning topic area.&lt;/p&gt;

&lt;p&gt;Hub: &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;practice-prompts-original&quot;&gt;Practice prompts (original)&lt;/h2&gt;

&lt;h3 id=&quot;q1-momentum-on-a-ravine&quot;&gt;Q1. Momentum on a ravine&lt;/h3&gt;

&lt;p&gt;Vanilla SGD oscillates across a narrow valley and crawls along the long axis. In one sentence each: what does a velocity buffer \(\mathbf{v}\leftarrow \beta\mathbf{v}+\nabla J\) change about those two directions?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; High-frequency flips average out; a consistent gradient accumulates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Across the ravine the gradient sign flips, so the momentum average stays small and the oscillation damps. Along the valley the gradient keeps the same sign, so \(\mathbf{v}\) builds and the crawl speeds up. That is the interview picture; you do not need a specific \(\beta\) derivation unless asked.&lt;/p&gt;

&lt;h3 id=&quot;q2-why-adams-bias-correction-exists&quot;&gt;Q2. Why Adam’s bias correction exists&lt;/h3&gt;

&lt;p&gt;Adam’s first moment is \(\mathbf{m}_t=\beta_1\mathbf{m}_{t-1}+(1-\beta_1)\mathbf{g}_t\) with \(\mathbf{m}_0=\mathbf{0}\). Why is \(\mathbf{m}_t\) too small at \(t=1\), and what does dividing by \(1-\beta_1^t\) do?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Unroll one step: \(\mathbf{m}_1=(1-\beta_1)\mathbf{g}_1\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; At \(t=1\) you only have a \((1-\beta_1)\) fraction of the first gradient (typically \(0.1\) if \(\beta_1=0.9\)). The factor \(1-\beta_1^t\) is the sum of the geometric weights; dividing undoes the cold-start shrink. The same story applies to the second moment with \(\beta_2\). After a few hundred steps \(\beta^t\approx 0\) and the correction is optional in practice — but interviewers still want the \(t=1\) calculation.&lt;/p&gt;

&lt;h3 id=&quot;q3-adam-vs-adamw&quot;&gt;Q3. Adam vs AdamW&lt;/h3&gt;

&lt;p&gt;You want an effective L2 penalty \(\frac{\lambda}{2}\|\mathbf{w}\|_2^2\). Why is “add \(\lambda\mathbf{w}\) to the gradient, then let Adam rescale” not the same as decaying \(\mathbf{w}\) by \(\lambda\eta\) outside the adaptive denominator?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Adam divides the gradient (and anything you add to it) by \(\sqrt{\hat{\mathbf{v}}}+\epsilon\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Coupled weight decay is distorted: coordinates with large second moments get &lt;em&gt;less&lt;/em&gt; decay. AdamW applies decay to the weights directly, so every coordinate shrinks by a comparable \(\lambda\eta\) (up to the learning-rate schedule). That is the default in modern CNN / Transformer recipes and the distinction Chapter 10 already names; this prompt only checks that you can say &lt;em&gt;why&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;q4-when-sgdmomentum-can-beat-adam&quot;&gt;Q4. When SGD+momentum can beat Adam&lt;/h3&gt;

&lt;p&gt;A ConvNet on a large image set generalizes worse with well-tuned Adam than with SGD+momentum at a longer horizon. Give one optimization-centric and one implicit-regularization-centric hypothesis — not “Adam is buggy.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Adaptive methods rewrite the preconditioner every step; SGD keeps a global scale.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Optimization: Adam can reach a sharp region of \(J\) faster and then sit there because the per-coordinate scale stays large on small-gradient coordinates. Implicit bias: the SGD noise + shared learning rate has a different stationary distribution over minima than Adam’s preconditioned noise. Neither hypothesis is a theorem you must prove on a whiteboard; you &lt;em&gt;should&lt;/em&gt; mention that you would verify with a longer SGD run and a proper val set, not with one seed.&lt;/p&gt;

&lt;h3 id=&quot;q5-a-one-line-warmup-rationale&quot;&gt;Q5. A one-line warmup rationale&lt;/h3&gt;

&lt;p&gt;You start a Transformer with AdamW at the peak learning rate and the loss spikes to NaN. Why might linearly warming \(\eta\) for a few thousand steps fix it even if the &lt;em&gt;final&lt;/em&gt; \(\eta\) is unchanged?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; At init, activations and attention logits are poorly scaled; a large step is taken with a meaningless \(\mathbf{m},\mathbf{v}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Early gradients are huge or incoherent; Adam’s second-moment estimate is also untrustworthy (Q2). A small \(\eta\) lets the moments and the residual stream settle before you take ImageNet- or LLM-sized steps. Warmup is not magic — if the peak \(\eta\) is simply too large, you will still diverge after warmup ends.&lt;/p&gt;

&lt;h2 id=&quot;attribution&quot;&gt;Attribution&lt;/h2&gt;

&lt;p&gt;Kashani, S., and Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Download the PDF from arXiv for the full solved Q&amp;amp;A. This page is original course practice, not a reprint.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, English. Before optimizer interview prompts.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, English. Be able to write Adam’s update from this derivation.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, English. And the plain step it reduces to if the moments are removed.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-01 Advanced Optimization Algorithms</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_01_Advanced_Optimizers/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_01_Advanced_Optimizers</id>
   <content type="html">&lt;p&gt;Gradient descent in 100 million dimensions is nothing like rolling a marble down a smooth bowl—the landscape is packed with saddle points, flat plateaus, and razor-thin ravines. This module hub connects the mathematical theory of advanced first-order optimizers (Momentum, NAG, AdaGrad, RMSprop, Adam) with full code implementations, trajectory comparisons, and practical hyperparameter playbooks.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-navigating-advanced-optimization&quot;&gt;Key ideas: Navigating Advanced Optimization&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Core Optimizer Theory&lt;/strong&gt;: Understanding first-moment velocity, Nesterov look-ahead, second-moment adaptive preconditioning, and Adam’s bias correction.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Code &amp;amp; Trajectory Analysis&lt;/strong&gt;: Implementing every optimizer from scratch and comparing convergence behavior on ill-conditioned surfaces and neural benchmarks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Default Selection Heuristics&lt;/strong&gt;: Matching optimizer + weight decay + LR schedule to vision, sequence, and Transformer workloads.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-effective-momentum-horizon-how-many-past-steps-does-beta--09-remember&quot;&gt;Worked example: Effective Momentum Horizon (How Many Past Steps Does \(\beta = 0.9\) Remember?)&lt;/h3&gt;

&lt;p&gt;In an exponential moving average \(m_t = \beta m_{t-1} + (1 - \beta) g_t\), the weight placed on a gradient from \(k\) steps ago decays as \(\beta^k\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Effective averaging window&lt;/strong&gt;:
\(N_{\text{eff}} \approx \frac{1}{1 - \beta}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Concrete values&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(\beta_1 = 0.9 \implies \frac{1}{1 - 0.9} = 10 \text{ steps}\) (Adam’s first moment tracks roughly the last 10 mini-batches).&lt;/li&gt;
      &lt;li&gt;\(\beta_2 = 0.999 \implies \frac{1}{1 - 0.999} = 1{,}000 \text{ steps}\) (Adam’s second moment averages gradient variance over ~1,000 steps!).&lt;/li&gt;
      &lt;li&gt;In LLM training with huge batches, practitioners often lower \(\beta_2 = 0.95\) (\(N_{\text{eff}} = 20\) steps) so the optimizer adapts faster to sudden gradient spikes!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers modern optimizers beyond vanilla gradient descent:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Optimizer Theory&lt;/strong&gt; — Momentum, NAG, AdaGrad, RMSprop, Adam, AdamW, and intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Optimizer Implementation&lt;/strong&gt; — code comparisons, papers, pitfalls, and takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, English. The family the theory and code lessons split.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, English. Adam’s two moment estimates, the update you will code.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 7&lt;/td&gt;
          &lt;td&gt;Training Neural Networks II](https://www.youtube.com/watch?v=_JB0AO7QxSA) — Stanford University School of Engineering, English. Stanford’s optimization lecture for the same family in a full training context.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-01-02 Optimizer Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_01_02_Optimizer_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_01_02_Optimizer_Implementation</id>
   <content type="html">&lt;p&gt;Knowing optimizer equations is one thing; watching their trajectories race side-by-side across an ill-conditioned 2D valley and a noisy neural network loss surface is what builds lasting engineering judgment. This implementation hub pairs the from-scratch NumPy/PyTorch optimizer classes with empirical benchmarks, Adam vs. AdamW comparisons, learning-rate schedules, and classic convergence pitfalls.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-practical-optimizer-engineering&quot;&gt;Key ideas: Practical Optimizer Engineering&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;From-Scratch Verification&lt;/strong&gt;: Coding Momentum, NAG, AdaGrad, RMSprop, and Adam in NumPy and confirming identical trajectories against &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.optim&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Comparative Benchmarking&lt;/strong&gt;: Testing convergence speed, oscillation damping, and generalization across both convex/non-convex 2D surfaces and neural classification tasks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Production Recipes&lt;/strong&gt;: Combining &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AdamW&lt;/code&gt; (for Transformers/NLP) or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;SGD + Momentum&lt;/code&gt; (for classic CNNs) with warmup, cosine decay, and gradient clipping.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-cosine-annealing-learning-rate-at-quarter-milestones&quot;&gt;Worked example: Computing Cosine Annealing Learning Rate at Quarter Milestones&lt;/h3&gt;

&lt;p&gt;For &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CosineAnnealingLR&lt;/code&gt; decaying from \(\eta_{\max} = 10^{-3}\) to \(\eta_{\min} = 0\) over \(T_{\max} = 100\) epochs:
\(\eta(t) = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min})\left(1 + \cos\!\left(\frac{\pi t}{T_{\max}}\right)\right).\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Epoch \(t = 0\)&lt;/strong&gt;: \(\cos(0) = 1 \implies \eta(0) = 1.0 \times 10^{-3}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Epoch \(t = 25\)&lt;/strong&gt;: \(\cos(\pi/4) \approx 0.7071 \implies \eta(25) = 0.5(1.7071) \times 10^{-3} \approx 8.54 \times 10^{-4}\) (stays high early!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Epoch \(t = 50\)&lt;/strong&gt;: \(\cos(\pi/2) = 0 \implies \eta(50) = 5.0 \times 10^{-4}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Epoch \(t = 75\)&lt;/strong&gt;: \(\cos(3\pi/4) \approx -0.7071 \implies \eta(75) = 0.5(0.2929) \times 10^{-3} \approx 1.46 \times 10^{-4}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Epoch \(t = 100\)&lt;/strong&gt;: \(\cos(\pi) = -1 \implies \eta(100) = 0\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Optimizer implementation:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Core Implementation&lt;/strong&gt; — Momentum through AdamW from scratch&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Comparisons, Papers, and Pitfalls&lt;/strong&gt; — 2D trajectories, classification bake-off, takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, English. The Adam update the code lesson implements.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, English. The neighboring updates (RMSProp, AdaGrad) so a bug in one buffer is easier to see.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, English. Calling the optimizer from a training step, after the update itself is clear.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-01-02-02 Optimizer Comparisons, Papers, and Pitfalls</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_01_02_02_Optimizer_Comparisons_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_01_02_02_Optimizer_Comparisons_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Benchmarking SGD, Momentum, RMSprop, and Adam on both a classic 2D ill-conditioned valley (like the Rosenbrock banana function) and a non-linear neural classification problem exposes a nuance that surprises many newcomers: &lt;strong&gt;faster training convergence does not always equal better test generalization&lt;/strong&gt;. Adam rockets down ravines in the first 50 epochs with almost zero tuning, yet on vision benchmarks like ImageNet ResNets, carefully tuned SGD + Momentum + cosine decay frequently edges out vanilla Adam on test accuracy—until &lt;strong&gt;AdamW&lt;/strong&gt; (decoupled weight decay) closes the gap.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-empirical-trade-offs--optimizer-pitfalls&quot;&gt;Key ideas: Empirical Trade-offs &amp;amp; Optimizer Pitfalls&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Adam vs. AdamW (Coupled L2 vs. Decoupled Weight Decay)&lt;/strong&gt;: Adding \(\lambda \theta\) to the gradient &lt;em&gt;before&lt;/em&gt; Adam’s adaptive normalization divides weight decay by \(\sqrt{\hat{v}_t}\), weakening regularization on weights with large historical gradients! Loshchilov &amp;amp; Hutter (2019) fixed this by applying \(\theta \leftarrow (1 - \eta \lambda)\theta\) directly outside the adaptive step.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Learning Rate Scale Incompatibility Across Optimizers&lt;/strong&gt;: A learning rate that is optimal for SGD (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-1&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-2&lt;/code&gt;) will catastrophically blow up Adam (whose sweet spot is typically &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-3&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3e-4&lt;/code&gt;), because Adam normalizes gradient magnitudes to \(O(1)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why SGD + Momentum Can Still Generalize Better on CNNs&lt;/strong&gt;: SGD’s isotropic mini-batch gradient noise acts as an implicit flat-minima regularizer, whereas adaptive coordinate scaling can slip into narrower, sharper valleys if weight decay is misconfigured.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Learning Rate Schedules (Warmup + Cosine Decay)&lt;/strong&gt;: Pairing any optimizer with linear warmup and cosine annealing (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CosineAnnealingLR&lt;/code&gt;) consistently outperforms constant learning rates by taking bold exploratory steps early and settling smoothly into the minimum late.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-numerical-proof-that-l2-inside-adam-differs-from-adamw&quot;&gt;Worked example: Numerical Proof That L2 Inside Adam Differs From AdamW&lt;/h3&gt;

&lt;p&gt;Consider two parameters with the same value \(\theta_A = \theta_B = 1.0\), weight decay \(\lambda = 0.1\), and \(\eta = 0.01\), where Feature A has large typical gradient scale \(\sqrt{\hat{v}_A} = 10.0\) and Feature B has small typical gradient scale \(\sqrt{\hat{v}_B} = 0.1\) (assume current data gradient \(g_{\text{data}} = 0\) to isolate weight decay):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Coupled L2 inside vanilla Adam&lt;/strong&gt; (adds \(\lambda \theta = 0.1\) to gradient, then divides by \(\sqrt{\hat{v}}\)):
    &lt;ul&gt;
      &lt;li&gt;Decay on \(\theta_A\): \(\Delta \theta_A = -0.01 \cdot \frac{0.1}{10.0} = -0.0001\) (\(0.01\%\) shrinkage!).&lt;/li&gt;
      &lt;li&gt;Decay on \(\theta_B\): \(\Delta \theta_B = -0.01 \cdot \frac{0.1}{0.1} = -0.0100\) (\(1.00\%\) shrinkage — &lt;strong&gt;100× stronger&lt;/strong&gt;!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decoupled Weight Decay (AdamW)&lt;/strong&gt; (applies \(-\eta \lambda \theta\) directly):
    &lt;ul&gt;
      &lt;li&gt;Decay on \(\theta_A\): \(\Delta \theta_A = -0.01 \times 0.1 \times 1.0 = -0.0010\) (\(0.1\%\)).&lt;/li&gt;
      &lt;li&gt;Decay on \(\theta_B\): \(\Delta \theta_B = -0.01 \times 0.1 \times 1.0 = -0.0010\) (\(0.1\%\) — &lt;strong&gt;strictly uniform&lt;/strong&gt;!).
That \(100\times\) distortion is why AdamW replaced Adam+L2 across Transformers and modern vision models.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Demonstrate optimizer comparison on 2D optimization problem
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Comparing Optimizers on Rosenbrock Function&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Rosenbrock: f(x,y) = (1-x)² + 100(y-x²)²&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Minimum at (1, 1), but narrow curved valley makes optimization hard&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Classic optimization test function with narrow curved valley&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient of Rosenbrock function&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;400&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Initialize parameters (start far from minimum)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create optimizers
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;opt_sgd&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]})()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;opt_momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SGDMomentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;opt_rmsprop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;opt_adam&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Track trajectories
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trajectories&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Momentum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()],&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Optimize for 500 steps
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Vanilla SGD
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;opt_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trajectories&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Momentum
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;opt_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trajectories&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Momentum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# RMSprop
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;opt_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trajectories&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Adam
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rosenbrock_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;opt_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;trajectories&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compare final positions
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Final positions after 500 steps:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  SGD:      (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_sgd&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Momentum: (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  RMSprop:  (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_rmsprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Adam:     (&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  True min: (1.0000, 1.0000)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observations:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Momentum accelerates along the valley&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- RMSprop adapts to different curvatures&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Adam combines benefits of both&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Vanilla SGD is slowest (gets stuck in oscillations)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now demonstrate on actual neural network training:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.utils.data&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;TensorDataset&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create simple classification task
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Neural Network with Different Optimizers&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate synthetic data: XOR-like problem
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# XOR
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;FloatTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TensorDataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simple network
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train with different optimizers
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizers_to_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;SGD+Momentum&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; 
                                                   &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;AdamW&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;lambda&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AdamW&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                            &lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizer_fn&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizers_to_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training with &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Create fresh model
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;optimizer_fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BCELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Train
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_batch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Forward
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Backward
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataloader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;25&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Test accuracy
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;final_loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compare results
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Optimizer Comparison Results&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Optimizer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Final Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;45&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;res&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;final_loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;12.4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;res&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;10.2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Key observations:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Momentum accelerates convergence over vanilla SGD&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Adaptive methods (RMSprop, Adam) converge faster&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- AdamW often best generalization with weight decay&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Choice matters: 2-5x speed difference common&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Demonstrate learning rate scheduling:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CosineAnnealingSchedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Cosine annealing learning rate schedule.
    
    Gradually decreases learning rate following cosine curve.
    Often combined with warm restarts for improved performance.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        lr_max: maximum learning rate
        lr_min: minimum learning rate
        T_max: period of cosine cycle (iterations)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_max&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;get_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Get learning rate at iteration t&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; \
               &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;CosineAnnealingSchedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr_max&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_min&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;T_max&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Learning Rate Scheduling&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;iterations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;300&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;lrs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Learning rate evolution (first 300 iterations):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Start: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  After 50 iters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  After 100 iters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (end of cycle, restarts)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  After 150 iters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lrs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;150&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cosine annealing smoothly reduces LR, enabling fine-tuning near minima&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;The relationship between optimization algorithms and the geometry of loss surfaces illuminates why different optimizers excel in different scenarios. Deep neural network loss surfaces are highly non-convex, featuring local minima, saddle points, and plateaus. Saddle points—where gradients are zero but we’re not at a minimum—are particularly common in high dimensions. Momentum helps escape saddle points by building velocity that carries through regions with zero gradient. Adaptive learning rates help when different directions have vastly different curvatures—common in neural networks where some parameters (like biases) receive consistently similar gradients while others (like weights) have highly variable gradient magnitudes.&lt;/p&gt;

&lt;p&gt;The connection to second-order optimization methods provides theoretical context. Newton’s method uses second derivatives (the Hessian matrix) to account for curvature, enabling faster convergence. However, computing and inverting the Hessian for networks with millions of parameters is computationally prohibitive—\(O(n^2)\) memory and \(O(n^3)\) computation. Adaptive learning rate methods like Adam approximate second-order information through gradient statistics (the second moment \(\mathbf{v}_t\) is related to diagonal Hessian entries) without the prohibitive cost. This approximate curvature information, while cruder than full Newton methods, provides enough benefit to significantly accelerate training while remaining computationally practical.&lt;/p&gt;

&lt;p&gt;Optimizers interact intimately with batch normalization and other normalization techniques. Batch normalization changes the loss surface geometry, making it smoother and reducing sensitivity to learning rates. This interaction can be subtle: some optimizers that work well without normalization may be less advantageous with it. Adam with batch normalization sometimes converges to worse minima than SGD with momentum, a phenomenon called “generalization gap.” Understanding these interactions guides optimizer choice based on architecture—Transformers (which use layer normalization) often work best with AdamW, while ResNets (with batch normalization) might prefer SGD with momentum for final performance.&lt;/p&gt;

&lt;p&gt;The evolution from hand-tuned learning rates to adaptive methods represents a broader trend in deep learning: automating hyperparameter choices. Early neural network training required extensive tuning of learning rates, schedules, and momentum coefficients. Modern adaptive optimizers reduce this burden—Adam’s default hyperparameters work reasonably across diverse tasks. This democratization of deep learning made the field more accessible, though it also created a risk: using black-box optimizers without understanding their assumptions can lead to poor performance in edge cases. The best practitioners understand both the algorithms and when their assumptions break down.&lt;/p&gt;

&lt;p&gt;Learning rate schedules connect to the exploration-exploitation tradeoff in optimization. Early in training, we want to explore broadly, taking larger steps to find good regions of parameter space. Later, we want to exploit, taking smaller steps to fine-tune parameters near a minimum. Schedules like cosine annealing or step decay formalize this, reducing learning rate as training progresses. Warm-up schedules do the opposite initially—start with very small learning rate and gradually increase—which helps when using very large batches or when parameters are randomly initialized and initial gradients might be misleading. The Transformer paper’s warm-up schedule \(\eta_t = d_{\text{model}}^{-0.5} \min(t^{-0.5}, t \cdot \text{warmup}^{-1.5})\) has become standard for training large models.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://proceedings.mlr.press/v28/sutskever13.html&quot;&gt;“On the importance of initialization and momentum in deep learning” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ilya Sutskever, James Martens, George Dahl, Geoffrey Hinton&lt;br /&gt;
This paper rigorously analyzed momentum’s benefits for deep learning, showing it’s not just a minor improvement but essential for training deep networks effectively. The authors demonstrated that momentum combined with proper initialization (they used specific schemes for different layer types) enables training much deeper networks than vanilla SGD. They showed momentum helps escape saddle points and reduces the impact of noisy gradients from mini-batch sampling. Importantly, they provided theoretical analysis of momentum’s dynamics, connecting it to classical optimization theory while demonstrating its specific advantages for non-convex neural network loss surfaces. The paper established Nesterov momentum as particularly effective, slightly but consistently outperforming standard momentum. This work influenced the field’s understanding that optimization algorithms must be tailored to deep learning’s unique challenges—high dimensionality, non-convexity, noisy gradients—rather than simply applying classical optimization methods.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1412.6980&quot;&gt;“Adam: A Method for Stochastic Optimization” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Diederik P. Kingma, Jimmy Ba&lt;br /&gt;
This paper introduced Adam and demonstrated its effectiveness across diverse tasks including image classification, language modeling, and variational inference. The key contribution was combining adaptive learning rates (like RMSprop) with momentum, while including bias correction to ensure good behavior from the first update. Kingma and Ba showed that Adam requires minimal hyperparameter tuning—default values \(\beta_1=0.9, \beta_2=0.999\) work well across problems—making it accessible to practitioners who can’t afford extensive tuning. The paper’s empirical comparisons showed Adam consistently matching or exceeding other optimizers while being robust to learning rate choice. Adam became the default optimizer for many applications, particularly in NLP where its adaptation to gradient statistics helps with sparse vocabularies. The paper also introduced AdaMax (a variant using \(L_\infty\) norm instead of \(L_2\)) and provided regret bound analysis connecting Adam to online convex optimization theory, though these theoretical aspects are less commonly used than the practical algorithm.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1711.05101&quot;&gt;“Decoupled Weight Decay Regularization” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ilya Loshchilov, Frank Hutter&lt;br /&gt;
This paper identified a subtle but important flaw in how Adam handles L2 regularization and proposed AdamW as the solution. The authors showed that adding weight decay to gradients (standard practice) and then applying adaptive learning rates (as Adam does) causes the effective weight decay to vary across parameters based on their gradient statistics. This coupling undermines regularization—parameters with large gradients receive less weight decay, opposite of what’s desirable. AdamW decouples weight decay from gradient-based updates, applying it directly to parameters after the adaptive update. The paper demonstrated improved generalization across multiple benchmarks, particularly for Transformers where proper regularization is crucial. AdamW has largely replaced Adam for training large language models and other Transformer-based systems. The work exemplifies how understanding the interaction between different training components (optimization + regularization) reveals subtle issues that significantly impact practical performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1908.03265&quot;&gt;“On the Variance of the Adaptive Learning Rate and Beyond” (2020)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Liyuan Liu, Haoming Jiang, Pengcheng He, Weizhu Chen, Xiaodong Liu, Jianfeng Gao, Jiawei Han&lt;br /&gt;
This paper analyzed why Adam sometimes generalizes worse than SGD despite converging faster, a phenomenon called the “generalization gap.” The authors showed that Adam’s adaptive learning rates can lead to sharp minima (low training loss but poor generalization) while SGD with momentum tends to find flatter minima (better generalization). They proposed RAdam (Rectified Adam), which modifies the bias correction to be more conservative early in training when gradient statistics are unreliable. The paper deepened understanding of the optimization-generalization tradeoff: faster convergence doesn’t always mean better final performance. It showed that variance in adaptive learning rates can be harmful and proposed variance reduction techniques. This work has influenced how practitioners use Adam—recognizing when its adaptive mechanism helps (sparse gradients, varying scales) versus when simpler methods with better generalization properties (SGD+momentum) are preferable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1907.08610&quot;&gt;“Lookahead Optimizer: k steps forward, 1 step back” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Michael R. Zhang, James Lucas, Geoffrey Hinton, Jimmy Ba&lt;br /&gt;
This paper introduced a meta-optimization algorithm that wraps around any base optimizer (SGD, Adam, etc.). Lookahead maintains two sets of weights: fast weights updated by the base optimizer and slow weights that periodically synchronize with fast weights. The algorithm runs the base optimizer for \(k\) steps (typically 5-10), then updates slow weights toward the fast weights, then resets fast weights to the slow weights. This reduces variance in optimization trajectory and improves convergence. The paper showed that Lookahead improves performance of base optimizers consistently across tasks, providing more stable training and often better generalization. While less commonly used than Adam or SGD+momentum, Lookahead demonstrates that optimization algorithms can be composed—we can build meta-algorithms that enhance existing optimizers. The paper’s empirical analysis across vision and language tasks established that optimizer design remains an active research area with room for innovation beyond the classics.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;The most common mistake when using adaptive optimizers like Adam is forgetting to adjust hyperparameters when changing batch size. With vanilla SGD, doubling batch size roughly requires doubling learning rate to maintain equivalent parameter updates (since gradients are averaged over batch). But for Adam, the relationship is more complex because adaptive learning rates already account for gradient magnitudes. A practical rule: when increasing batch size, increase learning rate proportionally but less aggressively (perhaps by \(\sqrt{2}\) instead of \(2\)), and monitor validation performance carefully. Very large batch sizes (thousands) may require learning rate warm-up to prevent early instability.&lt;/p&gt;

&lt;p&gt;A subtle issue is optimizer state accumulation when fine-tuning pre-trained models. If you load a pre-trained model and continue training with Adam, the momentum and variance estimates start from zero, not from values appropriate for a nearly-converged model. This can cause instability or prevent fine-tuning from improving the model. The solution: either use a lower learning rate for fine-tuning (allowing gradients to build up optimizer state safely) or reset the optimizer state when loading checkpoints, starting fresh. Understanding that optimizers maintain internal state beyond just parameters helps debug unexpected fine-tuning behavior.&lt;/p&gt;

&lt;p&gt;Weight decay in AdamW requires calibration differently than in SGD. For SGD, weight decay around 0.0001-0.001 is typical. For AdamW, values around 0.01-0.1 often work better because the decoupling changes its effective strength. When migrating from Adam to AdamW, don’t just enable weight decay with values tuned for SGD—you’ll likely over-regularize. Start with 0.01 and tune based on train-test gap. This illustrates a broader principle: hyperparameters are not architecture-agnostic but must be tuned within the context of the full training configuration.&lt;/p&gt;

&lt;p&gt;Gradient clipping interacts with optimizers in non-obvious ways. For Adam, clipping gradients before the optimizer sees them affects both momentum and variance estimates. If gradients are clipped to norm 5, the maximum second moment becomes 25, bounding the adaptive scaling. This can be beneficial (prevents extremely small effective learning rates) or harmful (prevents adaptation to true gradient scales). For stability, clip gradients for RNNs and Transformers. For maximum Adam adaptivity on well-behaved networks, skip clipping. Understanding this tradeoff helps choose appropriate configurations.&lt;/p&gt;

&lt;p&gt;A powerful technique for hyperparameter tuning is cyclical learning rates—varying learning rate between bounds during training. This allows the model to periodically escape local minima it might settle into, potentially finding better solutions. Combined with snapshot ensembling (saving models at different points in the cycle and ensembling their predictions), this can improve performance beyond single-model training with fixed learning rates. The computational cost is minimal (just scheduling) while benefits can be substantial, making it an underutilized trick in the practitioner’s toolkit.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Advanced optimization algorithms improve upon vanilla gradient descent by incorporating momentum to accelerate in consistent directions and dampen oscillations, and by adapting learning rates per parameter based on gradient history. SGD with momentum builds velocity from exponentially weighted gradient averages, helping traverse ravines and escape plateaus. RMSprop adapts learning rates using exponential averages of squared gradients, automatically scaling updates based on typical gradient magnitudes per parameter. Adam combines both mechanisms while including bias correction for proper early-iteration behavior, becoming the de facto standard for many applications due to robust performance with minimal tuning. AdamW improves Adam by decoupling weight decay from gradient-based updates, ensuring regularization strength is independent of adaptive scaling, crucial for training large Transformers. The choice of optimizer involves tradeoffs between convergence speed, final performance, computational cost, and hyperparameter sensitivity, with no single optimizer dominating all scenarios. Understanding each optimizer’s assumptions—what loss surface geometry it handles well, what gradient statistics it expects—enables matching algorithms to problems effectively. Modern practice often uses Adam or AdamW for initial experimentation due to robustness, potentially switching to SGD with momentum for final training if better generalization is needed. The sophistication of these algorithms shouldn’t obscure the fundamental principle: they’re all using gradients computed via backpropagation to iteratively improve parameters, differing only in how they process gradients into parameter updates.&lt;/p&gt;

&lt;p&gt;The evolution of optimization algorithms from vanilla gradient descent to modern adaptive methods represents the field learning to automate aspects of training that previously required expert tuning, democratizing deep learning while also introducing new subtleties that practitioners must understand to train models effectively.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, English. The comparison the lesson asks you to make.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, English. Adam’s failure modes (the bias correction, the learning-rate scale) are in this short derivation.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vMh0zPT0tLI&quot;&gt;Stochastic Gradient Descent, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. SGD is the baseline those comparisons keep losing or beating.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-01-02-01 Optimizer Core Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_01_02_01_Optimizer_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_01_02_01_Optimizer_Core_Code</id>
   <content type="html">&lt;p&gt;Implementing SGD, Momentum, NAG, AdaGrad, RMSprop, and Adam in ~100 lines of clean NumPy reveals an underappreciated systems reality of modern deep learning: &lt;strong&gt;optimizer states are often bigger than the model itself&lt;/strong&gt;. Every single trainable weight in Adam requires storing &lt;em&gt;two&lt;/em&gt; extra &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt; state tensors (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;m&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;v&lt;/code&gt;), tripling parameter memory before a single activation is even allocated. Coding each update rule explicitly also exposes subtle implementation details—like incrementing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self.t += 1&lt;/code&gt; &lt;em&gt;before&lt;/em&gt; bias correction and keeping &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eps&lt;/code&gt; outside the square root (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.sqrt(v_hat) + eps&lt;/code&gt;).&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-engineering-details-of-optimizer-implementations&quot;&gt;Key ideas: Engineering Details of Optimizer Implementations&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;State Buffer Allocation &amp;amp; Memory Footprint&lt;/strong&gt;: Vanilla SGD holds &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; extra floats/param; Momentum/RMSprop hold &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; float/param; Adam/AdamW hold &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2&lt;/code&gt; floats/param (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;m&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;v&lt;/code&gt;)—meaning a 7B-parameter model in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fp32&lt;/code&gt; requires \(7\text{B} \times 8\text{ bytes} = 56\text{ GB}\) just for Adam’s momentum and variance states!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step Counter Ordering (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self.t += 1&lt;/code&gt;)&lt;/strong&gt;: Computing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1 - beta1 ** self.t&lt;/code&gt; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t = 0&lt;/code&gt; divides by zero (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1 - 1 = 0&lt;/code&gt;). Incrementing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t&lt;/code&gt; at the start of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;step()&lt;/code&gt; ensures &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;t = 1&lt;/code&gt; on the very first update.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact Placement of \(\epsilon\)&lt;/strong&gt;: Adam places \(\epsilon\) &lt;em&gt;outside&lt;/em&gt; the square root (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sqrt(v_hat) + eps&lt;/code&gt;, default &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-8&lt;/code&gt;). When training in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fp16&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1e-8&lt;/code&gt; underflows or becomes too tiny relative to small gradients, which is why mixed-precision recipes often raise &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eps=1e-6&lt;/code&gt; or keep master optimizer states in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;fp32&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;In-Place Parameter Updates &amp;amp; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;zero_grad()&lt;/code&gt;&lt;/strong&gt;: In PyTorch, gradients accumulate across &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.backward()&lt;/code&gt; calls by design (enabling gradient accumulation for large effective batches), so forgetting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;optimizer.zero_grad(set_to_none=True)&lt;/code&gt; silently corrupts every step after step 1.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-memory-budget-of-training-a-100m-parameter-model-with-sgd-vs-adam&quot;&gt;Worked example: Memory Budget of Training a 100M-Parameter Model With SGD vs. Adam&lt;/h3&gt;

&lt;p&gt;Suppose a model has \(P = 100{,}000{,}000\) trainable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt; parameters (4 bytes each = \(400\text{ MB}\)):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Vanilla SGD (no momentum)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Weights (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;400 MB&lt;/code&gt;) + Gradients (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;400 MB&lt;/code&gt;) + Optimizer state (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0 MB&lt;/code&gt;) = &lt;strong&gt;800 MB&lt;/strong&gt; (\(8\text{ bytes/param}\)).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SGD + Momentum (or RMSprop)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Weights (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;400 MB&lt;/code&gt;) + Gradients (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;400 MB&lt;/code&gt;) + 1 state buffer &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;v&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;400 MB&lt;/code&gt;) = &lt;strong&gt;1,200 MB&lt;/strong&gt; (\(12\text{ bytes/param}\)).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adam / AdamW&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Weights (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;400 MB&lt;/code&gt;) + Gradients (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;400 MB&lt;/code&gt;) + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;m&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;400 MB&lt;/code&gt;) + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;v&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;400 MB&lt;/code&gt;) = &lt;strong&gt;1,600 MB&lt;/strong&gt; (\(16\text{ bytes/param}\)).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Systems Takeaway&lt;/strong&gt;: Adam doubles the static parameter+optimizer memory footprint over vanilla SGD—explaining why ZeRO-1/2/3, 8-bit Adam, and Adafactor were invented for large-scale training!&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Let’s implement optimizers from scratch to understand their mechanics:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SGDMomentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Stochastic Gradient Descent with Momentum.
    
    Maintains exponentially weighted average of gradients (velocity)
    and uses this for updates instead of raw gradients. Accelerates
    in consistent directions, dampens oscillations.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        params: list of parameter arrays to optimize
        lr: learning rate
        momentum: coefficient for velocity (β in equations)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initialize velocities to zero
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Each parameter gets its own velocity of same shape
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;velocities&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Update parameters using momentum.
        
        grads: list of gradients (same structure as params)
        
        The velocity update v_t = β*v_{t-1} + g_t creates exponential
        weighting: recent gradients contribute fully, older gradients
        contribute with weight β^k. Typical β=0.9 means we effectively
        average over ~10 recent gradients.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Update velocity: exponential moving average of gradients
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;velocities&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;velocities&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Update parameter using velocity
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Note: some formulations use (1-β)*g instead of g
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# We follow PyTorch convention
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;velocities&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RMSprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    RMSprop: Root Mean Square Propagation.
    
    Adapts learning rate per parameter based on exponential moving
    average of squared gradients. Parameters with consistently large
    gradients get smaller effective learning rate.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        beta: decay rate for gradient square average
        epsilon: small constant for numerical stability
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initialize squared gradient averages
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sq_grads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Update using adaptive learning rates.
        
        The division by √E[g²] means parameters with large typical gradients
        get smaller updates (to prevent instability), while parameters with
        small typical gradients get larger updates (to make progress).
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Update squared gradient moving average
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# E[g²]_t = β*E[g²]_{t-1} + (1-β)*g²_t
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sq_grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sq_grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; 
                               &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Adaptive learning rate: lr / √E[g²]
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Adding epsilon prevents division by zero
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;adapted_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sq_grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Update parameter
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;adapted_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Adam: Adaptive Moment Estimation.
    
    Combines momentum (first moment) and RMSprop (second moment).
    Includes bias correction for proper behavior early in training.
    The de facto standard optimizer for many deep learning tasks.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        beta1: decay rate for first moment (momentum)
        beta2: decay rate for second moment (RMSprop)
        
        Default values work well across many tasks - Adam&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s strength
        is robustness to hyperparameter choices.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initialize moments
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# First moment
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Second moment
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Time step (for bias correction)
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Adam update with bias correction.
        
        The bias correction is crucial early in training when m_t and v_t
        are biased toward zero. Without correction, early updates are too
        small, slowing initial training. The correction factor 1/(1-β^t)
        grows as t increases, then approaches 1.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Increment timestep
&lt;/span&gt;        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Update biased first moment estimate (momentum)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Update biased second moment estimate (RMSprop)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Compute bias-corrected moments
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# These corrections are largest early (when t is small)
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# and approach 1 as t → ∞
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;m_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;v_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Update parameter
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Combines momentum direction (m_hat) with adaptive scaling (√v_hat)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;AdamW&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    AdamW: Adam with decoupled weight decay.
    
    Separates L2 regularization from gradient-based optimization.
    Better generalization than Adam, especially for Transformers.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.999&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                 &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Adam update with decoupled weight decay.
        
        Key difference from Adam: weight decay is applied directly to
        parameters (θ ← θ - λθ) rather than being added to gradients.
        This ensures regularization strength is independent of adaptive
        learning rate scaling.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Update moments (same as Adam)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Bias correction
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;m_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;v_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Update with decoupled weight decay
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Weight decay happens outside adaptive scaling
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m_hat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v_hat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; 
                               &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight_decay&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;param&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, English. Write the two moment lines before any framework wrapper.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, English. Use this to check that momentum and RMSProp are not the same buffer.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, English. The step() call that should replace your hand-written update once it matches.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10-01-01 Optimizer Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_01_01_Optimizer_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_01_01_Optimizer_Theory</id>
   <content type="html">&lt;p&gt;The evolution from vanilla SGD to &lt;strong&gt;Momentum&lt;/strong&gt;, &lt;strong&gt;Nesterov Accelerated Gradient (NAG)&lt;/strong&gt;, &lt;strong&gt;AdaGrad&lt;/strong&gt;, &lt;strong&gt;RMSprop&lt;/strong&gt;, and &lt;strong&gt;Adam&lt;/strong&gt; is not a random grab-bag of heuristics—it is a clean, logical progression along two orthogonal axes: &lt;strong&gt;first-moment smoothing&lt;/strong&gt; (remembering the direction of recent gradients) and &lt;strong&gt;second-moment preconditioning&lt;/strong&gt; (normalizing each parameter by its historical gradient scale). Once you see how Adam literally fuses Momentum’s exponential moving average \(m_t\) with RMSprop’s exponential moving average \(v_t\)—and adds exact bias correction for step 1—every optimizer formula becomes effortless to derive from memory.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-unified-mathematical-family-of-first-order-optimizers&quot;&gt;Key ideas: The Unified Mathematical Family of First-Order Optimizers&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Classical Momentum &amp;amp; Nesterov Look-Ahead&lt;/strong&gt;: Heavy-ball momentum updates \(v_t = \beta v_{t-1} + g_t,\; \theta \leftarrow \theta - \eta v_t\). Nesterov evaluates the gradient &lt;em&gt;ahead&lt;/em&gt; at \(\theta - \eta \beta v_{t-1}\), acting as a predictive brake that reduces overshoot around sharp turns.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;AdaGrad &amp;amp; Its Vanishing Step Failure&lt;/strong&gt;: Accumulating the &lt;em&gt;unbounded&lt;/em&gt; sum of squared gradients \(G_t = \sum_{\tau=1}^t g_\tau^2\) works wonders on sparse NLP features, but monotonically shrinks the effective learning rate \(\eta / \sqrt{G_t}\) toward zero in long non-convex deep-learning runs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;RMSprop (Exponential Moving Average of \(g^2\))&lt;/strong&gt;: Replacing AdaGrad’s infinite sum with an exponential moving average \(v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\) forgets ancient gradients so training never stalls prematurely.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Adam &amp;amp; Zero-Initialization Bias Correction&lt;/strong&gt;: Initializing \(m_0 = 0, v_0 = 0\) biases early estimates heavily toward zero (at \(t=1\) with \(\beta_2 = 0.999\), \(v_1 = 0.001 g_1^2\)!). Dividing by \((1 - \beta_1^t)\) and \((1 - \beta_2^t)\) yields exact unbiased moment estimates \(\hat{m}_t, \hat{v}_t\) from the very first step.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-hand-tracing-2-full-steps-of-adam-with-bias-correction&quot;&gt;Worked example: Hand-Tracing 2 Full Steps of Adam (With Bias Correction)&lt;/h3&gt;

&lt;p&gt;Suppose a scalar parameter starts at \(\theta_0 = 1.0\) with hyperparameters \(\eta = 0.1, \beta_1 = 0.9, \beta_2 = 0.999, \epsilon = 10^{-8}\), initialized at \(m_0 = 0, v_0 = 0\), and receives gradients \(g_1 = 2.0\) at step 1 and \(g_2 = 1.0\) at step 2.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Step \(t = 1\) (\(g_1 = 2.0\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;First moment: \(m_1 = 0.9(0) + 0.1(2.0) = 0.2\).&lt;/li&gt;
      &lt;li&gt;Second moment: \(v_1 = 0.999(0) + 0.001(2.0^2) = 0.004\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Bias correction&lt;/strong&gt;:
\(\hat{m}_1 = \frac{0.2}{1 - 0.9^1} = \frac{0.2}{0.1} = 2.0, \quad \hat{v}_1 = \frac{0.004}{1 - 0.999^1} = \frac{0.004}{0.001} = 4.0.\)&lt;/li&gt;
      &lt;li&gt;Update:
\(\theta_1 = 1.0 - 0.1 \cdot \frac{2.0}{\sqrt{4.0} + 10^{-8}} = 1.0 - 0.1(1.0) = 0.9000.\)
&lt;em&gt;(Notice how without bias correction, \(m_1 / \sqrt{v_1} = 0.2 / \sqrt{0.004} \approx 3.16\) would have jumped \(3.16\times\) too far on step 1!)&lt;/em&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step \(t = 2\) (\(g_2 = 1.0\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(m_2 = 0.9(0.2) + 0.1(1.0) = 0.28\); \(\hat{m}_2 = \frac{0.28}{1 - 0.81} = \frac{0.28}{0.19} \approx 1.4737\).&lt;/li&gt;
      &lt;li&gt;\(v_2 = 0.999(0.004) + 0.001(1.0^2) = 0.004996\); \(\hat{v}_2 = \frac{0.004996}{1 - 0.999^2} = \frac{0.004996}{0.001999} \approx 2.4992\).&lt;/li&gt;
      &lt;li&gt;Update:
\(\theta_2 = 0.9000 - 0.1 \cdot \frac{1.4737}{\sqrt{2.4992}} \approx 0.9000 - 0.0932 = 0.8068.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;advanced-optimization-beyond-vanilla-gradient-descent&quot;&gt;Advanced Optimization: Beyond Vanilla Gradient Descent&lt;/h1&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;While gradient descent provides the fundamental principle for training neural networks—move parameters in the direction that decreases loss—its vanilla form suffers from several critical limitations that make training deep networks impractical. The learning rate must be carefully tuned: too large causes oscillation or divergence, too small causes painfully slow convergence. The same learning rate is used for all parameters, despite different parameters having different gradient scales and optimal update frequencies. Gradient descent treats all directions in parameter space equally, even though some directions represent ravines (steep in one direction, gentle in another) where we should move carefully. And it has no memory of previous gradients, unable to build momentum to escape shallow local minima or saddle points.&lt;/p&gt;

&lt;p&gt;Advanced optimization algorithms address these limitations through various mechanisms: maintaining momentum to accelerate in consistent directions while dampening oscillations; adapting learning rates per parameter based on gradient history, allowing aggressive updates for sparse gradients and conservative updates for frequent large gradients; and incorporating second-order information about the curvature of the loss surface without the prohibitive cost of computing full Hessian matrices. These improvements aren’t minor tweaks but essential techniques that have enabled training increasingly large and complex models—modern language models with billions of parameters simply couldn’t be trained with vanilla gradient descent.&lt;/p&gt;

&lt;p&gt;Understanding these optimizers deeply means recognizing that they’re not competing alternatives but tools suited for different scenarios. Stochastic Gradient Descent with momentum excels when the loss surface has clear, consistent gradient directions and is computationally efficient, making it popular for computer vision tasks with large batch sizes. RMSprop adapts learning rates based on recent gradient magnitudes, particularly useful for recurrent networks where gradient scales vary dramatically across time steps. Adam combines momentum and adaptive learning rates, providing good default performance across diverse tasks and becoming the de facto standard for many applications. AdamW improves Adam’s weight decay handling, crucial for training large Transformers. Each optimizer embodies different assumptions about the loss surface and gradient dynamics, and choosing appropriately can mean the difference between a model that trains in hours versus days, or that trains successfully versus not at all.&lt;/p&gt;

&lt;p&gt;The evolution of optimization algorithms parallels the evolution of neural architectures. As networks became deeper (requiring techniques to handle vanishing/exploding gradients), optimizers evolved to adapt learning rates and build momentum. As networks became larger (requiring training on smaller batches due to memory constraints), optimizers developed to work effectively with noisy gradient estimates. As tasks diversified (from vision to NLP to reinforcement learning), optimizers became more adaptive to different gradient landscapes. This co-evolution of architectures and optimizers is ongoing—new architectures often require optimizer innovations, and new optimizers enable new architectures.&lt;/p&gt;

&lt;p&gt;Yet with all these sophisticated algorithms, the fundamentals remain: we’re still computing gradients via backpropagation and taking steps opposite to these gradients. The advanced optimizers change how we determine step sizes and directions, leveraging gradient history and statistics, but the core principle—iterative refinement based on loss gradients—stays constant. This means that understanding vanilla gradient descent deeply provides the foundation for understanding all variants, which are best seen as sophisticated modifications addressing specific failure modes rather than entirely different approaches.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;Let’s build up the mathematics of advanced optimizers systematically, understanding each component’s purpose and how they combine to improve upon vanilla gradient descent. We’ll start with momentum and progress through increasingly sophisticated techniques.&lt;/p&gt;

&lt;h3 id=&quot;momentum-building-velocity&quot;&gt;Momentum: Building Velocity&lt;/h3&gt;

&lt;p&gt;Vanilla gradient descent updates parameters using only the current gradient:&lt;/p&gt;

\[\theta_t = \theta_{t-1} - \eta \nabla_\theta \mathcal{L}(\theta_{t-1})\]

&lt;p&gt;Momentum introduces a velocity term that accumulates gradients over time:&lt;/p&gt;

\[\mathbf{v}_t = \beta \mathbf{v}_{t-1} + \nabla_\theta \mathcal{L}(\theta_{t-1})\]

\[\theta_t = \theta_{t-1} - \eta \mathbf{v}_t\]

&lt;p&gt;where \(\beta \in [0, 1)\) is the momentum coefficient (typically 0.9). The velocity \(\mathbf{v}_t\) is an exponentially weighted moving average of gradients. Expanding the recursion reveals how past gradients influence current updates:&lt;/p&gt;

\[\mathbf{v}_t = \nabla_\theta \mathcal{L}(\theta_{t-1}) + \beta \nabla_\theta \mathcal{L}(\theta_{t-2}) + \beta^2 \nabla_\theta \mathcal{L}(\theta_{t-3}) + \ldots\]

&lt;p&gt;Recent gradients have full weight, while older gradients contribute with exponentially decaying weights \(\beta^k\). This creates several beneficial effects. First, if gradients consistently point in the same direction, the velocity builds up, accelerating progress—like a ball rolling downhill gaining speed. Second, if gradients oscillate (positive then negative), the velocity dampens oscillations—opposing gradients partially cancel. Third, momentum can carry the optimization through shallow local minima or flat regions where current gradients are near zero but past gradients indicated a good direction.&lt;/p&gt;

&lt;p&gt;The geometric intuition is that momentum transforms the gradient from a force into a velocity. In physics, force (gradient) causes acceleration, leading to velocity changes. Here, the gradient directly contributes to velocity, which determines position updates. This physics analogy isn’t perfect but captures how momentum creates inertia—the optimization continues moving in directions that were previously good even if the current gradient disagrees slightly.&lt;/p&gt;

&lt;h3 id=&quot;nesterov-accelerated-gradient-nag&quot;&gt;Nesterov Accelerated Gradient (NAG)&lt;/h3&gt;

&lt;p&gt;A clever modification of momentum computes gradients not at the current position but at the anticipated future position:&lt;/p&gt;

\[\mathbf{v}_t = \beta \mathbf{v}_{t-1} + \nabla_\theta \mathcal{L}(\theta_{t-1} - \beta \mathbf{v}_{t-1})\]

\[\theta_t = \theta_{t-1} - \eta \mathbf{v}_t\]

&lt;p&gt;The key difference is \(\nabla_\theta \mathcal{L}(\theta_{t-1} - \beta \mathbf{v}_{t-1})\) instead of \(\nabla_\theta \mathcal{L}(\theta_{t-1})\). We’re computing the gradient at where momentum would take us, then using that gradient to refine the update. This “look ahead” provides a form of correction: if momentum is carrying us toward a bad region, the gradient at the anticipated position will indicate this, allowing us to slow down or change direction.&lt;/p&gt;

&lt;p&gt;The improvement over standard momentum is subtle but consistent across many tasks. NAG typically converges faster and overshoots less at minima. The intuition is that standard momentum is reactive (respond to gradients at current position) while NAG is proactive (anticipate where we’re going and plan accordingly). In practice, the difference between momentum and NAG is often small, but NAG is theoretically better motivated and occasionally provides noticeable improvements.&lt;/p&gt;

&lt;h3 id=&quot;adagrad-adaptive-learning-rates&quot;&gt;AdaGrad: Adaptive Learning Rates&lt;/h3&gt;

&lt;p&gt;AdaGrad adapts learning rates per parameter based on accumulated squared gradients:&lt;/p&gt;

\[\mathbf{G}_t = \mathbf{G}_{t-1} + (\nabla_\theta \mathcal{L}(\theta_{t-1}))^2\]

\[\theta_t = \theta_{t-1} - \frac{\eta}{\sqrt{\mathbf{G}_t + \epsilon}} \odot \nabla_\theta \mathcal{L}(\theta_{t-1})\]

&lt;p&gt;where the square and square root are element-wise, \(\mathbf{G}_t\) accumulates squared gradients, and \(\epsilon\) (typically \(10^{-8}\)) prevents division by zero. The division by \(\sqrt{\mathbf{G}_t}\) means parameters with large accumulated gradients receive smaller updates, while parameters with small accumulated gradients receive larger updates.&lt;/p&gt;

&lt;p&gt;This adaptive scaling addresses a key limitation of vanilla gradient descent. In sparse features (common in NLP where most words don’t appear in most documents), some parameters receive gradient updates rarely. AdaGrad gives these infrequent parameters larger updates when they do receive gradients, while frequently updated parameters (corresponding to common features) receive smaller updates. This is particularly valuable in tasks with sparse data or highly variable feature frequencies.&lt;/p&gt;

&lt;p&gt;However, AdaGrad has a fatal flaw for long training runs: \(\mathbf{G}_t\) only grows, never shrinks. As training progresses, \(\sqrt{\mathbf{G}_t}\) becomes very large, making effective learning rates approach zero, and learning stops. This aggressive learning rate decay is appropriate for convex optimization where we want to slow down as we approach the minimum, but neural network loss surfaces are non-convex with many local minima, plateaus, and saddle points. Stopping adaptation too early prevents escaping these suboptimal regions.&lt;/p&gt;

&lt;h3 id=&quot;rmsprop-exponential-moving-average&quot;&gt;RMSprop: Exponential Moving Average&lt;/h3&gt;

&lt;p&gt;RMSprop fixes AdaGrad’s aggressive decay by using an exponentially weighted moving average of squared gradients instead of accumulation:&lt;/p&gt;

\[\mathbf{E}[g^2]_t = \beta \mathbf{E}[g^2]_{t-1} + (1-\beta)(\nabla_\theta \mathcal{L}(\theta_{t-1}))^2\]

\[\theta_t = \theta_{t-1} - \frac{\eta}{\sqrt{\mathbf{E}[g^2]_t + \epsilon}} \odot \nabla_\theta \mathcal{L}(\theta_{t-1})\]

&lt;p&gt;Typical \(\beta = 0.9\) means we consider roughly the last \(1/(1-\beta) = 10\) gradient updates. This allows the algorithm to forget old gradients, so if the gradient scale changes (as we move through different regions of the loss surface), the learning rate adaptation adjusts. RMSprop became particularly popular for training RNNs where gradient scales vary dramatically, and it remains a solid choice when gradient statistics change over training.&lt;/p&gt;

&lt;h3 id=&quot;adam-adaptive-moment-estimation&quot;&gt;Adam: Adaptive Moment Estimation&lt;/h3&gt;

&lt;p&gt;Adam combines momentum and RMSprop’s adaptive learning rates, maintaining both first moment (mean) and second moment (uncentered variance) estimates:&lt;/p&gt;

&lt;p&gt;\(\mathbf{m}_t = \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \nabla_\theta \mathcal{L}(\theta_{t-1})\) (momentum term)&lt;/p&gt;

&lt;p&gt;\(\mathbf{v}_t = \beta_2 \mathbf{v}_{t-1} + (1-\beta_2) (\nabla_\theta \mathcal{L}(\theta_{t-1}))^2\) (RMSprop term)&lt;/p&gt;

&lt;p&gt;These are biased toward zero initially (since \(\mathbf{m}_0 = \mathbf{v}_0 = 0\)). Adam corrects this bias:&lt;/p&gt;

\[\hat{\mathbf{m}}_t = \frac{\mathbf{m}_t}{1-\beta_1^t}, \quad \hat{\mathbf{v}}_t = \frac{\mathbf{v}_t}{1-\beta_2^t}\]

&lt;p&gt;The update rule combines both:&lt;/p&gt;

\[\theta_t = \theta_{t-1} - \frac{\eta}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon} \odot \hat{\mathbf{m}}_t\]

&lt;p&gt;Default hyperparameters \(\beta_1 = 0.9, \beta_2 = 0.999, \epsilon = 10^{-8}\) work well across many tasks, making Adam popular as a “low-tuning” optimizer. The algorithm adapts to gradient statistics (through \(\mathbf{v}_t\)) while building momentum (through \(\mathbf{m}_t\)), combining benefits of both approaches.&lt;/p&gt;

&lt;p&gt;The bias correction deserves careful attention. Early in training, \(\mathbf{m}_t\) and \(\mathbf{v}_t\) are dominated by their initialization at zero, making them biased estimates of true moments. For example, \(\mathbf{m}_1 = (1-\beta_1)g_1\) significantly underestimates \(\mathbb{E}[g]\) when \(\beta_1 = 0.9\). Dividing by \(1-\beta_1^t\) corrects this: \(\hat{\mathbf{m}}_1 = \frac{(1-\beta_1)g_1}{1-\beta_1} = g_1\). As \(t \to \infty\), \(\beta_1^t \to 0\), so the correction factor approaches 1 and has no effect. This ensures good behavior from the first update while asymptotically behaving like uncorrected exponential averages.&lt;/p&gt;

&lt;h3 id=&quot;adamw-decoupled-weight-decay&quot;&gt;AdamW: Decoupled Weight Decay&lt;/h3&gt;

&lt;p&gt;A subtle issue with Adam is how it handles L2 regularization (weight decay). Standard practice adds \(\lambda \theta\) to gradients:&lt;/p&gt;

\[\nabla \mathcal{L}_{\text{reg}} = \nabla \mathcal{L} + \lambda \theta\]

&lt;p&gt;But in Adam, this regularized gradient gets processed through adaptive learning rates, which can dilute the regularization effect. AdamW decouples weight decay from gradient-based optimization:&lt;/p&gt;

\[\mathbf{m}_t = \beta_1 \mathbf{m}_{t-1} + (1-\beta_1) \nabla_\theta \mathcal{L}(\theta_{t-1})\]

\[\mathbf{v}_t = \beta_2 \mathbf{v}_{t-1} + (1-\beta_2) (\nabla_\theta \mathcal{L}(\theta_{t-1}))^2\]

\[\theta_t = \theta_{t-1} - \eta \left(\frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon} + \lambda \theta_{t-1}\right)\]

&lt;p&gt;The weight decay term \(\lambda \theta_{t-1}\) is added after adaptive scaling, ensuring regularization strength is independent of gradient statistics. This seemingly minor change significantly improves generalization, particularly for Transformers and other large models where proper regularization is crucial.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;To understand how different optimizers behave, imagine optimizing a function with a ravine: steep sides and a gentle slope along the bottom toward the minimum. Picture a 2D loss surface where one direction has high curvature (steep) and the perpendicular direction has low curvature (gentle). The minimum lies at the bottom of this ravine.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vanilla Gradient Descent&lt;/strong&gt;: Steps perpendicular to contours of constant loss. In the ravine, gradients point mostly toward the ravine bottom (steep direction), barely along it (gentle direction). We take large steps toward the sides, bounce between them, and make slow progress along the ravine toward the minimum. It’s inefficient—most gradient magnitude is in the wrong direction (perpendicular to the path to minimum) rather than the right direction (along the ravine).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SGD with Momentum&lt;/strong&gt;: Accumulates velocity along the ravine as consistent gradients in that direction build up momentum. When gradients oscillate perpendicular to the ravine (positive then negative as we bounce between sides), the velocity in that direction dampens. We accelerate along the ravine while oscillations perpendicular to it are suppressed. The ball rolling downhill analogy is apt—momentum carries us through flat regions and helps escape shallow bowls.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AdaGrad/RMSprop&lt;/strong&gt;: Notices that gradients in the steep direction are consistently large, while gradients in the gentle direction are small. It reduces learning rate in the steep direction (to prevent bouncing) and maintains it in the gentle direction (to make progress). This automatically does gradient rescaling based on the different curvatures, allowing larger effective steps along the ravine even with smaller steps perpendicular to it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Adam&lt;/strong&gt;: Combines both mechanisms. Momentum accelerates along the ravine. Adaptive learning rates prevent excessive bouncing. The result is fast, stable progress toward the minimum. Adam also handles the fact that gradient statistics change as we move—early in training, far from the minimum, gradients are large; near the minimum, they shrink. The adaptive scaling adjusts automatically.&lt;/p&gt;

&lt;p&gt;Consider a concrete scenario: training a neural network on a dataset with rare but important features. Vanilla SGD updates all parameters equally, so rare features get updated infrequently (only when examples containing them appear). AdaGrad/Adam give these parameters larger effective learning rates (because their \(\mathbf{v}_t\) is smaller, having accumulated fewer gradient updates), allowing them to learn quickly from the few examples they see. Common features, updated frequently, get smaller effective learning rates, preventing overreaction to individual examples. This adaptivity is why Adam often converges faster than SGD, particularly in NLP where vocabulary sparsity is extreme.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, English. Each method is an average of past gradients, which is the theory.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, English. The un-averaged step those methods start from.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, English. Why any of this is descending a cost, before the moment bookkeeping.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>10 Deep Learning Algorithms</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter10/10_00_Introduction</id>
   <content type="html">&lt;p&gt;Picture standing blindfolded inside a steep, narrow canyon: the walls on your left and right plunge nearly vertically, while the canyon floor slopes gently downward toward the exit a mile away. Vanilla Stochastic Gradient Descent (SGD) takes one step perpendicular to the contour lines—slamming straight across the narrow canyon wall, overshooting to the opposite cliff, and zigzagging wildly while barely making progress down the valley. Nearly every modern deep learning optimizer—&lt;strong&gt;Momentum&lt;/strong&gt;, &lt;strong&gt;NAG&lt;/strong&gt;, &lt;strong&gt;RMSprop&lt;/strong&gt;, &lt;strong&gt;Adam&lt;/strong&gt;, and &lt;strong&gt;AdamW&lt;/strong&gt;—was invented to solve that exact geometric pathology: damping high-curvature oscillations while accelerating smoothly along flat, consistent directions.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-why-optimization-algorithms-make-or-break-deep-learning&quot;&gt;Key ideas: Why Optimization Algorithms Make or Break Deep Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Ill-Conditioned Curvature (Ravines &amp;amp; Condition Number \(\kappa\))&lt;/strong&gt;: When the Hessian eigenvalues along different parameter axes differ by orders of magnitude (\(\kappa = \lambda_{\max}/\lambda_{\min} \gg 1\)), a single global learning rate is simultaneously too large for steep axes (divergence) and too small for flat axes (crawling progress).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;First-Moment Inertia (Momentum &amp;amp; Nesterov)&lt;/strong&gt;: Maintaining an exponentially decaying velocity \(v_t = \beta v_{t-1} + g_t\) cancels out opposing zigzag gradients across steep walls while compounding consistent descent steps along the valley floor.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Second-Moment Adaptive Scaling (AdaGrad, RMSprop, Adam)&lt;/strong&gt;: Dividing each parameter’s update by the root-mean-square of its past gradients \(\sqrt{v_t} + \epsilon\) gives steep coordinates smaller effective step sizes and sparse/flat coordinates larger ones—approximating diagonal preconditioning!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decoupled Weight Decay (AdamW) &amp;amp; Schedules&lt;/strong&gt;: Coupling L2 regularization inside adaptive denominators distorts decay strength across coordinates; decoupling weight decay from the gradient step plus cosine/warmup schedules became the foundation of modern deep learning training.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-condition-number-of-a-2d-ravine--max-stable-sgd-step-size&quot;&gt;Worked example: Condition Number of a 2D Ravine &amp;amp; Max Stable SGD Step Size&lt;/h3&gt;

&lt;p&gt;Consider the quadratic ravine \(f(x, y) = \frac{1}{2}(x^2 + 100 y^2)\) with minimum at \((0, 0)\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Hessian and condition number&lt;/strong&gt;:
\(H = \begin{bmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 100 \end{bmatrix} \implies \lambda_{\min} = 1,\; \lambda_{\max} = 100,\; \kappa = \frac{\lambda_{\max}}{\lambda_{\min}} = 100.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stability ceiling for vanilla SGD&lt;/strong&gt; (requires \(\eta &amp;lt; 2 / \lambda_{\max}\)):
\(\eta_{\max} = \frac{2}{100} = 0.02.\)
If we safely choose \(\eta = 0.01\):
    &lt;ul&gt;
      &lt;li&gt;Along the steep \(y\)-axis, \(y_{t+1} = (1 - 0.01 \times 100) y_t = 0\) (converges in 1 step!).&lt;/li&gt;
      &lt;li&gt;Along the flat \(x\)-axis, \(x_{t+1} = (1 - 0.01 \times 1) x_t = 0.99 x_t\)—taking &lt;strong&gt;459 steps&lt;/strong&gt; just to reduce \(x\) to \(1\%\) of its starting error (\(0.99^{459} \approx 0.01\))!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why adaptive optimizers shine&lt;/strong&gt;: Scaling each axis by \(1/\sqrt{\text{curvature}}\) equalizes effective step sizes across \(x\) and \(y\) simultaneously.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Advanced deep-learning algorithms improve training speed and convergence. This chapter covers momentum, RMSprop, Adam, AdamW, and learning rate schedules. Understanding these optimizers is essential for efficiently training deep neural networks and achieving state-of-the-art results.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After Adam and AdamW, see &lt;strong&gt;10-99 Modern Applications and Updates&lt;/strong&gt; for Lion, Sophia, Muon, and schedule-free training.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (interview practice):&lt;/strong&gt; After the optimizer notes, see &lt;strong&gt;10-98 Interviews Practice&lt;/strong&gt; for original Adam / momentum / warmup prompts; the solved bank is &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LLM hub:&lt;/strong&gt; Which parameters receive AdamW weight decay in a decoder LM is the short checklist in &lt;strong&gt;26-01&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, English. Adam is the optimizer this chapter is heading toward.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, English. Momentum, RMSProp, AdaGrad, and Adam in one comparison.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, English. Plain gradient descent, the baseline every later method modifies.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Walk into a modern frontier LLM pretraining run (Llama, Gemma, Qwen) and you will notice something surprising: &lt;strong&gt;Dropout is almost completely gone&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dropout = 0.0&lt;/code&gt;), replaced by single-epoch multi-trillion-token data streams, decoupled weight decay (AdamW), and RMSNorm—while in Vision Transformers and ConvNeXt, &lt;strong&gt;DropPath (Stochastic Depth)&lt;/strong&gt; and &lt;strong&gt;Sharpness-Aware Minimization (SAM)&lt;/strong&gt; have largely superseded neuron-level dropout. Understanding &lt;em&gt;why&lt;/em&gt; modern recipes shifted from random neuron masking to path dropping and flat-minima optimization connects textbook regularization directly to 2022–2026 research.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-modern-regularization-recipes-sam-droppath-llm-stacks&quot;&gt;Key ideas: Modern Regularization Recipes (SAM, DropPath, LLM Stacks)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Sharpness-Aware Minimization (SAM)&lt;/strong&gt;: Instead of minimizing loss only at the current point \(w\), SAM minimizes the worst-case loss inside an \(\ell_2\) ball of radius \(\rho\): \(\min_w \max_{\|\epsilon\|_2 \le \rho} \mathcal{L}(w + \epsilon)\)—explicitly steering SGD into wide, flat basins that generalize better under distribution shift.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stochastic Depth / DropPath&lt;/strong&gt;: In deep residual vision backbones (ViT, ConvNeXt, Swin), randomly dropping entire residual branches \(x + \text{DropPath}(F(x))\) with linearly increasing drop probability across depth regularizes deep pathways far more effectively than dropping individual activations.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why Frontier LLMs Often Use Zero Dropout&lt;/strong&gt;: When pretraining on trillions of unique tokens (roughly 1 epoch), the model rarely sees the same example twice—so classic memorization overfitting is minimal, and dropout actually wastes effective model capacity per FLOP.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Label Smoothing, Z-Loss, and QK-Norm&lt;/strong&gt;: Modern large-scale recipes pair decoupled weight decay with logit stabilization (router/logit z-loss) and Query–Key normalization to prevent attention-logit explosion at billion-parameter scale.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-one-two-step-sam-update-on-a-1d-sharp-vs-flat-valley&quot;&gt;Worked example: One Two-Step SAM Update on a 1D Sharp vs. Flat Valley&lt;/h3&gt;

&lt;p&gt;Suppose we evaluate a 1D loss \(\mathcal{L}(w) = 10(w - 1)^2\) at \(w = 1.2\) with perturbation radius \(\rho = 0.05\) and learning rate \(\eta = 0.02\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Step 1 — Ascent to the worst-case neighbor \(w_{\text{adv}}\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Local gradient: \(g = \mathcal{L}&apos;(1.2) = 20(1.2 - 1) = 4.0\).&lt;/li&gt;
      &lt;li&gt;
        &lt;table&gt;
          &lt;tbody&gt;
            &lt;tr&gt;
              &lt;td&gt;Normalized adversarial step: $$\hat{\epsilon} = \rho \frac{g}{&lt;/td&gt;
              &lt;td&gt;g&lt;/td&gt;
              &lt;td&gt;} = 0.05 \times (+1) = +0.05$$.&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/li&gt;
      &lt;li&gt;Perturbed weight: \(w_{\text{adv}} = 1.2 + 0.05 = 1.25\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step 2 — Compute gradient at the perturbed point and update original \(w\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Gradient at \(w_{\text{adv}}\): \(g_{\text{adv}} = \mathcal{L}&apos;(1.25) = 20(1.25 - 1) = 5.0\).&lt;/li&gt;
      &lt;li&gt;SAM weight update: \(w_{\text{new}} = w - \eta g_{\text{adv}} = 1.2 - 0.02(5.0) = 1.10\) (vs. standard SGD’s \(1.2 - 0.02(4.0) = 1.12\)).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Intuition&lt;/strong&gt;: In a sharp ravine, stepping \(\rho\) uphill reveals a much steeper slope, pushing the optimizer aggressively away from sharp cliffs at the cost of \(2\times\) forward/backward passes per step.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-regularization-after-dropout--sam-droppath-and-llm-recipes&quot;&gt;Optional: regularization after dropout — SAM, DropPath, and LLM recipes&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace dropout or BatchNorm theory. It covers the regularizers that actually appear in 2022–2026 training recipes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Dropout&lt;/p&gt;

\[\tilde{\mathbf{h}} = \frac{\mathbf{m} \odot \mathbf{h}}{1-p}, \quad m_i \sim \mathrm{Bernoulli}(1-p)\]

&lt;p&gt;is still the right mental model. Large Transformers, however, often drop &lt;strong&gt;residual branches&lt;/strong&gt; (stochastic depth / DropPath) rather than hidden units, and they lean on &lt;strong&gt;weight decay + data scale&lt;/strong&gt; more than on classic dropout.&lt;/p&gt;

&lt;h2 id=&quot;1-sharpness-aware-minimization-sam&quot;&gt;1. Sharpness-Aware Minimization (SAM)&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2010.01412&quot;&gt;Foret et al., 2021&lt;/a&gt; (widely adopted after 2022 in vision) seek parameters that stay good in a neighborhood:&lt;/p&gt;

\[\min_\theta \max_{\|\boldsymbol{\varepsilon}\|_2 \le \rho} \mathcal{L}(\theta + \boldsymbol{\varepsilon}).\]

&lt;p&gt;The practical step is a two-forward update: climb to \(\theta + \rho \frac{\nabla \mathcal{L}}{\|\nabla \mathcal{L}\|}\), then step using that “worst-case” gradient. &lt;a href=&quot;https://arxiv.org/abs/2102.11600&quot;&gt;ASAM&lt;/a&gt; and later SAM-for-LLM papers adapt the radius. This is regularization of the &lt;strong&gt;optimizer trajectory&lt;/strong&gt;, complementary to dropout’s noise on activations.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;stochastic-depth--droppath&quot;&gt;Stochastic depth / DropPath&lt;/h3&gt;

&lt;p&gt;Vision ConvNeXt and ViT recipes randomly drop an entire residual block during training (Huang et al., 2016; used as default in 2022–2026 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timm&lt;/code&gt; recipes). That is dropout on &lt;strong&gt;paths&lt;/strong&gt;, not units — the implementation is a few lines, the effect is implicit ensembling of shallower nets.&lt;/p&gt;

&lt;h3 id=&quot;what-llms-actually-use&quot;&gt;What LLMs actually use&lt;/h3&gt;

&lt;p&gt;LLaMA-style training: &lt;strong&gt;weight decay&lt;/strong&gt; (AdamW), token-level dropout rarely, sometimes attention/dropout on tiny models only. The regularizer that matters at 7B+ is &lt;strong&gt;data mixture + packing + decay&lt;/strong&gt;, plus later RLHF/DPO (Chapter 21). Do not expect the homework dropout rate \(p=0.5\) in a Llama trainer.&lt;/p&gt;

&lt;h3 id=&quot;normalization-variants-as-regularizers&quot;&gt;Normalization variants as regularizers&lt;/h3&gt;

&lt;p&gt;LayerNorm / RMSNorm replaced BatchNorm in sequence models (already in Chapter 09’s BN variants). Residual + norm is part of the regularizer story: they stabilize scale so you can train longer without exploding features.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timm&lt;/code&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DropPath&lt;/code&gt; and SAM implementations in &lt;a href=&quot;https://github.com/jettify/pytorch-optimizer&quot;&gt;pytorch-optimizer&lt;/a&gt; / &lt;a href=&quot;https://github.com/davda54/sam&quot;&gt;sam&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.optim.AdamW&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_decay&lt;/code&gt; (see Chapter 10).&lt;/li&gt;
  &lt;li&gt;Hugging Face training recipes (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Trainer&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;trl&lt;/code&gt;) — weight decay defaults, little hidden dropout.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2010.01412&quot;&gt;Sharpness-Aware Minimization (Foret et al., 2021)&lt;/a&gt; — the SAM objective used throughout 2022–2026 vision.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2201.03545&quot;&gt;ConvNeXt (Liu et al., 2022)&lt;/a&gt; — stochastic depth as a first-class recipe ingredient.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1711.05101&quot;&gt;AdamW (Loshchilov &amp;amp; Hutter, 2019)&lt;/a&gt; — decoupled decay; still the LLM default in 2026.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Keep the dropout inverted-dropout derivation and the BatchNorm placement notes. This lesson only adds &lt;strong&gt;SAM&lt;/strong&gt; and &lt;strong&gt;DropPath&lt;/strong&gt;, and warns that foundation-model recipes drifted away from heavy unit dropout.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=k6-jJ58MFKU&quot;&gt;Sharpness-Aware Minimization (SAM) in 7 minutes&lt;/a&gt; — Yuxiang “Shawn” Wang, English. Sharpness-aware minimization is the 2021–2026 generalization method this note adds.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=DEMmkFC6IGM&quot;&gt;Overfitting in a Neural Network explained&lt;/a&gt; — deeplizard, English. The overfitting problem SAM is still trying to solve.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer, English. Bias and variance, so the sharpness story has the older vocabulary next to it.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-98 Interviews Practice (overfitting and regularizers)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;Regularization and normalization questions are staples of ML engineering interviews because they separate practitioners who memorize API flags from those who actually debug diverging or overfitting training runs. Can you explain geometrically why L1 induces exact sparsity while L2 shrinks weights smoothly? Can you trace what breaks when &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; is forgotten on a network containing both Dropout and BatchNorm? These five focused prompts sharpen your diagnostic instincts.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-high-signal-interview-concepts-in-regularization&quot;&gt;Key ideas: High-Signal Interview Concepts in Regularization&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Diagnosing Overfitting vs. Underfitting&lt;/strong&gt;: Reading train/val loss divergence curves and matching remedies (data augmentation, weight decay, dropout, early stopping) to the actual failure mode.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;L1 vs. L2 Geometry &amp;amp; Subgradients&lt;/strong&gt;: Understanding why the diamond-shaped L1 ball intersects loss contours on coordinate axes (exact zeros / feature selection), whereas the circular L2 ball shrinks all coordinates proportionally without zeroing them.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Train vs. Eval Mode Semantics&lt;/strong&gt;: Articulating the exact mathematical difference between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train()&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval()&lt;/code&gt; for both Dropout (masking + \(1/(1-p)\) scaling vs. identity) and BatchNorm (batch stats vs. EMA running stats).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Data Augmentation as Implicit Invariance&lt;/strong&gt;: Framing random crops, flips, and Mixup as injecting domain-symmetry priors directly into the empirical risk distribution.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-one-gradient-step--l1-vs-l2-regularization-on-a-small-weight&quot;&gt;Worked example: One Gradient Step — L1 vs. L2 Regularization on a Small Weight&lt;/h3&gt;

&lt;p&gt;Suppose a single weight currently sits at \(w = 0.02\), the data-loss gradient is \(g = 0\) (an irrelevant feature!), learning rate is \(\eta = 0.1\), and regularization strength is \(\lambda = 0.3\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Under L2 regularization (\(\frac{\lambda}{2} w^2\), gradient \(\lambda w\))&lt;/strong&gt;:
\(w_{\text{new}} = 0.02 - 0.1(0.3 \times 0.02) = 0.02 - 0.0006 = 0.0194.\)
As \(w\) gets smaller, the L2 pull shrinks proportionally—so \(w\) approaches \(0\) asymptotically but never hits exact \(0\).&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;**Under L1 regularization ($$\lambda&lt;/td&gt;
          &lt;td&gt;w&lt;/td&gt;
          &lt;td&gt;\(, subgradient\)\lambda \operatorname{sign}(w)$$ with proximal/soft-thresholding)**:&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
    &lt;ul&gt;
      &lt;li&gt;
        &lt;table&gt;
          &lt;tbody&gt;
            &lt;tr&gt;
              &lt;td&gt;Pull magnitude is a constant $$\eta \lambda = 0.1 \times 0.3 = 0.03 &amp;gt;&lt;/td&gt;
              &lt;td&gt;w&lt;/td&gt;
              &lt;td&gt;$$.&lt;/td&gt;
            &lt;/tr&gt;
          &lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/li&gt;
      &lt;li&gt;Proximal step snaps \(w_{\text{new}} = \operatorname{sign}(w)\max(|w| - \eta\lambda, 0) = 0.0\) &lt;strong&gt;exactly&lt;/strong&gt;!
That constant-slope pull near zero is why L1 yields sparse models while L2 yields small dense weights.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-interview-practice--overfitting-and-regularizers&quot;&gt;Optional: interview practice — overfitting and regularizers&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace dropout, BatchNorm, or the other regularization notes. After those lessons, use this drill, then open &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for solved items on overfitting, validation, and capacity control.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Book themes for this chapter (study in the PDF, not here):&lt;/strong&gt; overfitting / generalization, validation, and the regularizers that appear in the expanded deep-learning topic area.&lt;/p&gt;

&lt;p&gt;Hub: &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;practice-prompts-original&quot;&gt;Practice prompts (original)&lt;/h2&gt;

&lt;h3 id=&quot;q1-train-loss-down-val-loss-up&quot;&gt;Q1. Train loss down, val loss up&lt;/h3&gt;

&lt;p&gt;Training cross-entropy is still falling after epoch 40; validation cross-entropy rose from epoch 25. Name two &lt;em&gt;different&lt;/em&gt; interventions (not “get more GPUs”) and what each assumes about the gap.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; One changes the hypothesis class or the effective objective; one changes &lt;em&gt;when&lt;/em&gt; you stop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; (1) Stronger regularization (higher weight decay, more dropout, more augmentation) assumes the model can still fit the training set but is too flexible. (2) Early stopping / model selection on a true validation split assumes you already passed the useful-capacity point. Collecting more labeled data attacks the same gap from the sample-size side. Retraining from scratch with a smaller net is a capacity change, not a training-time regularizer.&lt;/p&gt;

&lt;h3 id=&quot;q2-l2-vs-l1-on-a-linear-head&quot;&gt;Q2. L2 vs L1 on a linear head&lt;/h3&gt;

&lt;p&gt;For a linear layer, compare adding \(\frac{\lambda}{2}\|\mathbf{w}\|_2^2\) vs \(\lambda\|\mathbf{w}\|_1\) to the loss. Which one drives individual weights to &lt;em&gt;exact&lt;/em&gt; zero more readily, and why is that only a partial story in a ReLU net?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; The L1 subgradient contains an interval at 0; L2’s gradient is linear and shrinks but rarely hits zero in SGD.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; L1 (lasso-style) can produce exact zeros; L2 shrinks weights toward the origin without a sparsity incentive. In a deep ReLU network the “feature” that is zeroed is an &lt;em&gt;activation path&lt;/em&gt;, not a single coordinate of \(\mathbf{w}\), so L1 on raw weights is a blunt instrument. Weight decay (L2) remains the default because it is rotation-friendly in the linear case and cheap.&lt;/p&gt;

&lt;h3 id=&quot;q3-dropout-train-vs-eval&quot;&gt;Q3. Dropout train vs eval&lt;/h3&gt;

&lt;p&gt;A unit is dropped with probability \(p=0.5\) at training time. What must you do at evaluation so that the expected pre-activation matches training? What goes wrong if you forget?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Inverted dropout vs classic dropout scaling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Inverted dropout (the usual framework default) scales surviving units by \(1/(1-p)\) &lt;em&gt;during training&lt;/em&gt; and uses the full net at eval. Classic dropout leaves training unscaled and multiplies weights by \(1-p\) at eval. If you drop at train and do nothing at eval, every layer is systematically larger than the network you optimized — calibration and accuracy both suffer. Saying “dropout is an ensemble of \(2^n\) nets” is a slogan; the operational point is the scaling.&lt;/p&gt;

&lt;h3 id=&quot;q4-batchnorm-at-train-and-at-test&quot;&gt;Q4. BatchNorm at train and at test&lt;/h3&gt;

&lt;p&gt;Why does BatchNorm store running means, and what breaks if you evaluate a freshly loaded checkpoint in train mode on a batch of size 1?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Train uses batch statistics; eval uses the moving average.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; The stored moments are the test-time estimate of \(\mathbb{E}[\mathbf{h}]\) and \(\mathrm{Var}(\mathbf{h})\). A batch of size 1 makes the batch variance undefined or noisy, so train-mode BN is not a drop-in eval. Small-batch training has the same issue — that is why LayerNorm / GroupNorm appear in other chapters’ recipes, but the interview answer for &lt;em&gt;this&lt;/em&gt; chapter is: know which statistics are in use.&lt;/p&gt;

&lt;h3 id=&quot;q5-augmentation-as-a-regularizer&quot;&gt;Q5. Augmentation as a regularizer&lt;/h3&gt;

&lt;p&gt;You cannot increase \(\lambda\) because the train loss is already high. Give one data-side regularizer that does not add a penalty term to \(J(\mathbf{w})\), and one failure mode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; The training distribution becomes a smoothed version of the original.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Random crops, flips, or color jitter inject invariance you care about without changing the parameter penalty. Failure: augmentations that destroy the label (e.g. a crop that removes the object) add &lt;em&gt;noise&lt;/em&gt;, not useful invariance, and can raise both train and val error. Early stopping is another penalty-free regularizer; it does not replace a bad augmentation policy.&lt;/p&gt;

&lt;h2 id=&quot;attribution&quot;&gt;Attribution&lt;/h2&gt;

&lt;p&gt;Kashani, S., and Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Download the PDF from arXiv for the full solved Q&amp;amp;A. This page is original course practice, not a reprint.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer, English. The overfitting prompts.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Q81RR3yKn30&quot;&gt;Regularization Part 1: Ridge (L2) Regression&lt;/a&gt; — StatQuest with Josh Starmer, English. L2 weight decay is the classical regularizer those prompts still ask for.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=D8PJAL-MZv8&quot;&gt;Dropout Regularization (C2W1L06)&lt;/a&gt; — DeepLearningAI, English. Dropout is the neural-net regularizer to set beside L2.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-02 Batch Normalization</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_02_Batch_Normalization/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_02_Batch_Normalization</id>
   <content type="html">&lt;p&gt;Few ideas in deep learning delivered a bigger immediate payoff than normalizing intermediate layer activations. In just two lines of math—standardize, then scale and shift—Batch Normalization tamed gradient explosion, accelerated convergence by \(5\times\text{–}10\times\), and unlocked deep architectures like ResNet. This module hub connects the exact train/eval mechanics of BatchNorm with its placement rules and batch-independent successors (LayerNorm, InstanceNorm, GroupNorm).&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-batch-normalization--its-family-tree&quot;&gt;Key ideas: Batch Normalization &amp;amp; Its Family Tree&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Exact Forward/Eval Mechanics&lt;/strong&gt;: Computing mini-batch mean/variance during training, updating EMA running statistics, and freezing them at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Architectural Placement &amp;amp; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias=False&lt;/code&gt;&lt;/strong&gt;: Understanding Conv–BN–ReLU ordering and why preceding conv biases are mathematically redundant.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Choosing the Right Normalizer&lt;/strong&gt;: Matching BatchNorm (large-batch CNNs), GroupNorm (small-batch vision), InstanceNorm (style transfer), and LayerNorm/RMSNorm (Transformers).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-verifying-why-conv-bias-cancels-out-before-batchnorm&quot;&gt;Worked example: Verifying Why Conv Bias Cancels Out Before BatchNorm&lt;/h3&gt;

&lt;p&gt;Suppose a convolutional channel outputs \(z_i = u_i + b\) across a batch \(i = 1 \dots m\), where \(b\) is a constant scalar bias added to every sample in that channel.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Batch mean with bias&lt;/strong&gt;:
\(\mu_z = \frac{1}{m}\sum_{i=1}^m (u_i + b) = \mu_u + b.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Centered activations&lt;/strong&gt;:
\(z_i - \mu_z = (u_i + b) - (\mu_u + b) = u_i - \mu_u.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Batch variance&lt;/strong&gt;:
\(\sigma_z^2 = \frac{1}{m}\sum_{i=1}^m (u_i - \mu_u)^2 = \sigma_u^2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;: Both numerator and denominator of \(\hat{z}_i = (z_i - \mu_z)/\sqrt{\sigma_z^2 + \epsilon}\) are &lt;strong&gt;100% independent of \(b\)&lt;/strong&gt;—proving &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias=False&lt;/code&gt; before BatchNorm loses zero expressivity while saving parameters and memory bandwidth!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Batch normalization:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mechanics&lt;/strong&gt; — what BN is, how it works, implementation, why it helps&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Placement, Variants, and Tips&lt;/strong&gt; — CNNs, LayerNorm and alternatives, issues, modern practice&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=nUUqwaxLnWs&quot;&gt;Why Does Batch Norm Work? (C2W3L06)&lt;/a&gt; — DeepLearningAI, English. Why normalizing a batch changes training, which is this block’s question.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=P6sfmUTpUmc&quot;&gt;Building makemore Part 3: Activations &amp;amp; Gradients, BatchNorm&lt;/a&gt; — Andrej Karpathy, English. Batch norm implemented inside a real training run, including the activation interaction.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 6&lt;/td&gt;
          &lt;td&gt;Training Neural Networks I](https://www.youtube.com/watch?v=wEoyxE0GP2M) — Stanford University School of Engineering, English. The lecture placement of batch norm among other training tricks.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-02-02 Batch Norm Placement, Variants, and Tips</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_02_02_BatchNorm_Placement_and_Variants/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_02_02_BatchNorm_Placement_and_Variants</id>
   <content type="html">&lt;p&gt;Batch Normalization conquered ImageNet CNNs trained with batch sizes of 64 to 256—yet the moment you move to high-resolution object detection (batch size 2), style transfer, or variable-length Transformers, normalizing &lt;em&gt;across the batch axis&lt;/em&gt; breaks down completely: noisy 2-sample variance estimates destabilize training, and padding tokens pollute sequence statistics. That exact limitation gave birth to the normalization family tree—&lt;strong&gt;LayerNorm&lt;/strong&gt;, &lt;strong&gt;InstanceNorm&lt;/strong&gt;, and &lt;strong&gt;GroupNorm&lt;/strong&gt;—each differing solely in &lt;em&gt;which axes&lt;/em&gt; of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, C, H, W)&lt;/code&gt; tensor are averaged together.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-axis-geometry-of-normalization-variants&quot;&gt;Key ideas: The Axis Geometry of Normalization Variants&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;BatchNorm2d — Normalize Over &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, H, W)&lt;/code&gt; per Channel &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;C&lt;/code&gt;&lt;/strong&gt;: Computes one mean and variance per channel across the entire mini-batch and spatial grid. Excels on medium/large-batch CNNs; degrades sharply when per-GPU batch size drops below ~8.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LayerNorm — Normalize Over &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(C, H, W)&lt;/code&gt; (or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;D&lt;/code&gt;) per Sample &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;N&lt;/code&gt;&lt;/strong&gt;: Completely independent of batch size and sequence length, with identical behavior at train and test time—making it (and RMSNorm) the undisputed standard for Transformers and RNNs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;InstanceNorm — Normalize Over &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(H, W)&lt;/code&gt; per Sample &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;N&lt;/code&gt; and Channel &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;C&lt;/code&gt;&lt;/strong&gt;: Strips per-image contrast and color statistics independently for each channel, making it the workhorse of neural style transfer and image-to-image translation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GroupNorm — Normalize Over &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(C/G, H, W)&lt;/code&gt; per Sample &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;N&lt;/code&gt; and Group &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;G&lt;/code&gt;&lt;/strong&gt;: Splits channels into \(G\) groups (e.g., \(G = 32\)), interpolating smoothly between LayerNorm (\(G=1\)) and InstanceNorm (\(G=C\)) while remaining 100% batch-size independent for detection/segmentation backbones.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-counting-normalization-groups-on-a-n2-c6-h4-w4-tensor&quot;&gt;Worked example: Counting Normalization Groups on a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N=2, C=6, H=4, W=4)&lt;/code&gt; Tensor&lt;/h3&gt;

&lt;p&gt;Consider a 4D feature tensor of shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N=2, C=6, H=4, W=4)&lt;/code&gt; (total \(2 \times 6 \times 16 = 192\) activations). How many &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(mean, var)&lt;/code&gt; pairs are computed, and how many elements are averaged in each?&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;BatchNorm2d&lt;/strong&gt; (axes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, H, W)&lt;/code&gt;):
    &lt;ul&gt;
      &lt;li&gt;\(C = 6\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(mean, var)&lt;/code&gt; pairs; each averages \(N \cdot H \cdot W = 2 \times 4 \times 4 = 32\) elements.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LayerNorm&lt;/strong&gt; (axes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(C, H, W)&lt;/code&gt;):
    &lt;ul&gt;
      &lt;li&gt;\(N = 2\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(mean, var)&lt;/code&gt; pairs; each averages \(C \cdot H \cdot W = 6 \times 4 \times 4 = 96\) elements.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;InstanceNorm2d&lt;/strong&gt; (axes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(H, W)&lt;/code&gt;):
    &lt;ul&gt;
      &lt;li&gt;\(N \cdot C = 12\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(mean, var)&lt;/code&gt; pairs; each averages \(H \cdot W = 4 \times 4 = 16\) elements.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GroupNorm with \(G = 2\) groups&lt;/strong&gt; (each group has \(C / G = 3\) channels):
    &lt;ul&gt;
      &lt;li&gt;\(N \cdot G = 4\) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(mean, var)&lt;/code&gt; pairs; each averages \((C/G) \cdot H \cdot W = 3 \times 4 \times 4 = 48\) elements.
Notice the invariant: in every single variant, \((\text{\# groups}) \times (\text{elements per group}) = 192\)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;where-to-place-batch-norm&quot;&gt;Where to Place Batch Norm&lt;/h2&gt;

&lt;h3 id=&quot;before-or-after-activation&quot;&gt;Before or After Activation?&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Original paper (before activation)&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Modern practice (after activation)&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Both work, but “after” is more common now.&lt;/p&gt;

&lt;h3 id=&quot;complete-network-example&quot;&gt;Complete Network Example&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvNetWithBatchNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Convolution + BatchNorm + Activation
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Conv2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Conv2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Conv2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm1D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Block 1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Block 2
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Block 3
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Fully connected
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;batch-normalization-for-cnns&quot;&gt;Batch Normalization for CNNs&lt;/h2&gt;

&lt;p&gt;For convolutional layers, normalize across spatial dimensions:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Parameters: one per channel
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Running statistics
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: shape (batch, channels, height, width)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Compute mean and var across batch and spatial dims
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Keep channel dimension
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Normalize
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Scale and shift
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Update running stats
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
                               &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
                              &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt;
            
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; \
                    &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;variants-and-alternatives&quot;&gt;Variants and Alternatives&lt;/h2&gt;

&lt;h3 id=&quot;1-layer-normalization&quot;&gt;1. Layer Normalization&lt;/h3&gt;

&lt;p&gt;Normalize across features instead of batch:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;layer_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    x: shape (batch, features)
    Normalize each sample independently
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Use case&lt;/strong&gt;: RNNs, Transformers (where batch size varies or is 1)&lt;/p&gt;

&lt;h3 id=&quot;2-instance-normalization&quot;&gt;2. Instance Normalization&lt;/h3&gt;

&lt;p&gt;Normalize each sample and each channel independently:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;instance_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    x: shape (batch, channels, height, width)
    Normalize each instance and channel
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Use case&lt;/strong&gt;: Style transfer, GANs&lt;/p&gt;

&lt;h3 id=&quot;3-group-normalization&quot;&gt;3. Group Normalization&lt;/h3&gt;

&lt;p&gt;Compromise between Layer and Instance norm:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;group_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_groups&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    x: shape (batch, channels, height, width)
    Split channels into groups and normalize
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_groups&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_groups&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Use case&lt;/strong&gt;: Small batch sizes, object detection&lt;/p&gt;

&lt;h2 id=&quot;common-issues-and-solutions&quot;&gt;Common Issues and Solutions&lt;/h2&gt;

&lt;h3 id=&quot;issue-1-small-batch-sizes&quot;&gt;Issue 1: Small Batch Sizes&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Unreliable batch statistics with small batches&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solutions&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Use Group Normalization or Layer Normalization&lt;/li&gt;
  &lt;li&gt;Increase batch size if possible&lt;/li&gt;
  &lt;li&gt;Use larger momentum for running statistics&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;issue-2-train-test-discrepancy&quot;&gt;Issue 2: Train-Test Discrepancy&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Different behavior between training and testing&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Always remember to set training mode correctly&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Training
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# or training=True
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Testing
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# or training=False
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;evaluate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;issue-3-batch-norm--dropout&quot;&gt;Issue 3: Batch Norm + Dropout&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Can interact poorly&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solutions&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Usually don’t need dropout with batch norm&lt;/li&gt;
  &lt;li&gt;If using both: dropout after batch norm&lt;/li&gt;
  &lt;li&gt;Or use only one of them&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practical-tips&quot;&gt;Practical Tips&lt;/h2&gt;

&lt;h3 id=&quot;1-initialization-with-batch-norm&quot;&gt;1. Initialization with Batch Norm&lt;/h3&gt;

&lt;p&gt;Can use larger initial weights:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Without BatchNorm: careful initialization
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# With BatchNorm: can be more aggressive
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.05&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Larger variance OK
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;2-learning-rates&quot;&gt;2. Learning Rates&lt;/h3&gt;

&lt;p&gt;Can use much higher learning rates:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Without BatchNorm
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# With BatchNorm
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 10x higher!
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;3-momentum-for-running-stats&quot;&gt;3. Momentum for Running Stats&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Fast adaptation (small datasets)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Stable statistics (large datasets)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Default
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Very stable (production)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;batch-norm-in-modern-architectures&quot;&gt;Batch Norm in Modern Architectures&lt;/h2&gt;

&lt;h3 id=&quot;resnet&quot;&gt;ResNet&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet_block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Conv -&amp;gt; BN -&amp;gt; ReLU
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Conv -&amp;gt; BN
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Add skip connection before final ReLU
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;mobilenet&quot;&gt;MobileNet&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;depthwise_separable_block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Depthwise conv
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;depthwise_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Pointwise conv
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_1x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Batch Normalization&lt;/strong&gt; normalizes layer inputs to stable distribution&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Reduces internal covariate shift&lt;/strong&gt;, enables faster training&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Allows higher learning rates&lt;/strong&gt; (10-100x speedup)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Acts as regularization&lt;/strong&gt;, reduces need for dropout&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Variants&lt;/strong&gt;: Layer Norm (RNNs), Instance Norm (style transfer), Group Norm (small batches)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Modern practice&lt;/strong&gt;: Essential in almost all deep networks&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Key&lt;/strong&gt;: Remember training vs. inference modes!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Batch Normalization revolutionized deep learning by making networks much easier to train. It’s now a standard component in almost every modern architecture.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Next&lt;/strong&gt;: We’ll explore L1/L2 regularization, early stopping, and data augmentation to complete our regularization toolkit!&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=nUUqwaxLnWs&quot;&gt;Why Does Batch Norm Work? (C2W3L06)&lt;/a&gt; — DeepLearningAI, English. So placement debates (before or after the activation) have a mechanism under them.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=P6sfmUTpUmc&quot;&gt;Building makemore Part 3: Activations &amp;amp; Gradients, BatchNorm&lt;/a&gt; — Andrej Karpathy, English. Where the norm actually sits in a modern block, and what breaks if the batch is tiny.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 7&lt;/td&gt;
          &lt;td&gt;Training Neural Networks II](https://www.youtube.com/watch?v=_JB0AO7QxSA) — Stanford University School of Engineering, English. Layer-norm style alternatives show up in this second training lecture’s modern-architecture discussion.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-02-01 Batch Normalization Mechanics</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_02_01_BatchNorm_Mechanics/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_02_01_BatchNorm_Mechanics</id>
   <content type="html">&lt;p&gt;Before 2015, training a 20-layer neural network felt like balancing a broomstick on your fingertip: choose a learning rate slightly too large or initialize weights slightly off scale, and layer activations either exploded into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; or collapsed into dead ReLUs. Sergey Ioffe and Christian Szegedy’s &lt;strong&gt;Batch Normalization&lt;/strong&gt; transformed deep learning overnight by standardizing each feature channel to zero mean and unit variance across the mini-batch—then letting two learnable parameters \((\gamma, \beta)\) restore any scale or shift the network actually needs. Later work (Santurkar et al., 2018) revealed an even deeper secret: BatchNorm works primarily because it dramatically smooths the loss surface’s Lipschitzness, letting SGD take bold, stable steps.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-exact-mechanics-of-batch-normalization&quot;&gt;Key ideas: The Exact Mechanics of Batch Normalization&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Per-Channel Standardization&lt;/strong&gt;: For a mini-batch of \(m\) activations \(\{x_1, \dots, x_m\}\) at one channel/feature, BatchNorm computes \(\mu_B = \frac{1}{m}\sum x_i\), \(\sigma_B^2 = \frac{1}{m}\sum (x_i - \mu_B)^2\), and normalizes \(\hat{x}_i = \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Learnable Affine Recovery (\(\gamma, \beta\))&lt;/strong&gt;: Pure standardization would restrict activations to mean 0 and variance 1 (e.g., trapping inputs inside the linear region of a sigmoid). Adding \(y_i = \gamma \hat{x}_i + \beta\) guarantees BatchNorm can even recover the exact identity function if \(\gamma = \sigma_B, \beta = \mu_B\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exponential Moving Average (EMA) for Inference&lt;/strong&gt;: At test time, predictions for a single image must be deterministic and independent of other images in the batch—so BatchNorm swaps \((\mu_B, \sigma_B^2)\) for running statistics updated during training via \(\mu_{\text{run}} \leftarrow (1 - \alpha)\mu_{\text{run}} + \alpha \mu_B\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scale Invariance of Weights&lt;/strong&gt;: Scaling the weights of the preceding linear/conv layer by any constant \(c &amp;gt; 0\) multiplies both \(x\) and \(\sigma_B\) by \(c\), which cancels out in \(\hat{x}\)—making effective step sizes self-stabilizing!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-hand-computing-a-complete-batchnorm-forward-pass&quot;&gt;Worked example: Hand-Computing a Complete BatchNorm Forward Pass&lt;/h3&gt;

&lt;p&gt;Suppose a single feature channel receives a mini-batch of \(m = 4\) values \(x = [2.0,\; 4.0,\; 6.0,\; 8.0]\), with learnable parameters \(\gamma = 1.5\), \(\beta = 0.5\), and \(\epsilon = 0\) (for clean exact arithmetic).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Batch mean \(\mu_B\)&lt;/strong&gt;:
\(\mu_B = \frac{2 + 4 + 6 + 8}{4} = \frac{20}{4} = 5.0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Batch variance \(\sigma_B^2\) and standard deviation \(\sigma_B\)&lt;/strong&gt;:
\(\sigma_B^2 = \frac{(2-5)^2 + (4-5)^2 + (6-5)^2 + (8-5)^2}{4} = \frac{9 + 1 + 1 + 9}{4} = \frac{20}{4} = 5.0 \implies \sigma_B = \sqrt{5} \approx 2.2361.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Standardize each sample \(\hat{x}_i = (x_i - 5.0) / 2.2361\)&lt;/strong&gt;:
\(\hat{x} \approx [-1.3416,\; -0.4472,\; +0.4472,\; +1.3416].\)
(Check: mean \(= 0.0\), variance \(= (1.8 + 0.2 + 0.2 + 1.8)/4 = 1.0\).)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply learnable affine transform \(y_i = 1.5 \hat{x}_i + 0.5\)&lt;/strong&gt;:
\(y \approx [-1.5124,\; -0.1708,\; +1.1708,\; +2.5124].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Update running mean&lt;/strong&gt; (starting from \(\mu_{\text{run}}^{(0)} = 0\) with PyTorch momentum \(\alpha = 0.1\)):
\(\mu_{\text{run}}^{(1)} = 0.9(0) + 0.1(5.0) = 0.5.\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;what-is-batch-normalization&quot;&gt;What is Batch Normalization?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Batch Normalization&lt;/strong&gt; (BatchNorm or BN), introduced by Ioffe and Szegedy (2015), normalizes the inputs of each layer to have zero mean and unit variance. It has become one of the most important techniques in modern deep learning.&lt;/p&gt;

&lt;h3 id=&quot;the-problem-internal-covariate-shift&quot;&gt;The Problem: Internal Covariate Shift&lt;/h3&gt;

&lt;p&gt;As network trains:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Distribution of layer inputs changes&lt;/li&gt;
  &lt;li&gt;Each layer must adapt to new input distribution&lt;/li&gt;
  &lt;li&gt;Slows down training significantly&lt;/li&gt;
  &lt;li&gt;Makes networks sensitive to initialization&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Batch Norm solution&lt;/strong&gt;: Normalize layer inputs to stable distribution.&lt;/p&gt;

&lt;h2 id=&quot;how-batch-normalization-works&quot;&gt;How Batch Normalization Works&lt;/h2&gt;

&lt;h3 id=&quot;forward-pass-training&quot;&gt;Forward Pass (Training)&lt;/h3&gt;

&lt;p&gt;For a mini-batch of activations \(\mathbf{x} = \{x_1, x_2, \ldots, x_m\}\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Compute batch statistics&lt;/strong&gt;&lt;/p&gt;

\[\mu_{\mathcal{B}} = \frac{1}{m} \sum_{i=1}^{m} x_i\]

\[\sigma^2_{\mathcal{B}} = \frac{1}{m} \sum_{i=1}^{m} (x_i - \mu_{\mathcal{B}})^2\]

&lt;p&gt;&lt;strong&gt;Step 2: Normalize&lt;/strong&gt;&lt;/p&gt;

\[\hat{x}_i = \frac{x_i - \mu_{\mathcal{B}}}{\sqrt{\sigma^2_{\mathcal{B}} + \epsilon}}\]

&lt;p&gt;where \(\epsilon\) (e.g., \(10^{-5}\)) prevents division by zero.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Scale and shift (learnable parameters)&lt;/strong&gt;&lt;/p&gt;

\[y_i = \gamma \hat{x}_i + \beta\]

&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\gamma\): scale parameter (learned)&lt;/li&gt;
  &lt;li&gt;\(\beta\): shift parameter (learned)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;inference-testing&quot;&gt;Inference (Testing)&lt;/h3&gt;

&lt;p&gt;Use population statistics (moving averages from training):&lt;/p&gt;

\[\hat{x} = \frac{x - \mu_{\text{pop}}}{\sqrt{\sigma^2_{\text{pop}} + \epsilon}}\]

\[y = \gamma \hat{x} + \beta\]

&lt;h2 id=&quot;implementation&quot;&gt;Implementation&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm1D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        num_features: number of features/channels
        eps: small constant for numerical stability
        momentum: for running mean/var updates
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Learnable parameters
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Running statistics (for inference)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Cache for backprop
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: input of shape (batch_size, num_features)
        training: whether in training mode
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Compute batch statistics
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;batch_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;batch_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Normalize
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Scale and shift
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Update running statistics
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
                               &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_mean&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
                              &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;momentum&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_var&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Cache for backward pass
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_var&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Use running statistics
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; \
                          &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;running_var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;beta&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Backpropagate through batch normalization
        dout: gradient from next layer
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;D&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradients of parameters
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dgamma&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_normalized&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dbeta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient of normalized x
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dx_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gamma&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient of variance
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dx_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; \
                     &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient of mean
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dmean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dx_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
                &lt;span class=&quot;n&quot;&gt;dvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient of x
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dx_normalized&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;eps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
             &lt;span class=&quot;n&quot;&gt;dvar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; \
             &lt;span class=&quot;n&quot;&gt;dmean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;N&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dx&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example usage
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BatchNorm1D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_features&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;out_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Train output mean: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Train output std: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Testing
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;out_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Test uses running statistics&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;why-batch-normalization-works&quot;&gt;Why Batch Normalization Works&lt;/h2&gt;

&lt;h3 id=&quot;1-reduces-internal-covariate-shift&quot;&gt;1. Reduces Internal Covariate Shift&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Stabilizes distribution of layer inputs&lt;/li&gt;
  &lt;li&gt;Each layer sees more consistent inputs&lt;/li&gt;
  &lt;li&gt;Easier to learn&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-allows-higher-learning-rates&quot;&gt;2. Allows Higher Learning Rates&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;More stable gradient flow&lt;/li&gt;
  &lt;li&gt;Can train 10-100x faster&lt;/li&gt;
  &lt;li&gt;Less sensitive to initialization&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-acts-as-regularization&quot;&gt;3. Acts as Regularization&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Adds noise to activations (from batch statistics)&lt;/li&gt;
  &lt;li&gt;Similar effect to dropout&lt;/li&gt;
  &lt;li&gt;Can reduce need for dropout&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-smooths-optimization-landscape&quot;&gt;4. Smooths Optimization Landscape&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Makes loss surface smoother&lt;/li&gt;
  &lt;li&gt;Gradients more predictable&lt;/li&gt;
  &lt;li&gt;Easier optimization&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=nUUqwaxLnWs&quot;&gt;Why Does Batch Norm Work? (C2W3L06)&lt;/a&gt; — DeepLearningAI, English. The mean-variance normalize-and-rescale formula.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=P6sfmUTpUmc&quot;&gt;Building makemore Part 3: Activations &amp;amp; Gradients, BatchNorm&lt;/a&gt; — Andrej Karpathy, English. Those statistics computed in code, so the per-channel reduction is visible.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 6&lt;/td&gt;
          &lt;td&gt;Training Neural Networks I](https://www.youtube.com/watch?v=wEoyxE0GP2M) — Stanford University School of Engineering, English. The original training-stabilization claim the mechanics are justifying.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-01 Dropout Regularization</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_01_Dropout/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_01_Dropout</id>
   <content type="html">&lt;p&gt;Why does intentionally sabotaging half of a neural network’s neurons on every training step often make the final network &lt;em&gt;more&lt;/em&gt; accurate on unseen data? Because forcing every neuron to survive random teammate outages prevents fragile memorization and turns a single set of weights into an implicit ensemble of sub-networks. This module hub links the probabilistic theory of Dropout with hands-on PyTorch and NumPy implementations, spatial dropout, and BatchNorm interaction pitfalls.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-navigating-dropout-regularization&quot;&gt;Key ideas: Navigating Dropout Regularization&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Theory &amp;amp; Implicit Ensembles&lt;/strong&gt;: Understanding co-adaptation, inverted dropout scaling (\(\frac{1}{1-p}\)), and the connection to adaptive L2 regularization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Code &amp;amp; Diagnostics&lt;/strong&gt;: Implementing inverted dropout forward/backward passes from scratch and mastering &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.train()&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Architecture-Specific Placement&lt;/strong&gt;: Choosing dropout rates across MLPs (\(0.2\text{–}0.5\)), CNNs (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Dropout2d&lt;/code&gt;), and Transformers (attention + residual dropout \(0.1\)).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-effective-ensemble-size--active-parameter-fraction&quot;&gt;Worked example: Effective Ensemble Size &amp;amp; Active Parameter Fraction&lt;/h3&gt;

&lt;p&gt;Consider a 2-hidden-layer MLP where each hidden layer has \(n = 10\) neurons and dropout rate \(p = 0.5\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Number of distinct sub-networks across both hidden layers&lt;/strong&gt;:
\(2^{10} \times 2^{10} = 2^{20} = 1{,}048{,}576 \text{ distinct thinned sub-networks!}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Expected fraction of weights active in the middle \(10 \times 10\) weight matrix on any single step&lt;/strong&gt;:
A weight \(W_{ij}\) is active only if &lt;em&gt;both&lt;/em&gt; input neuron \(j\) and output neuron \(i\) survive:
\((1 - p)(1 - p) = 0.5 \times 0.5 = 0.25 \quad (\text{only } 25\% \text{ of connections update together}).\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Dropout regularization:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Theory and Intuition&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implementation and Pitfalls&lt;/strong&gt; — code, papers, common mistakes, takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=D8PJAL-MZv8&quot;&gt;Dropout Regularization (C2W1L06)&lt;/a&gt; — DeepLearningAI, English. Dropout randomly masks units, which is this block’s method.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=6g0t3Phly2M&quot;&gt;Regularization (C2W1L04)&lt;/a&gt; — DeepLearningAI, English. Where dropout sits among other regularizers.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer, English. The variance it is trying to buy back.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-01-02 Dropout Implementation and Pitfalls</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_01_02_Dropout_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_01_02_Dropout_Implementation</id>
   <content type="html">&lt;p&gt;Dropout is one line of PyTorch (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Dropout(p=0.5)&lt;/code&gt;), yet it is responsible for some of the most baffling production bugs in deep learning. Forget to call &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; before validation, and your validation accuracy will randomly wobble—and often score &lt;em&gt;lower&lt;/em&gt; than training accuracy. Apply standard 1D dropout to 2D CNN feature maps instead of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Dropout2d&lt;/code&gt; (Spatial Dropout), and neighboring correlated pixels instantly leak the dropped activation’s information right around the hole! Mastering exact inverted-dropout code and placement rules prevents these silent traps.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-practical-dropout-engineering--pitfalls&quot;&gt;Key ideas: Practical Dropout Engineering &amp;amp; Pitfalls&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Inverted Dropout Backward Pass&lt;/strong&gt;: During backpropagation, the exact same binary mask \(m\) and scale \(\frac{1}{1-p}\) used in the forward pass multiply the upstream gradient: \(\frac{\partial \mathcal{L}}{\partial h} = \frac{\partial \mathcal{L}}{\partial \tilde{h}} \odot \frac{m}{1 - p}\). Dropped neurons receive strictly zero gradient.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; Contract&lt;/strong&gt;: Leaving a network in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train()&lt;/code&gt; mode during inference keeps random masking active—introducing stochastic predictions and artificially degrading test accuracy. (Exception: &lt;strong&gt;MC Dropout&lt;/strong&gt; intentionally keeps dropout on across \(K\) forward passes to estimate epistemic uncertainty!)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Spatial Dropout (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Dropout2d&lt;/code&gt;) for CNNs&lt;/strong&gt;: Because adjacent pixels in a feature map are strongly correlated, zeroing isolated pixels barely regularizes a CNN; dropping entire &lt;em&gt;channels&lt;/em&gt; forces true feature-level redundancy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dropout + BatchNorm Disharmony (Li et al., 2019)&lt;/strong&gt;: Placing Dropout immediately &lt;em&gt;before&lt;/em&gt; BatchNorm shifts feature variance between train mode (inflated by \(\frac{1}{1-p}\)) and eval mode (no noise), causing running-variance mismatch; place Dropout &lt;em&gt;after&lt;/em&gt; BatchNorm/activation or only on final dense heads.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-dropout-before-batchnorm-causes-variance-shift&quot;&gt;Worked example: Why Dropout Before BatchNorm Causes Variance Shift&lt;/h3&gt;

&lt;p&gt;Suppose an activation \(x\) has mean \(0\) and variance \(\sigma^2 = 1.0\) before a Dropout layer with \(p = 0.5\), followed immediately by BatchNorm.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;During training (inverted dropout active)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Expected mean: \(\mathbb{E}[\tilde{x}] = 0\).&lt;/li&gt;
      &lt;li&gt;Second moment / variance:
\(\operatorname{Var}(\tilde{x}) = \mathbb{E}[\tilde{x}^2] = (1 - p)\frac{\mathbb{E}[x^2]}{(1 - p)^2} = \frac{1}{1 - p}\sigma^2 = \frac{1}{0.5}(1.0) = 2.0!\)&lt;/li&gt;
      &lt;li&gt;BatchNorm’s running variance tracker converges to \(\sigma_{\text{running}}^2 \approx 2.0\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;During evaluation (dropout turned off)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;The true input variance entering BatchNorm drops abruptly back to \(\sigma^2 = 1.0\), yet BatchNorm divides by \(\sqrt{\sigma_{\text{running}}^2} = \sqrt{2.0} \approx 1.414\)—shrinking all test-time activations by \(29.3\%\)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Fix&lt;/strong&gt;: Place Dropout &lt;em&gt;after&lt;/em&gt; BatchNorm (or omit Dropout in Conv+BN stacks and rely on weight decay + data augmentation).&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;h3 id=&quot;pytorch-implementation&quot;&gt;PyTorch Implementation&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MLPWithDropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;MLPWithDropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Layer 1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropout1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Dropout after activation
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Layer 2
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropout2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Output layer (no dropout)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MLPWithDropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Enable dropout
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Batch of 32
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training output shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (32, 10)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Testing
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Disable dropout
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;output_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Test output shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (10, 10)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Check dropout effect
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Same input
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training (with dropout) - outputs vary:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;outputs_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Same input
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Testing (no dropout) - outputs identical:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;manual-dropout-implementation&quot;&gt;Manual Dropout Implementation&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DropoutManual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        X: (batch, features)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Generate mask: 1 with prob (1-p), 0 with prob p
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;keep_prob&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keep_prob&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Apply mask and scale
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keep_prob&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient only flows through kept neurons&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;keep_prob&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keep_prob&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DropoutManual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dropped units: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Testing  
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dropped units at test: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;spatial-dropout-for-cnns&quot;&gt;Spatial Dropout for CNNs&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SpatialDropout2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (batch, channels, height, width)
        Drop entire feature maps
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;training&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Mask shape: (batch, channels, 1, 1)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Same mask for all spatial positions in a channel
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bernoulli&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; 
                              &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;spatial_dropout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SpatialDropout2D&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Batch=2, 64 channels, 32×32
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;spatial_dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Entire channels dropped: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;h3 id=&quot;batch-normalization&quot;&gt;Batch Normalization&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Also provides regularization&lt;/li&gt;
  &lt;li&gt;Often reduces need for dropout&lt;/li&gt;
  &lt;li&gt;Modern architectures: BN instead of dropout in many cases&lt;/li&gt;
  &lt;li&gt;If using both: dropout after batch norm&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;data-augmentation&quot;&gt;Data Augmentation&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Another form of regularization&lt;/li&gt;
  &lt;li&gt;Adds noise/variation to training data&lt;/li&gt;
  &lt;li&gt;Complementary to dropout&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;early-stopping&quot;&gt;Early Stopping&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Stop training when validation loss increases&lt;/li&gt;
  &lt;li&gt;Prevents overfitting&lt;/li&gt;
  &lt;li&gt;Used together with dropout&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;ensemble-methods&quot;&gt;Ensemble Methods&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Train multiple independent models&lt;/li&gt;
  &lt;li&gt;Average predictions&lt;/li&gt;
  &lt;li&gt;Dropout approximates this with single model&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;dropconnect&quot;&gt;DropConnect&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Drop connections instead of neurons&lt;/li&gt;
  &lt;li&gt;Similar effect, different implementation&lt;/li&gt;
  &lt;li&gt;Less commonly used&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://jmlr.org/papers/v15/srivastava14a.html&quot;&gt;“Dropout: A Simple Way to Prevent Neural Networks from Overfitting” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Nitish Srivastava, Geoffrey Hinton, Alex Krizhevsky, Ilya Sutskever, Ruslan Salakhutdinov&lt;br /&gt;
&lt;strong&gt;THE foundational dropout paper&lt;/strong&gt;. Introduced dropout and provided theoretical analysis showing it prevents co-adaptation of neurons. Demonstrated dramatic improvements on multiple benchmarks including MNIST, CIFAR, and ImageNet. Became standard regularization technique in deep learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1207.0580&quot;&gt;“Improving neural networks by preventing co-adaptation of feature detectors” (2012)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Geoffrey E. Hinton, Nitish Srivastava, Alex Krizhevsky, et al.&lt;br /&gt;
Early dropout paper introducing the concept. Explained how dropout creates an ensemble of exponentially many thinned networks that share parameters. Showed empirical improvements and provided intuition for why random deactivation helps.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://proceedings.mlr.press/v28/wan13.html&quot;&gt;“Regularization of Neural Networks using DropConnect” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Li Wan, Matthew Zeiler, Sixin Zhang, Yann LeCun, Rob Fergus&lt;br /&gt;
Introduced DropConnect - dropping connections instead of neurons. Showed this variant can sometimes outperform dropout. Generalized the concept of random dropping beyond individual units.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1411.4280&quot;&gt;“Spatial Dropout” (2015) - part of “Efficient Object Localization Using CNNs”&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Jonathan Tompson, Ross Goroshin, Arjun Jain, Yann LeCun, Christoph Bregler&lt;br /&gt;
Introduced spatial dropout for convolutional layers - dropping entire feature maps instead of individual activations. Showed this is more effective for CNNs where nearby pixels are correlated.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.05287&quot;&gt;“A Theoretically Grounded Application of Dropout in RNNs” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Yarin Gal, Zoubin Ghahramani&lt;br /&gt;
Analyzed dropout in RNNs and introduced variational dropout - using same mask across time steps. Provided theoretical foundation connecting dropout to Bayesian inference, showing dropout approximates uncertainty estimation.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;h3 id=&quot;️-pitfall-1-forgetting-to-disable-during-testing&quot;&gt;⚠️ Pitfall 1: Forgetting to Disable During Testing&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Issue&lt;/strong&gt;: Dropout still active at test time → inconsistent predictions&lt;br /&gt;
&lt;strong&gt;Solution&lt;/strong&gt;: Always set model.eval()&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Wrong
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Dropout still active if model in train mode!
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Correct
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;️-pitfall-2-too-high-dropout-rate&quot;&gt;⚠️ Pitfall 2: Too High Dropout Rate&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Issue&lt;/strong&gt;: Network loses too much capacity&lt;br /&gt;
&lt;strong&gt;Solution&lt;/strong&gt;: Start with 0.5, reduce if performance drops&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Too aggressive - may hurt performance
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Dropping 90%!
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Better starting points
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# Fully connected
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Convolutional
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# Input layer
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;️-pitfall-3-using-with-batch-normalization&quot;&gt;⚠️ Pitfall 3: Using with Batch Normalization&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Issue&lt;/strong&gt;: Both provide regularization, can interact poorly&lt;br /&gt;
&lt;strong&gt;Solution&lt;/strong&gt;: Usually choose one or the other&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Modern practice: Use BN, skip dropout
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# No dropout needed!
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# If using both: dropout after BN
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;batch_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# After activation
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;-trick-1-different-rates-for-different-layers&quot;&gt;✅ Trick 1: Different Rates for Different Layers&lt;/h3&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SmartDropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Conservative
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Standard
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout_deep&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Lower for deep layers
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;-trick-2-monte-carlo-dropout-uncertainty-estimation&quot;&gt;✅ Trick 2: Monte Carlo Dropout (Uncertainty Estimation)&lt;/h3&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mc_dropout_predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Multiple stochastic forward passes for uncertainty
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Keep dropout ON
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mean_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;uncertainty&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;uncertainty&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Get prediction with uncertainty
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mc_dropout_predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Prediction: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Uncertainty: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;-trick-3-scheduled-dropout&quot;&gt;✅ Trick 3: Scheduled Dropout&lt;/h3&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ScheduledDropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradually increase dropout during training&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;final_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total_epochs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_rate&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;final_rate&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total_epochs&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;get_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;progress&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;progress&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Dropout&lt;/strong&gt; randomly deactivates neurons during training&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Rate&lt;/strong&gt;: 0.5 for FC layers, 0.1-0.3 for conv, 0.2 for input&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scaling&lt;/strong&gt;: Multiply by \(\frac{1}{1-p}\) during training&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Inference&lt;/strong&gt;: Use all neurons, no dropout&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Effect&lt;/strong&gt;: Ensemble learning, prevents co-adaptation&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Modern use&lt;/strong&gt;: Less common with batch normalization&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Key&lt;/strong&gt;: Remember train vs eval modes!&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Dropout remains one of the simplest yet most effective regularization techniques in deep learning!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Next&lt;/strong&gt;: Batch Normalization - another powerful technique that revolutionized training!&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=D8PJAL-MZv8&quot;&gt;Dropout Regularization (C2W1L06)&lt;/a&gt; — DeepLearningAI, English. Before writing the mask, including the inverted-dropout scaling.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 6&lt;/td&gt;
          &lt;td&gt;Training Neural Networks I](https://www.youtube.com/watch?v=wEoyxE0GP2M) — Stanford University School of Engineering, English. How a training loop applies that mask only in train mode.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=6g0t3Phly2M&quot;&gt;Regularization (C2W1L04)&lt;/a&gt; — DeepLearningAI, English. The pitfalls of leaving dropout on at evaluation, which this lesson warns about.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09-01-01 Dropout Theory and Intuition</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_01_01_Dropout_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_01_01_Dropout_Theory</id>
   <content type="html">&lt;p&gt;Imagine a large engineering team where one star developer secretly writes all the critical code while everyone else coasts—until that star goes on vacation and the entire system collapses. Neurons inside a dense hidden layer suffer from the exact same pathology, called &lt;strong&gt;co-adaptation&lt;/strong&gt;: one neuron learns to fix the mistakes of another rather than learning an independently useful feature. In 2012–2014, Hinton, Srivastava, and colleagues introduced &lt;strong&gt;Dropout&lt;/strong&gt;: on every training mini-batch, flip a biased coin for each neuron and temporarily switch off a fraction \(p\) of them. Suddenly no neuron can rely on any specific teammate being present—forcing redundant, resilient features and approximating an ensemble of \(2^n\) sub-networks in a single model.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-probability--ensemble-theory-of-dropout&quot;&gt;Key ideas: The Probability &amp;amp; Ensemble Theory of Dropout&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bernoulli Masking &amp;amp; Co-Adaptation Prevention&lt;/strong&gt;: Sampling \(m_i \sim \text{Bernoulli}(1 - p)\) independently per unit and multiplying \(\tilde{h} = m \odot h\) breaks brittle inter-neuron dependencies and forces every unit to contribute useful signal across diverse random contexts.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Inverted Dropout Scaling (\(\frac{1}{1 - p}\))&lt;/strong&gt;: Dropping a fraction \(p\) of neurons shrinks the expected sum flowing into the next layer by \((1 - p)\). Scaling surviving activations by \(\frac{1}{1 - p}\) &lt;em&gt;during training&lt;/em&gt; keeps \(\mathbb{E}[\tilde{h}] = h\), so &lt;strong&gt;inference requires zero rescaling&lt;/strong&gt; (just the identity map!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implicit Exponential Model Averaging&lt;/strong&gt;: A network with \(n\) droppable units contains \(2^n\) distinct thinned architectures sharing weights; evaluating the full network at test time approximates the geometric mean of their predictions at \(O(1)\) cost.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Variance Inflation Trade-off&lt;/strong&gt;: While inverted dropout preserves the &lt;em&gt;mean&lt;/em&gt; \(\mathbb{E}[\tilde{h}_i] = h_i\), it injects multiplicative variance \(\operatorname{Var}(\tilde{h}_i) = \frac{p}{1 - p} h_i^2\)—which acts like adaptive L2 regularization scaled by input feature magnitude!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-exact-mean--variance-of-inverted-dropout&quot;&gt;Worked example: Exact Mean &amp;amp; Variance of Inverted Dropout&lt;/h3&gt;

&lt;p&gt;Consider a 4-neuron hidden layer output \(h = [2.0,\; 4.0,\; 6.0,\; 8.0]\) with dropout rate \(p = 0.5\) (keep probability \(q = 1 - p = 0.5\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sample a Bernoulli keep mask&lt;/strong&gt; (say \(m = [1, 0, 1, 0]\)):
    &lt;ul&gt;
      &lt;li&gt;Unscaled masked activations: \(m \odot h = [2.0,\; 0.0,\; 6.0,\; 0.0]\) (sum drops from \(20.0\) to \(8.0\)!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply inverted dropout scaling (\(\frac{1}{1 - p} = \frac{1}{0.5} = 2.0\))&lt;/strong&gt;:
\(\tilde{h} = \frac{m \odot h}{1 - p} = [4.0,\; 0.0,\; 12.0,\; 0.0].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify exact expectation per neuron \(i\)&lt;/strong&gt;:
\(\mathbb{E}[\tilde{h}_i] = (1 - p)\left(\frac{h_i}{1 - p}\right) + p(0) = h_i.\)
For neuron 2 (\(h_2 = 6.0\)): \(\mathbb{E}[\tilde{h}_2] = 0.5(12.0) + 0.5(0) = 6.0\)—exact match to inference!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify injected noise variance on neuron 2&lt;/strong&gt;:
\(\operatorname{Var}(\tilde{h}_2) = \frac{p}{1 - p} h_2^2 = \frac{0.5}{0.5} (6.0)^2 = 36.0.\)
At &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt;, dropout turns off and passes \(h = [2.0, 4.0, 6.0, 8.0]\) unchanged with zero variance.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;dropout-preventing-overfitting-through-random-deactivation&quot;&gt;Dropout: Preventing Overfitting Through Random Deactivation&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/0/04/Dropout_Neural_Net_Model.svg/800px-Dropout_Neural_Net_Model.svg.png&quot; alt=&quot;Dropout Visualization&quot; /&gt;
&lt;em&gt;Hình ảnh: Minh họa kỹ thuật Dropout trong mạng neural. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Dropout&lt;/strong&gt; is a powerful regularization technique that randomly “drops out” (sets to zero) a fraction of neurons during training. This simple yet effective method prevents overfitting and has become one of the most widely used regularization techniques in deep learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Dropout matters&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Prevents co-adaptation&lt;/strong&gt;: Forces neurons to learn independently&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ensemble effect&lt;/strong&gt;: Like training many sub-networks simultaneously&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Simple to implement&lt;/strong&gt;: Just a few lines of code&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Effective&lt;/strong&gt;: Significantly improves generalization&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Key insight&lt;/strong&gt;: By randomly removing neurons during training, we prevent the network from relying too heavily on any single neuron, forcing it to learn robust, distributed representations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Analogy&lt;/strong&gt;: Like a team where members randomly don’t show up to practice. Each member must learn to perform well independently rather than relying on specific teammates, making the team more robust overall.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;h3 id=&quot;dropout-during-training&quot;&gt;Dropout During Training&lt;/h3&gt;

&lt;p&gt;For layer with activation \(\mathbf{a}\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Generate binary mask&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{m}_i \sim \text{Bernoulli}(1-p)\]

&lt;p&gt;where \(p\) is dropout rate (probability of dropping).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Apply mask and scale&lt;/strong&gt; (inverted dropout):&lt;/p&gt;

\[\mathbf{a}_{\text{dropout}} = \frac{\mathbf{m} \odot \mathbf{a}}{1-p}\]

&lt;p&gt;where \(\odot\) is element-wise multiplication.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why scale by \(\frac{1}{1-p}\)?&lt;/strong&gt; To maintain expected value:&lt;/p&gt;

\[\mathbb{E}[\mathbf{a}_{\text{dropout}}] = \mathbb{E}\left[\frac{\mathbf{m} \odot \mathbf{a}}{1-p}\right] = \mathbf{a}\]

&lt;h3 id=&quot;dropout-during-inference&quot;&gt;Dropout During Inference&lt;/h3&gt;

&lt;p&gt;At test time, use all neurons:&lt;/p&gt;

\[\mathbf{a}_{\text{test}} = \mathbf{a}\]

&lt;p&gt;No dropping, no scaling needed (due to scaling during training).&lt;/p&gt;

&lt;h3 id=&quot;mathematical-interpretation&quot;&gt;Mathematical Interpretation&lt;/h3&gt;

&lt;p&gt;Dropout approximates training an ensemble of \(2^n\) different networks (where \(n\) is number of neurons):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Each training step uses a different sub-network&lt;/li&gt;
  &lt;li&gt;Final network approximates averaging all sub-networks&lt;/li&gt;
  &lt;li&gt;Ensemble learning without training multiple models!&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;expected-behavior&quot;&gt;Expected Behavior&lt;/h3&gt;

&lt;p&gt;For dropout rate \(p\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Fraction of zeros during training: \(p\)&lt;/li&gt;
  &lt;li&gt;Remaining activations scaled by: \(\frac{1}{1-p}\)&lt;/li&gt;
  &lt;li&gt;Expected output: Same as without dropout&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;h3 id=&quot;concrete-example&quot;&gt;Concrete Example&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Network&lt;/strong&gt;: Hidden layer with 4 neurons&lt;br /&gt;
&lt;strong&gt;Dropout rate&lt;/strong&gt;: \(p = 0.5\) (50%)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Training iteration 1&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Activations: \([2.0, 3.5, 1.2, 4.1]\)&lt;/li&gt;
  &lt;li&gt;Random mask: \([0, 1, 1, 0]\)&lt;/li&gt;
  &lt;li&gt;After dropout: \([0, 7.0, 2.4, 0]\) (scaled by 2)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Training iteration 2&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Activations: \([2.0, 3.5, 1.2, 4.1]\)&lt;/li&gt;
  &lt;li&gt;Random mask: \([1, 0, 1, 1]\)&lt;/li&gt;
  &lt;li&gt;After dropout: \([4.0, 0, 2.4, 8.2]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Testing&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Activations: \([2.0, 3.5, 1.2, 4.1]\)&lt;/li&gt;
  &lt;li&gt;No mask: \([2.0, 3.5, 1.2, 4.1]\) (all neurons active)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;visual-intuition&quot;&gt;Visual Intuition&lt;/h3&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Training (dropout=0.5):
    Input → [X  ✓  ✓  X] → Output
            ↓  ↓  ↓  ↓
         (dropped) (scaled)

Testing (no dropout):
    Input → [✓  ✓  ✓  ✓] → Output
            ↓  ↓  ↓  ↓
           (all active)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;why-it-works-preventing-co-adaptation&quot;&gt;Why It Works: Preventing Co-Adaptation&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Without dropout&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Neuron A becomes expert at “eyes”&lt;/li&gt;
  &lt;li&gt;Neuron B always relies on Neuron A&lt;/li&gt;
  &lt;li&gt;If A makes mistake, B fails too&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;With dropout&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Sometimes A is dropped&lt;/li&gt;
  &lt;li&gt;B must learn to work without A&lt;/li&gt;
  &lt;li&gt;Both learn robust, independent features&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=D8PJAL-MZv8&quot;&gt;Dropout Regularization (C2W1L06)&lt;/a&gt; — DeepLearningAI, English. The train-time mask and the test-time scale, which is the theory.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer, English. Why a noisier estimator can generalize, the intuition the formula is serving.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=6g0t3Phly2M&quot;&gt;Regularization (C2W1L04)&lt;/a&gt; — DeepLearningAI, English. The surrounding regularization argument if dropout feels like an isolated trick.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>09 Regularization Techniques</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter09/09_00_Introduction</id>
   <content type="html">&lt;p&gt;Modern deep neural networks routinely contain millions or billions of parameters—more than enough capacity to memorize the entire training set down to random label noise and still score poorly on unseen test data. Watching training loss plunge to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.01&lt;/code&gt; while validation loss climbs steadily upward is every practitioner’s first encounter with &lt;strong&gt;overfitting&lt;/strong&gt;. Regularization and normalization techniques—from &lt;strong&gt;Dropout&lt;/strong&gt; and &lt;strong&gt;weight decay&lt;/strong&gt; to &lt;strong&gt;Batch Normalization&lt;/strong&gt; and &lt;strong&gt;LayerNorm&lt;/strong&gt;—do not shrink a model’s expressive power; they sculpt its optimization landscape and inject controlled noise so the network learns robust, generalizable representations instead of fragile memorization shortcuts.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-foundations-of-regularization--normalization&quot;&gt;Key ideas: Foundations of Regularization &amp;amp; Normalization&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bias–Variance Trade-off in Over-Parameterized Regimes&lt;/strong&gt;: Regularizers constrain effective capacity or flatten loss minima so small perturbations in input data or weights produce small changes in predictions, shrinking the generalization gap \((\mathcal{L}_{\text{val}} - \mathcal{L}_{\text{train}})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stochastic Structural Regularization (Dropout)&lt;/strong&gt;: Randomly zeroing activations during training prevents neurons from forming fragile co-adaptations and implicitly trains an exponential ensemble of thinned sub-networks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Activation Normalization (BatchNorm, LayerNorm, GroupNorm)&lt;/strong&gt;: Standardizing layer activations stabilizes gradient scales across depth, smooths the loss landscape, and allows dramatically higher learning rates.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Train-Time vs. Inference-Time Consistency&lt;/strong&gt;: Both Dropout and BatchNorm behave &lt;em&gt;differently&lt;/em&gt; during training and evaluation—making &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.train()&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; switches critical for reproducible accuracy.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-quantifying-the-generalization-gap--l2-weight-decay-penalty&quot;&gt;Worked example: Quantifying the Generalization Gap &amp;amp; L2 Weight Decay Penalty&lt;/h3&gt;

&lt;p&gt;Suppose a linear layer has weights \(w = [2.0, -1.0, 0.5]\), unregularized training loss \(\mathcal{L}_{\text{data}} = 0.40\), and weight-decay coefficient \(\lambda = 0.1\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the L2 regularization penalty&lt;/strong&gt;:
\(\frac{\lambda}{2} \|w\|_2^2 = \frac{0.1}{2} \left(2.0^2 + (-1.0)^2 + 0.5^2\right) = 0.05 \times (4.0 + 1.0 + 0.25) = 0.05 \times 5.25 = 0.2625.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Total regularized objective&lt;/strong&gt;:
\(\mathcal{L}_{\text{total}} = 0.40 + 0.2625 = 0.6625.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient pull toward zero&lt;/strong&gt;:
\(\nabla_w \left(\frac{\lambda}{2} \|w\|_2^2\right) = \lambda w = [0.20,\; -0.10,\; 0.05].\)
With learning rate \(\eta = 0.1\), every step shrinks each weight multiplicatively by \((1 - \eta \lambda) = 0.99\) before applying the data gradient—preferring smaller, smoother weights distributed across many features.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Regularization prevents overfitting by constraining model complexity. This chapter covers essential techniques: L1/L2 regularization, dropout, batch normalization, data augmentation, and early stopping. These methods are crucial for building models that generalize well to unseen data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After dropout and BatchNorm, see &lt;strong&gt;09-99 Modern Applications and Updates&lt;/strong&gt; for SAM, DropPath, and how foundation-model recipes regularize today.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (interview practice):&lt;/strong&gt; After the regularizer notes, see &lt;strong&gt;09-98 Interviews Practice&lt;/strong&gt; for original overfitting / dropout / BN prompts; open &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for the solved bank.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=DEMmkFC6IGM&quot;&gt;Overfitting in a Neural Network explained&lt;/a&gt; — deeplizard, English. Overfitting is the failure this chapter exists to reduce.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EuBBz3bI-aA&quot;&gt;Machine Learning Fundamentals: Bias and Variance&lt;/a&gt; — StatQuest with Josh Starmer, English. Bias and variance name that failure in the way the lessons will.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=6g0t3Phly2M&quot;&gt;Regularization (C2W1L04)&lt;/a&gt; — DeepLearningAI, English. The regularization menu (weight decay and friends) the chapter then specializes.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Open the source code of Llama 3, Qwen 2.5, Mistral, or Gemma and compare it line-by-line against the 2017 &lt;em&gt;Attention Is All You Need&lt;/em&gt; diagram: the macro skeleton is unmistakably the same decoder-only Transformer, yet &lt;strong&gt;five targeted micro-upgrades&lt;/strong&gt; replaced almost every original sub-layer. Pre-RMSNorm replaced Post-LayerNorm, Rotary Positional Embeddings (RoPE) replaced additive sinusoids, SwiGLU replaced ReLU FFNs, and Grouped-Query Attention (GQA) replaced standard MHA—together enabling stable 70B–600B+ parameter scaling and 128K+ context windows.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-five-modern-upgrades-inside-frontier-llm-blocks&quot;&gt;Key ideas: Five Modern Upgrades Inside Frontier LLM Blocks&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pre-RMSNorm&lt;/strong&gt;: Dropping mean-centering from LayerNorm leaves \(\text{RMSNorm}(x) = \frac{x}{\sqrt{\frac{1}{d}\sum x_i^2 + \epsilon}} \odot g\)—matching LayerNorm’s training stability while cutting normalization overhead by ~\(10\text{–}40\%\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Rotary Positional Embeddings (RoPE)&lt;/strong&gt;: Instead of adding position vectors to embeddings, RoPE rotates each 2D pair of \(q_m, k_n\) by angles \(m\theta_i\) and \(n\theta_i\), so their dot product \(q_m^\top k_n\) depends &lt;em&gt;purely&lt;/em&gt; on the relative distance \((m - n)\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SwiGLU Gated Feed-Forward Layers&lt;/strong&gt;: Replacing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;W2(ReLU(W1 x))&lt;/code&gt; with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;W_down(SiLU(W_gate x) * (W_up x))&lt;/code&gt; adds multiplicative gating; to keep parameter counts equal to a \(4d\) ReLU FFN, intermediate width is scaled to \(\approx \frac{8}{3} d_{\text{model}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multimodal &amp;amp; Local Serving Ecosystem&lt;/strong&gt;: The exact same Transformer backbone now fuses ViT image patches, audio tokens, and text tokens inside unified models served locally via quantized GGUF/llama.cpp or at scale via vLLM/SGLang.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-swiglu-uses-hidden-width-frac83-d-instead-of-4-d&quot;&gt;Worked example: Why SwiGLU Uses Hidden Width \(\frac{8}{3} d\) Instead of \(4 d\)&lt;/h3&gt;

&lt;p&gt;A standard Transformer FFN has &lt;strong&gt;2&lt;/strong&gt; matrices (\(W_1, W_2\)) with hidden width \(d_{\text{ff}} = 4 d\), giving parameter count:
\(P_{\text{ReLU-FFN}} = 2 \cdot d \cdot (4 d) = 8 d^2.\)
A SwiGLU FFN has &lt;strong&gt;3&lt;/strong&gt; matrices (\(W_{\text{gate}}, W_{\text{up}}, W_{\text{down}}\)) with hidden width \(d_{\text{swiglu}}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Equate parameter budgets&lt;/strong&gt;:
\(3 \cdot d \cdot d_{\text{swiglu}} = 8 d^2 \implies d_{\text{swiglu}} = \frac{8}{3} d \approx 2.667\, d.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Concrete Llama-style example (\(d = 4{,}096\))&lt;/strong&gt;:
\(\frac{8}{3} \times 4{,}096 = 10{,}922.67 \xrightarrow{\text{round to multiple of 256}} 11{,}008.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check RoPE relative-distance property in 2D&lt;/strong&gt;:
If \(R(\theta)\) is a \(2 \times 2\) rotation matrix, then \(R(m\theta)^\top R(n\theta) = R((n - m)\theta)\). Thus \((R(m\theta) q)^\top (R(n\theta) k) = q^\top R((n - m)\theta) k\)—exact relative position invariance with zero extra parameters!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-transformer-stacks-that-became-llms&quot;&gt;Optional: Transformer stacks that became LLMs&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; rewrite encoder/decoder theory or positional encodings. It maps the 2017 block onto the 2022–2026 LLM stack: RoPE, KV-cache, open weights, and serving.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A Transformer layer is still “communicate (attention) then compute (MLP).” After ChatGPT (late 2022), that block is the &lt;strong&gt;default computer&lt;/strong&gt; for language, code, and many multimodal systems.&lt;/p&gt;

&lt;h2 id=&quot;1-what-actually-changed-in-the-block&quot;&gt;1. What actually changed in the block&lt;/h2&gt;

&lt;p&gt;Most decoder-only LMs (GPT-2 lineage → Llama / Mistral / Qwen / Gemma) use:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;RoPE&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2104.09864&quot;&gt;Su et al., 2021/2023&lt;/a&gt;) instead of absolute sin–cos added to embeddings,&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;pre-norm + RMSNorm + SwiGLU&lt;/strong&gt; (Chapter 02 optional),&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GQA&lt;/strong&gt; and FlashAttention (Chapter 07 optional),&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;KV-cache&lt;/strong&gt; at decode time: keys/values for tokens \(1..t-1\) are reused so each new token costs \(O(t)\), not \(O(t^2)\) matmuls from scratch.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;RoPE rotates pairs of dimensions by an angle \(\theta_i t\):&lt;/p&gt;

\[\begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}
\leftarrow
\begin{pmatrix} \cos(t\theta_i) &amp;amp; -\sin(t\theta_i) \\ \sin(t\theta_i) &amp;amp; \cos(t\theta_i) \end{pmatrix}
\begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}.\]

&lt;p&gt;The theory lesson’s sin–cos PE is still the right first model; RoPE is the one you will see in 2025 checkpoints.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;open-foundation-lms&quot;&gt;Open foundation LMs&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2302.13971&quot;&gt;LLaMA&lt;/a&gt;, &lt;a href=&quot;https://arxiv.org/abs/2307.09288&quot;&gt;Llama 2&lt;/a&gt;, Llama 3, &lt;a href=&quot;https://arxiv.org/abs/2310.06825&quot;&gt;Mistral 7B&lt;/a&gt;, Qwen2, and Gemma 2 are the reference decoder stacks. Instruction-tuned variants are the ones products call.&lt;/p&gt;

&lt;h3 id=&quot;serving-and-local-inference&quot;&gt;Serving and local inference&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt; — continuous batching + PagedAttention.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;llama.cpp&lt;/a&gt; — GGUF quantized inference on CPUs and Apple Silicon.&lt;/li&gt;
  &lt;li&gt;Speculative decoding (&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Leviathan et al., 2023&lt;/a&gt;) — a small draft model proposes tokens; the large model verifies in parallel.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;multimodal-transformers&quot;&gt;Multimodal Transformers&lt;/h3&gt;

&lt;p&gt;ViT (&lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;Dosovitskiy et al., 2021&lt;/a&gt;) plus a language decoder (LLaVA, 2023; later GPT-4V-class systems) reuse the same block on image patches. Architecture homework stays in this chapter; vision-language products are the application.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/transformers&quot;&gt;Hugging Face transformers&lt;/a&gt; — model definitions and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;generate()&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt; and &lt;a href=&quot;https://github.com/sgl-project/sglang&quot;&gt;SGLang&lt;/a&gt; — high-throughput serving.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;llama.cpp&lt;/a&gt; — local GGUF.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2302.13971&quot;&gt;LLaMA (Touvron et al., 2023)&lt;/a&gt; and &lt;a href=&quot;https://arxiv.org/abs/2307.09288&quot;&gt;Llama 2 (2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2310.06825&quot;&gt;Mistral 7B (Jiang et al., 2023)&lt;/a&gt; — sliding-window + GQA.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2104.09864&quot;&gt;RoFormer / RoPE (Su et al., 2023 journal version)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2211.17192&quot;&gt;Fast Inference from Transformers via Speculative Decoding (Leviathan et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Complete the encoder–decoder derivation and the toy PyTorch Transformer first. This lesson only names the &lt;strong&gt;LLM product stack&lt;/strong&gt; built on that derivation. Formulas and Mermaid for RMSNorm → attention + RoPE → SwiGLU, plus parameter / FLOP accounting, live in &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. The baseline block this note says has since changed in detail but not in outline.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How might LLMs store facts&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 7](https://www.youtube.com/watch?v=9-Jl0dxWQs8) — 3Blue1Brown, English. The MLP-as-memory view of what a modern decoder block still computes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=gBMO1JZav44&quot;&gt;How FlashAttention Accelerates Generative AI Revolution&lt;/a&gt; — Jia-Bin Huang, English. The attention implementation change (FlashAttention) the note treats as a systems upgrade, not a new formula.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-02 Transformer Explainer</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_02_Transformer_Explainer/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_02_Transformer_Explainer</id>
   <content type="html">&lt;p&gt;Even after deriving every matrix equation of a Transformer, it is surprisingly hard to &lt;em&gt;feel&lt;/em&gt; what happens to a single prompt—like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;Data visualization empowers users to&quot;&lt;/code&gt;—as it flows through tokenization, embeddings, 12 layers of multi-head self-attention and MLP expansions, and finally into a probability distribution over 50,257 GPT-2 vocabulary tokens. Interactive visualizers like Polo Club’s &lt;em&gt;Transformer Explainer&lt;/em&gt; turn those abstract tensors into a live glass box where you can watch temperature, top-\(k\), and top-\(p\) reshape the next word in real time.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-tracing-one-live-token-through-gpt-2&quot;&gt;Key ideas: Tracing One Live Token Through GPT-2&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Subword Tokenization (BPE) &amp;amp; Embedding Lookup&lt;/strong&gt;: Byte-Pair Encoding splits text into frequent subword chunks (avoiding out-of-vocabulary failures), mapping each integer token ID \(t_i \in \{0, \dots, 50256\}\) to a 768-dimensional vector plus a learned positional vector.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multi-Head Self-Attention Flow&lt;/strong&gt;: In GPT-2 Small (12 layers, 12 heads, \(d_{\text{model}} = 768, d_k = 64\)), each token’s residual vector is projected into 12 parallel &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(Q, K, V)&lt;/code&gt; subspaces, mixed causally, and added back to the residual stream.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;MLP Expansion &amp;amp; GELU Non-Linearity&lt;/strong&gt;: Each token independently expands \(768 \to 3{,}072 \to 768\) through a smooth GELU activation, acting like a key-value associative memory bank that refines semantic predictions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Unembedding &amp;amp; Sampling Controls (Temperature, Top-\(k\), Top-\(p\))&lt;/strong&gt;: Multiplying the final hidden state by \(W_{\text{emb}}^\top\) produces 50,257 logits; temperature rescales sharpness, top-\(k\) truncates to the \(k\) highest-scoring tokens, and top-\(p\) (nucleus sampling) truncates to the smallest token set whose cumulative probability exceeds \(p\).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-top-k-vs-top-p-nucleus-truncation-on-5-candidate-tokens&quot;&gt;Worked example: Top-\(k\) vs. Top-\(p\) (Nucleus) Truncation on 5 Candidate Tokens&lt;/h3&gt;

&lt;p&gt;Suppose GPT-2’s softmax over the top 5 next-token candidates yields:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;understand&quot;&lt;/code&gt;: \(0.45\)&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;explore&quot;&lt;/code&gt;: \(0.30\)&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;see&quot;&lt;/code&gt;: \(0.15\)&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;analyze&quot;&lt;/code&gt;: \(0.07\)&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;paint&quot;&lt;/code&gt;: \(0.03\) (sum \(= 1.00\))&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Apply Top-\(k\) with \(k = 2\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Keep only &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;understand&quot;&lt;/code&gt; (\(0.45\)) and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;explore&quot;&lt;/code&gt; (\(0.30\)); total kept mass \(= 0.75\).&lt;/li&gt;
      &lt;li&gt;Renormalize: \(p(\text{&quot;understand&quot;}) = 0.45 / 0.75 = 0.60\), \(p(\text{&quot;explore&quot;}) = 0.30 / 0.75 = 0.40\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply Top-\(p\) (Nucleus) with \(p = 0.85\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Cumulative sums: \(0.45\) (1 token), \(0.45 + 0.30 = 0.75\) (2 tokens, still \(&amp;lt; 0.85\)), \(0.75 + 0.15 = 0.90\) (3 tokens, crosses \(0.85\)!).&lt;/li&gt;
      &lt;li&gt;Keep the top 3 tokens (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;understand&quot;&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;explore&quot;&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;see&quot;&lt;/code&gt;); total kept mass \(= 0.90\).&lt;/li&gt;
      &lt;li&gt;Renormalize: \(0.45/0.90 = 0.500\), \(0.30/0.90 = 0.333\), \(0.15/0.90 = 0.167\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why practitioners prefer Top-\(p\)&lt;/strong&gt;: When the model is very confident (e.g., top token \(= 0.92\)), Top-\(p\) dynamically shrinks to 1 token; when uncertain, it expands smoothly to include plausible continuations!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;transformer-explainer&quot;&gt;Transformer Explainer&lt;/h1&gt;

&lt;p&gt;The equations in this chapter tell you &lt;em&gt;what&lt;/em&gt; a Transformer computes. &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; lets you &lt;em&gt;watch&lt;/em&gt; those computations on a real language model, with no installation and no GPU. It runs a live &lt;strong&gt;GPT-2 (small)&lt;/strong&gt; model (124 million parameters, 12 stacked Transformer blocks) directly in the browser, so every number you see is the actual forward pass for the prompt you type.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_summary.png&quot; alt=&quot;Transformer Explainer overview&quot; /&gt;
&lt;em&gt;Overview of the interactive interface: a prompt is tokenized, then flows through embedding, multi-head self-attention, and the MLP. Source: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (MIT License).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Open the tool first, then use this lesson as a guided map:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Live demo:&lt;/strong&gt; &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;poloclub.github.io/transformer-explainer&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Source code:&lt;/strong&gt; &lt;a href=&quot;https://github.com/poloclub/transformer-explainer&quot;&gt;github.com/poloclub/transformer-explainer&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Paper (CHI 2026):&lt;/strong&gt; &lt;a href=&quot;https://doi.org/10.1145/3772318.3791725&quot;&gt;Cho et al., “Transformer Explainer…”&lt;/a&gt; (&lt;a href=&quot;https://poloclub.github.io/papers/26-chi-transformer-explainer.pdf&quot;&gt;PDF&lt;/a&gt;, &lt;a href=&quot;https://arxiv.org/abs/2408.04619&quot;&gt;arXiv:2408.04619&lt;/a&gt;)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Demo video:&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=TFUc41G2ikY&quot;&gt;YouTube&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The site is built for full-page exploration (hovering on attention weights, expanding layers, moving sliders). This course therefore links out to the live demo rather than embedding it in a small frame.&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;GPT-2 is a &lt;strong&gt;decoder-only&lt;/strong&gt; Transformer: it predicts the next token given all tokens to its left. That is a slightly narrower architecture than the encoder–decoder map in “Attention Is All You Need,” which also has encoder self-attention and encoder–decoder cross-attention. The pieces you already studied still appear, just arranged for causal language modeling:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Embedding&lt;/strong&gt; — tokens become vectors, plus a positional signal.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Transformer blocks&lt;/strong&gt; — each block is multi-head &lt;strong&gt;self-attention&lt;/strong&gt; (communicate across positions) followed by an &lt;strong&gt;MLP&lt;/strong&gt; (compute per position), with residual connections.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Output probabilities&lt;/strong&gt; — a linear head plus softmax turns the last hidden state into a distribution over the vocabulary, from which the next token is sampled.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;GPT-2 (small) uses a 50,257-token vocabulary and 768-dimensional embeddings. The 12 blocks are identical in structure; the visualization typically expands &lt;strong&gt;Block 1&lt;/strong&gt; and notes that eleven more follow. The in-browser model is adapted from Andrej Karpathy’s nanoGPT and executed with ONNX Runtime, so the values update live as you edit the prompt or the sampling controls.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_teaser.jpg&quot; alt=&quot;Annotated teaser of the full interface&quot; /&gt;
&lt;em&gt;Official teaser of the full interface (resized for the course site). (A) type a prompt and generate the next token; (B) change temperature and sampling; (C) expand the attention computation (dot product, scaling and causal mask, softmax). Source: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (MIT License).&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;2-what-each-part-of-the-visualization-shows&quot;&gt;2. What each part of the visualization shows&lt;/h2&gt;

&lt;h3 id=&quot;embedding-tokenization-and-positional-encoding&quot;&gt;Embedding, tokenization, and positional encoding&lt;/h3&gt;

&lt;p&gt;Expand the &lt;strong&gt;Embedding&lt;/strong&gt; column. The prompt is first &lt;strong&gt;tokenized&lt;/strong&gt;. GPT-2 uses a subword vocabulary: whole words such as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Data&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;visualization&lt;/code&gt; may be a single token, while &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;empowers&lt;/code&gt; is split into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;em&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;powers&lt;/code&gt;. Each token has an integer id and a learned 768-dimensional &lt;strong&gt;token embedding&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_embedding.png&quot; alt=&quot;Embedding: tokens, token embeddings, and positional encodings&quot; /&gt;
&lt;em&gt;Four steps of embedding for the prompt “Data visualization empowers users to”: (1) tokens, (2) token embeddings with vocabulary ids, (3) positional encodings, (4) the final sum. Source: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (MIT License).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Positional encoding is added, not concatenated.&lt;/strong&gt; GPT-2 does &lt;em&gt;not&lt;/em&gt; use the fixed sine/cosine table from the original Transformer paper; it learns a positional embedding matrix during training and adds it to the token embedding. The teaching point is the same as in the theory lesson: self-attention has no built-in order, so position must be injected somehow. After the sum, each row is a vector that carries both “what this token is” and “where it sits in the prompt.”&lt;/p&gt;

&lt;h3 id=&quot;query-key-value-and-multi-head-self-attention&quot;&gt;Query, key, value, and multi-head self-attention&lt;/h3&gt;

&lt;p&gt;From those embeddings the model builds &lt;strong&gt;query (Q)&lt;/strong&gt;, &lt;strong&gt;key (K)&lt;/strong&gt;, and &lt;strong&gt;value (V)&lt;/strong&gt; vectors. In GPT-2 (small) this is one matrix multiply: a \((6, 768)\) embedding matrix times a learned \((768, 2304)\) weight matrix, plus a bias, produces a \((6, 2304)\) tensor. The 2304 columns are simply \(3 \times 768\) — Q, K, and V concatenated — which are then split across &lt;strong&gt;12 attention heads&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_qkv.png&quot; alt=&quot;Computing Q, K, and V from embeddings&quot; /&gt;
&lt;em&gt;Embeddings multiplied by the combined QKV weight matrix (plus bias) yield concatenated Q, K, and V. Source: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (MIT License).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A useful analogy, also used by the tool: the &lt;strong&gt;query&lt;/strong&gt; is the search you type, the &lt;strong&gt;keys&lt;/strong&gt; are the titles you might match, and the &lt;strong&gt;values&lt;/strong&gt; are the page contents you actually read. Attention is a soft lookup: each token asks “which earlier tokens are relevant to me?” and mixes their values accordingly.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_attention.png&quot; alt=&quot;Scaled dot-product attention with a causal mask&quot; /&gt;
&lt;em&gt;One attention head: Q–K dot products, scaling and causal mask, then softmax (and dropout during training). The lower-triangular structure is the decoder rule: a token must not attend to the future. Source: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (MIT License).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Walk the three matrices from left to right:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Dot product&lt;/strong&gt; \(QK^{\top}\) measures raw similarity between every query and every key.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scaling and mask&lt;/strong&gt; divides by \(\sqrt{d_k}\) (the same \(1/\sqrt{d_k}\) factor from Chapter 07) and applies a &lt;strong&gt;causal mask&lt;/strong&gt;, setting future positions to \(-\infty\) so they cannot be attended to when predicting the next token.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Softmax&lt;/strong&gt; turns each row into a probability distribution over allowed positions. Those weights multiply \(V\) to produce the head output.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You can switch heads (1 of 12) and hover on tokens to see which positions a given token attends to. Different heads often specialize: some pick up local syntax, others longer semantic links. The head outputs are concatenated and projected before the residual stream continues.&lt;/p&gt;

&lt;h3 id=&quot;mlp&quot;&gt;MLP&lt;/h3&gt;

&lt;p&gt;After attention has &lt;em&gt;routed&lt;/em&gt; information between tokens, the &lt;strong&gt;MLP&lt;/strong&gt; (a two-layer feed-forward network) &lt;em&gt;refines&lt;/em&gt; each token on its own. In GPT-2 (small) the hidden width expands from 768 to \(4 \times 768 = 3072\) with a GELU activation, then projects back to 768. Residual connections sit around the block so the original representation can pass through.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_mlp.png&quot; alt=&quot;MLP expansion to 3072 dimensions with residual path&quot; /&gt;
&lt;em&gt;The position-wise MLP expands each token to a 3072-dimensional hidden vector, then writes back into the residual stream. Source: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (MIT License).&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;output-probabilities-temperature-and-sampling&quot;&gt;Output probabilities, temperature, and sampling&lt;/h3&gt;

&lt;p&gt;After all 12 blocks, a linear layer maps the last position to &lt;strong&gt;logits&lt;/strong&gt; — one score per vocabulary item. Softmax converts logits into a probability distribution over the next token.&lt;/p&gt;

&lt;p&gt;Temperature is a surprisingly small operation with a large effect: the logits are divided by \(T\) &lt;em&gt;before&lt;/em&gt; softmax.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(T = 1\): the distribution is unchanged.&lt;/li&gt;
  &lt;li&gt;\(T &amp;lt; 1\): the distribution sharpens; the model looks more confident and deterministic.&lt;/li&gt;
  &lt;li&gt;\(T &amp;gt; 1\): the distribution flattens; lower-ranked tokens become more likely, which people often describe as more “creative” (and more error-prone).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Two common filters then restrict what may be sampled:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Top-k:&lt;/strong&gt; keep only the \(k\) tokens with the highest probability; the rest are set to \(-\infty\) and receive probability 0.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Top-p&lt;/strong&gt; (nucleus sampling): keep the smallest set of tokens whose cumulative probability exceeds a threshold \(p\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_explainer_softmax.png&quot; alt=&quot;Temperature, top-k sampling, and next-token probabilities&quot; /&gt;
&lt;em&gt;With temperature 0.8 and top-k = 5, logits are scaled, tokens outside the top five are zeroed out, and softmax yields the next-token distribution. Here “visualize” leads at 54.67% for the prompt “…users to”. Source: Polo Club of Data Science, Georgia Tech, &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;Transformer Explainer&lt;/a&gt; (MIT License).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In the figure, a temperature of 0.8 turns a logit of \(-135.91\) into a scaled value of \(-169.89\) (exactly \(-135.91 / 0.8\)). After top-k, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;quickly&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;explore&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;find&lt;/code&gt; are no longer candidates. Sampling is not the same as always taking \(\arg\max\): even at this setting, “create” still has about 21% probability.&lt;/p&gt;

&lt;h2 id=&quot;3-guided-exercise&quot;&gt;3. Guided exercise&lt;/h2&gt;

&lt;p&gt;Open the &lt;a href=&quot;https://poloclub.github.io/transformer-explainer/&quot;&gt;live demo&lt;/a&gt; and work through the following, writing short answers as you go. The default prompt “Data visualization empowers users to” is a good starting point.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Read the tokenization.&lt;/strong&gt; Expand Embedding. Which words stay as one token, and which word is split? Why might a subword vocabulary do that?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Confirm the positional sum.&lt;/strong&gt; Check that each final embedding is the token embedding plus a position vector (0, 1, 2, …). What would go wrong if this addition were skipped? (The ablation in &lt;strong&gt;08-01-02-02&lt;/strong&gt; is the coding counterpart of this question.)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Inspect one attention head.&lt;/strong&gt; Open a head in Block 1, hover over the last token, and note which earlier tokens receive the largest weights. Switch to another head. Do the two heads agree?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Find the causal mask.&lt;/strong&gt; In the “Scaling · Mask” matrix, identify the positions that are blocked. Why must a decoder-only model hide the future even during a visualization of a &lt;em&gt;prompt&lt;/em&gt; that you already typed?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sweep temperature.&lt;/strong&gt; Set temperature near 0.1, then near 1.5, without changing the prompt. Describe how the probability bar chart changes. Which setting would you use if you needed a reliable completion versus a more diverse one?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare top-k and top-p.&lt;/strong&gt; With temperature fixed (try 0.8), set top-k to 1, then to 5, then switch to top-p. What happens to tokens that fall outside the cutoff? How is that visible in the Softmax column?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use your own sentence.&lt;/strong&gt; Type a short English prompt (or a mix of English and Vietnamese) and press Generate. Does the next-token list match your expectation? If not, remember that this is GPT-2 small, not a modern instruction-tuned LLM — the architecture is the same family, the capacity is not.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-related-concepts&quot;&gt;4. Related Concepts&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Chapter 07&lt;/strong&gt; — scaled dot-product attention, multi-head attention, and causal masks are exactly the matrices the explainer draws.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;08-01-01 Transformer Theory&lt;/strong&gt; — positional encodings and the full block (attention + FFN + residual + norm). Note the GPT-2 detail: learned absolute PE rather than sine/cosine PE.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;08-01-02-02 Demos, papers, and pitfalls&lt;/strong&gt; — a tiny model you train yourself; use the explainer when you want a &lt;em&gt;pretrained&lt;/em&gt; GPT-2 you can inspect without writing a training loop.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chapter 26&lt;/strong&gt; — tokenization, decoding, and sampling at LLM scale; this lesson is the visual preview of those decoding choices.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-fundamental-papers&quot;&gt;5. Fundamental Papers&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://doi.org/10.1145/3772318.3791725&quot;&gt;Transformer Explainer (Cho et al., CHI 2026)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
The interactive system this lesson is built around: a live in-browser GPT-2 with an overview of data flow and on-demand views of embedding, attention, and next-token probabilities. Also on &lt;a href=&quot;https://arxiv.org/abs/2408.04619&quot;&gt;arXiv:2408.04619&lt;/a&gt;.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf&quot;&gt;Language Models are Unsupervised Multitask Learners (GPT-2, Radford et al., 2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
The decoder-only model family running inside the visualization.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need (Vaswani et al., 2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
The original encoder–decoder Transformer; compare it with the decoder-only stack you see in the explainer.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;6-key-takeaways&quot;&gt;6. Key Takeaways&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;A text-generative Transformer is a next-token predictor: embedding → stacked blocks (attention + MLP) → softmax over the vocabulary.&lt;/li&gt;
  &lt;li&gt;Attention weights are not decoration — they are the normalized, masked similarities that decide how each token gathers context.&lt;/li&gt;
  &lt;li&gt;Temperature, top-k, and top-p do not retrain the model; they only reshape the same logits into a different sampling distribution.&lt;/li&gt;
  &lt;li&gt;GPT-2 small is small enough to run in a browser and large enough to make the architecture tangible. Treat it as a microscope for Chapter 08, not as a substitute for a modern LLM.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;attribution-and-license&quot;&gt;Attribution and license&lt;/h2&gt;

&lt;p&gt;Transformer Explainer was created by Aeree Cho, Grace C. Kim, Alexander Karpekov, Alec Helbling, Jay Wang, Seongmin Lee, Benjamin Hoover, and Polo Chau at the Georgia Institute of Technology (Polo Club of Data Science). The software is released under the &lt;a href=&quot;https://github.com/poloclub/transformer-explainer/blob/main/LICENSE&quot;&gt;MIT License&lt;/a&gt;. The figures in this lesson are copied or resized from the project’s official &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;static/preview&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;static/article_assets&lt;/code&gt; files in the &lt;a href=&quot;https://github.com/poloclub/transformer-explainer&quot;&gt;public repository&lt;/a&gt;; the teaser was resized from 8135×3895 to 2400×1149 for the course site. Please cite the CHI 2026 paper if you use the tool in written work:&lt;/p&gt;

&lt;div class=&quot;language-bibtex highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nc&quot;&gt;@inproceedings&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;cho2026transformer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{Transformer Explainer: Learning LLM Transformers with Interactive Visual Explanation and Experimentation}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;author&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{Cho, Aeree and Kim, Grace C and Karpekov, Alexander and Lee, Seongmin and Helbling, Alec and Hoover, Benjamin and Wang, Zijie J and Kahng, Minsuk and Chau, Duen Horng}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;booktitle&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{Proceedings of the 2026 CHI Conference on Human Factors in Computing Systems}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;pages&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{1--21}&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
  &lt;span class=&quot;na&quot;&gt;year&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;{2026}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=TFUc41G2ikY&quot;&gt;Transformer Explainer Demo&lt;/a&gt; — Polo Club / Georgia Tech, English. A short walk through the live GPT-2 visualization this lesson uses.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. The same embedding → attention → MLP → softmax story, in animation rather than in a live model.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, English. The nanoGPT implementation that the in-browser model is derived from.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-01 The Transformer Architecture</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_01_Transformer_Architecture/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_01_Transformer_Architecture</id>
   <content type="html">&lt;p&gt;How did one architecture unify machine translation, code generation, protein folding, and image recognition under a single set of building blocks? Because the Transformer separates &lt;em&gt;where information flows&lt;/em&gt; (self- and cross-attention) from &lt;em&gt;how each token transforms it&lt;/em&gt; (position-wise MLPs), wrapped inside a deeply stable residual stream. This module hub connects the full mathematical theory of the Transformer with its step-by-step PyTorch implementation and diagnostic demos.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mastering-the-transformer-module&quot;&gt;Key ideas: Mastering the Transformer Module&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Theory &amp;amp; Equations&lt;/strong&gt;: Positional encodings, Pre-LN vs. Post-LN residual blocks, FFN capacity, and encoder–decoder vs. decoder-only topologies.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;From-Scratch Code&lt;/strong&gt;: Modular PyTorch layers, mask broadcasting, buffer registration, and unit tests.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Training &amp;amp; Diagnostics&lt;/strong&gt;: Learning-rate warmup, attention map inspection, and classic failure modes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-encoder-only-vs-decoder-only-attention-complexity&quot;&gt;Worked example: Encoder-Only vs. Decoder-Only Attention Complexity&lt;/h3&gt;

&lt;p&gt;Compare a 6-layer Encoder-only model (BERT-style) and a 6-layer Decoder-only model (GPT-style) on a sequence of length \(T = 128\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Active entries in the \(128 \times 128\) attention matrix per head&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Bidirectional Encoder: every token attends to all \(128\) tokens \(\implies 128^2 = 16{,}384\) active entries.&lt;/li&gt;
      &lt;li&gt;Causal Decoder: token \(i\) attends only to tokens \(0 \dots i\) \(\implies \frac{128 \times 129}{2} = 8{,}256\) active entries (roughly \(50\%\) of the matrix is strictly masked to zero!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Systems implication&lt;/strong&gt;: FlashAttention exploits this exact causal triangle to skip computing the upper-right half of the tile grid—achieving nearly a \(2\times\) speedup on causal LLMs compared to bidirectional encoders at the same sequence length.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;08-01-the-transformer-architecture&quot;&gt;08-01 The Transformer Architecture&lt;/h1&gt;

&lt;p&gt;This section is the heart of the chapter: how attention pieces from Chapter 07 assemble into a full model.&lt;/p&gt;

&lt;h2 id=&quot;lessons&quot;&gt;Lessons&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Transformer Theory&lt;/strong&gt;&lt;br /&gt;
Motivation vs RNNs, QKV self-attention inside the model, multi-head packaging, positional encodings, encoder layer, decoder layer (masked self-attn + cross-attn + FFN), residuals/LayerNorm, encoder-only vs decoder-only vs encoder–decoder families.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Transformer Implementation&lt;/strong&gt;&lt;br /&gt;
From-scratch modules, smoke tests, a tiny training demo, papers, and production pitfalls (mask conventions, PE mistakes, KV-cache, \(O(L^2)\) cost).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;suggested-path&quot;&gt;Suggested path&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Step&lt;/th&gt;
      &lt;th&gt;Lesson&lt;/th&gt;
      &lt;th&gt;Outcome&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;08-01-01 Theory&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;You can write the layer equations without notes&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02 Implementation overview&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Module map + checklist&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02-01 Core code&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Working PyTorch blocks&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02-02 Demos &amp;amp; pitfalls&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Train a toy model; debug confidently&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;If theory feels abstract, open the matching class in Core Code, run a forward pass on random tokens, then return to the equations.&lt;/p&gt;

&lt;p&gt;Continue with &lt;strong&gt;Transformer Theory&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. The data flow the theory and code lessons share.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, English. The code lesson’s destination: a GPT built from that block.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zxQyTK8quyY&quot;&gt;Transformer Neural Networks, ChatGPT’s foundation, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Use this if you want every tensor named before opening the code.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-01-02 Transformer Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_01_02_Transformer_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_01_02_Transformer_Implementation</id>
   <content type="html">&lt;p&gt;Going from Transformer equations to a rock-solid PyTorch codebase requires discipline across two stages: first implementing every core layer (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MultiHeadAttention&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PositionwiseFFN&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PositionalEncoding&lt;/code&gt;, encoder/decoder stacks) with airtight tensor shapes and masks; second running forward demos, inspecting attention weights, and guarding against real-world training pitfalls. This hub maps every module and pre-scaling checklist item before you train on larger corpora.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-transformer-module-architecture--pre-scaling-checklist&quot;&gt;Key ideas: Transformer Module Architecture &amp;amp; Pre-Scaling Checklist&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Core Layer Composition&lt;/strong&gt;: Connecting embeddings, positional buffers, Pre-/Post-LN sublayers, and residual dropouts into composable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Module&lt;/code&gt; blocks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Masking &amp;amp; Causal Integrity&lt;/strong&gt;: Enforcing padding masks in cross/self-attention and causal triangular masks in autoregressive decoders with zero leakage.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scaling Readiness&lt;/strong&gt;: Validating loss on a tiny overfit-one-batch sanity test, verifying gradient norms, and applying LR warmup + AdamW before launching multi-epoch runs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-the-overfit-one-batch-sanity-check-formula&quot;&gt;Worked example: The “Overfit One Batch” Sanity Check Formula&lt;/h3&gt;

&lt;p&gt;Before training a Transformer for hours, compute the expected &lt;strong&gt;initial random cross-entropy loss&lt;/strong&gt; for vocabulary size \(V = 10{,}000\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Expected loss at Step 0 (uniform random logits)&lt;/strong&gt;:
\(\mathcal{L}_0 = -\ln\!\left(\frac{1}{V}\right) = \ln(10{,}000) \approx 9.2103\text{ nats}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diagnostic interpretation&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;If your Step-0 loss is around &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;9.2&lt;/code&gt; and drops cleanly toward &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt; 0.1&lt;/code&gt; within 50–100 gradient steps on a single repeated batch, your masks, targets, and gradients are wired properly.&lt;/li&gt;
      &lt;li&gt;If Step-0 loss is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;45.0&lt;/code&gt; (poor weight initialization scale) or stalls at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;9.2&lt;/code&gt; (broken gradient flow or detached tensor), you catch the bug in 10 seconds instead of 10 hours!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;08-01-02-transformer-implementation&quot;&gt;08-01-02 Transformer Implementation&lt;/h1&gt;

&lt;p&gt;Theory defines the maps. Implementation must respect &lt;strong&gt;shapes, masks, residual order, and numerical stability&lt;/strong&gt;. These lessons build a small but honest Transformer stack.&lt;/p&gt;

&lt;h2 id=&quot;lessons&quot;&gt;Lessons&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Core Implementation&lt;/strong&gt;&lt;br /&gt;
Scaled attention, multi-head, positional encoding, FFN, encoder layer/stack—from scratch in PyTorch.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Demos, Papers, and Pitfalls&lt;/strong&gt;&lt;br /&gt;
Forward smoke tests, attention inspection, a tiny sequence task, literature, and a production-oriented debugging checklist.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;module-map&quot;&gt;Module map&lt;/h2&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Token ids
  → Embedding + PositionalEncoding
  → N × EncoderLayer
        MultiHeadSelfAttention (+ residual/norm)
        PositionwiseFFN        (+ residual/norm)
  → (optional) DecoderLayer stack with causal + cross-attn
  → Linear vocabulary head
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;checklist-before-you-scale-up&quot;&gt;Checklist before you scale up&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Item&lt;/th&gt;
      &lt;th&gt;Test&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Causal mask&lt;/td&gt;
      &lt;td&gt;Future weights ≈ 0&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Padding mask&lt;/td&gt;
      &lt;td&gt;Pad keys get weight 0&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Residual path&lt;/td&gt;
      &lt;td&gt;Ablation: removing residual should hurt depth&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;PE added once at input (classic)&lt;/td&gt;
      &lt;td&gt;Not every layer unless you chose that design&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_first&lt;/code&gt; consistency&lt;/td&gt;
      &lt;td&gt;All modules agree on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B,L,d)&lt;/code&gt; vs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(L,B,d)&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Dropout only in train mode&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; for inference&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Start with &lt;strong&gt;Core Implementation&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, English. The module map (attention, MLP, block, language-model head) is built on camera.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. The equations those modules must match.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zxQyTK8quyY&quot;&gt;Transformer Neural Networks, ChatGPT’s foundation, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. A second labeling of the block if a shape error is hard to localize.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-01-02-02 Transformer Demos, Papers, and Pitfalls</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_01_02_02_Transformer_Demos_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_01_02_02_Transformer_Demos_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Once your Transformer passes forward smoke tests, training it on a real sequence task exposes a new class of real-world engineering challenges: training instability without warmup, teacher-forcing vs. autoregressive decoding loops, subtle off-by-one target shifting (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x = seq[:-1]&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y = seq[1:]&lt;/code&gt;), and interpreting noisy attention heatmaps (which do not always equal causal feature importance!). Walking through concrete forward demos, attention visualizations, and classic failure modes turns working toy code into reliable production intuition.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-training-dynamics-decoding-and-transformer-pitfalls&quot;&gt;Key ideas: Training Dynamics, Decoding, and Transformer Pitfalls&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Next-Token Shift Alignment&lt;/strong&gt;: In causal language modeling, input &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[BOS, A, B, C]&lt;/code&gt; aligns with target &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[A, B, C, EOS]&lt;/code&gt;. Off-by-one shifting causes the model to learn the trivial identity function (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss -&amp;gt; 0.0&lt;/code&gt; instantly!) while producing gibberish at generation time.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Warmup + Cosine / Inverse-Sqrt LR Schedules&lt;/strong&gt;: In early steps, Adam’s second-moment variance estimates are noisy and Post-LN gradients are steep; linearly ramping the learning rate over the first \(N_{\text{warmup}}\) steps prevents early attention entropy collapse.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Autoregressive Decoding Latency &amp;amp; KV-Caching&lt;/strong&gt;: Recomputing the full forward pass over &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0..t]&lt;/code&gt; at every generated token costs \(O(T^3)\) total FLOPs for a length-\(T\) generation; caching past \(K, V\) drops total generation FLOPs to \(O(T^2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Attention Is Not Always Explanation&lt;/strong&gt;: Because residual connections mix token representations across layers, high attention weight on token \(j\) in layer 6 does not guarantee token \(j\) drove the final prediction—gradient-based attribution or ablation is needed for causal claims.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-the-vaswani-warmup-learning-rate-schedule&quot;&gt;Worked example: Computing the Vaswani Warmup Learning Rate Schedule&lt;/h3&gt;

&lt;p&gt;The original Transformer paper schedules the learning rate at step \(t\) using:
\(\eta(t) = d_{\text{model}}^{-0.5} \cdot \min\!\left(t^{-0.5},\; t \cdot N_{\text{warmup}}^{-1.5}\right).\)
Let \(d_{\text{model}} = 512\) (so \(d_{\text{model}}^{-0.5} = 1/\sqrt{512} \approx 0.04419\)) and \(N_{\text{warmup}} = 4{,}000\) (so \(4000^{-1.5} = 1 / (4000 \times 63.246) \approx 3.953 \times 10^{-6}\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;During warmup (\(t = 1{,}000\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(t^{-0.5} = 0.03162\), while \(t \cdot N_{\text{warmup}}^{-1.5} = 1000 \times 3.953 \times 10^{-6} = 0.003953\) (smaller).&lt;/li&gt;
      &lt;li&gt;\(\eta(1000) = 0.04419 \times 0.003953 \approx 1.75 \times 10^{-4}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;At peak warmup (\(t = 4{,}000\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Both terms equal \(4000^{-0.5} \approx 0.01581\).&lt;/li&gt;
      &lt;li&gt;\(\eta(4000) = 0.04419 \times 0.01581 \approx 6.99 \times 10^{-4}\) (maximum LR).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Post-warmup decay (\(t = 16{,}000\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(t^{-0.5} = 1/\sqrt{16000} \approx 0.007906\) (smaller).&lt;/li&gt;
      &lt;li&gt;\(\eta(16000) = 0.04419 \times 0.007906 \approx 3.49 \times 10^{-4}\) (exactly half the peak!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;transformer-demos-papers-and-pitfalls&quot;&gt;Transformer Demos, Papers, and Pitfalls&lt;/h1&gt;

&lt;p&gt;With modules in place, this lesson &lt;strong&gt;runs&lt;/strong&gt; them, trains a tiny task so gradients mean something, situates the architecture in the literature, and catalogs the mistakes that waste the most engineering time.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Three practical skills separate “I copied a Transformer” from “I can ship one”:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Instrumentation&lt;/strong&gt; — inspect attention weights and layer norms.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Minimal training loop&lt;/strong&gt; — prove the stack learns &lt;em&gt;something&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Operational knowledge&lt;/strong&gt; — warmup, KV-cache, mixed precision, \(O(L^2)\) limits.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We keep models tiny so demos run on a laptop CPU.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-mathematical--system-notes&quot;&gt;2. Mathematical / System Notes&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Teacher forcing loss&lt;/strong&gt; for next-token prediction on a sequence \(y_{1:L}\):&lt;/p&gt;

\[\mathcal{L} = -\sum_{t=1}^{L-1} \log p_\theta(y_{t+1} \mid y_{\le t})\]

&lt;p&gt;In a pure encoder toy task below, we instead train a simple &lt;strong&gt;shift prediction&lt;/strong&gt; head on encoder states (not a full LM)—enough to exercise PE + attention + residual stack.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;KV-cache (inference):&lt;/strong&gt; when generating token \(t\), reuse \(K_{1:t-1}, V_{1:t-1}\) already computed; only project the new token. Amortized cost per new token becomes \(O(t\,d)\) instead of recomputing a full \(O(t^2 d)\) pass from scratch each step (still total \(O(T^2)\) over full length \(T\), but with much less constant-factor waste).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Toy task: given a sequence of integers, predict the next integer (copy-shift). A model with PE + self-attention can learn “look at the last token / local pattern” without recurrence. If PE is removed, performance should collapse on order-sensitive patterns—use that as a sanity ablation.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;h3 id=&quot;41-forward-demo--attention-peek&quot;&gt;4.1 Forward demo + attention peek&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Reuse modules from the core lesson (paste classes from 08-01-02-01 into the same script,
# or import them from your package).
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# --- assume MultiHeadAttention, PositionalEncoding, TransformerEncoder,
# --- subsequent_mask are defined as in 08-01-02-01 ---
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;manual_seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;enc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TransformerEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;ids&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Inspect first layer self-attention with causal mask via standalone MHA
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detach&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subsequent_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, H, L, L)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;future mass&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diagonal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;42-tiny-training-next-step-prediction-on-encoder-states&quot;&gt;4.2 Tiny training: next-step prediction on encoder states&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyNextStepModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TransformerEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;head&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, L) token ids
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# (B, L, d)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;head&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# (B, L, V)
&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;make_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# sequences 0..seq_len-1 mod vocab, plus noise offset per row
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;base&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;repeat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;offset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;base&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;offset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# predict next id (shift); last position predicts (last+1)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyNextStepModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;opt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3e-4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;201&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;make_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# predict y_t from representation at position t
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;opt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip_grad_norm_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;opt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;step &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  loss &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;make_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;input    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tolist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;target   &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tolist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;pred     &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tolist&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;You should see loss trend down. Perfect accuracy is not required; &lt;strong&gt;downward loss + finite grads&lt;/strong&gt; is the bar.&lt;/p&gt;

&lt;h3 id=&quot;43-ablation-remove-positional-encoding&quot;&gt;4.3 Ablation: remove positional encoding&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NoPEEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TransformerEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;token_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;embed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;token_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# intentionally skip self.pos
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln_f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train briefly with NoPEEncoder inside a similar wrapper and compare final loss.
# Order-sensitive tasks should degrade without PE.
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;44-sketch-learning-rate-warmup-original-transformer-style&quot;&gt;4.4 Sketch: learning-rate warmup (original Transformer style)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;transformer_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;warmup&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;step&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;warmup&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;transformer_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;RNN seq2seq&lt;/strong&gt; — same encode/decode story; worse parallelism.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;CNN seq models&lt;/strong&gt; — local receptive fields; long range needs depth.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sparse Transformers / Longformer / Linformer&lt;/strong&gt; — sub-quadratic attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Encoder-decoder vs decoder-only&lt;/strong&gt; — product surface, shared guts.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Instruction tuning / RLHF&lt;/strong&gt; — sit &lt;em&gt;on top of&lt;/em&gt; pretrained Transformer LMs (later systems courses).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need (Vaswani et al., 2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Defines the architecture: multi-head attention, PE, encoder/decoder stacks, training recipe. The root paper for this chapter.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;BERT (Devlin et al., 2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Bidirectional encoder pretraining (MLM + NSP). Established pretrain → fine-tune for NLU.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf&quot;&gt;GPT-2 (Radford et al., 2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Large causal LMs; zero-shot task framing via prompts; scaling narrative.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;ViT (Dosovitskiy et al., 2021)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Images as patch token sequences; Transformers beyond text.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/2207.09238&quot;&gt;Formal Algorithms for Transformers (Phuong &amp;amp; Hutter, 2022)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Precise pseudocode for variants—use when reimplementing carefully.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-common-pitfalls-and-tricks&quot;&gt;7. Common Pitfalls and Tricks&lt;/h2&gt;

&lt;h3 id=&quot;critical-pitfalls&quot;&gt;Critical pitfalls&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;No positional signal&lt;/strong&gt; — model becomes bag-of-vectors with pairwise content mixing only.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mask polarity inverted&lt;/strong&gt; — future leakage or all-zero rows → &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; after softmax.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Padding attended as content&lt;/strong&gt; — unstable MT/LM metrics.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Missing \(1/\sqrt{d_k}\)&lt;/strong&gt; — sharp attention, poor training at width.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Post-LN vs Pre-LN recipe mismatch&lt;/strong&gt; — copy LR/warmup from a paper using the other.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Training dropout left on at inference&lt;/strong&gt; — noisy generations.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Recomputing full past every decode step&lt;/strong&gt; — unusable latency; add KV-cache for real decoding.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;training-tricks&quot;&gt;Training tricks&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Grad clip&lt;/strong&gt; (e.g. 1.0) helps early Transformer runs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Warmup&lt;/strong&gt; then decay; avoid large LR at step 0.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mixed precision&lt;/strong&gt; with loss scaling for speed/memory.&lt;/li&gt;
  &lt;li&gt;Log &lt;strong&gt;attention entropy&lt;/strong&gt; per layer to detect collapse or uniformity.&lt;/li&gt;
  &lt;li&gt;Start &lt;strong&gt;small&lt;/strong&gt; (2 layers, d=64–128) before scaling.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;debugging-checklist&quot;&gt;Debugging checklist&lt;/h3&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[ ] out.shape == (B, L, d) or (B, L, V)
[ ] causal: triu(attn,1) ≈ 0
[ ] pad keys: weights ≈ 0
[ ] loss finite; grad norms finite
[ ] PE length covers max L
[ ] model.train() vs model.eval() correct
[ ] Ablation: shuffle positions → performance drop (if PE works)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-key-takeaways&quot;&gt;8. Key Takeaways&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;A correct Transformer is &lt;strong&gt;modules + masks + residual discipline&lt;/strong&gt;, not only multi-head code.&lt;/li&gt;
  &lt;li&gt;Tiny trainable demos prove the stack before you download a 7B checkpoint.&lt;/li&gt;
  &lt;li&gt;Literature branches (BERT/GPT/ViT) share this core.&lt;/li&gt;
  &lt;li&gt;Most production pain is &lt;strong&gt;masks, PE, precision, and \(O(L^2)\)&lt;/strong&gt;, not the softmax formula.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You now have a complete Chapter 08 path: introduction → theory → implementation → demos/pitfalls. From here you can specialize into large language models, encoder-only NLU, or Vision Transformers using the same algebraic skeleton.&lt;/p&gt;

&lt;p&gt;To inspect a &lt;em&gt;pretrained&lt;/em&gt; GPT-2 without writing a training loop, continue to &lt;strong&gt;08-02 Transformer Explainer&lt;/strong&gt;: an in-browser visualization of embeddings, attention heads, temperature, and top-k / top-p sampling.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, English. The sampling demo and the pitfalls of an unmasked or untied implementation.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zxQyTK8quyY&quot;&gt;Transformer Neural Networks, ChatGPT’s foundation, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. A cleaner diagram of failure modes such as missing the residual path.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[How might LLMs store facts&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 7](https://www.youtube.com/watch?v=9-Jl0dxWQs8) — 3Blue1Brown, English. What the MLP inside the block can store, which is the lesson’s deeper reading of a working demo.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-01-02-01 Transformer Core Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_01_02_01_Transformer_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_01_02_01_Transformer_Core_Code</id>
   <content type="html">&lt;p&gt;Assembling a full Transformer from scratch in PyTorch—&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PositionalEncoding&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MultiHeadAttention&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PositionwiseFFN&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;EncoderLayer&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DecoderLayer&lt;/code&gt;, and top-level masks—is one of the most rewarding exercises in deep learning because the entire architecture fits cleanly in ~200 lines of readable code. Yet a single subtle convention mismatch—such as inverting the boolean mask polarity between padding and causal masks, or forgetting to scale embeddings by \(\sqrt{d_{\text{model}}}\)—can leave a syntactically valid model completely unable to converge.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-engineering-a-clean-pytorch-transformer&quot;&gt;Key ideas: Engineering a Clean PyTorch Transformer&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Embedding Scaling (\(\sqrt{d_{\text{model}}}\))&lt;/strong&gt; : Multiplying learned token embeddings by \(\sqrt{d_{\text{model}}}\) keeps their variance comparable to the \([-1, 1]\) sinusoidal positional encodings so position signals do not drown out word semantics at initialization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Unified Mask Polarity &amp;amp; Broadcasting&lt;/strong&gt;: Combining a 2D causal lower-triangular mask &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(1, 1, T, T)&lt;/code&gt; with a 1D padding mask &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, 1, 1, T)&lt;/code&gt; via logical &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AND&lt;/code&gt; (or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;OR&lt;/code&gt; depending on polarity) ensures every head and batch item enforces both causality and padding simultaneously.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Registering Non-Trainable Buffers (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;register_buffer&lt;/code&gt;)&lt;/strong&gt;: Storing the precomputed sinusoidal positional encoding table via &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;self.register_buffer(&quot;pe&quot;, pe)&lt;/code&gt; ensures it automatically moves with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.to(device)&lt;/code&gt; and saves inside &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;state_dict&lt;/code&gt; without receiving optimizer gradient updates.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Smoke-Test Driven Verification&lt;/strong&gt;: Running shape assertions, causal leakage tests (perturbing token \(t+1\) must change output at step \(t\) by exactly &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt;), and gradient-flow checks before training prevents hours of wasted GPU compute.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-verifying-zero-future-leakage-in-a-causal-mask-test&quot;&gt;Worked example: Verifying Zero Future Leakage in a Causal Mask Test&lt;/h3&gt;

&lt;p&gt;How do you prove mathematically that your decoder implementation has zero future-token leakage?&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Construct two length-4 input batches&lt;/strong&gt; that match on tokens &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0, 1, 2&lt;/code&gt; and differ &lt;em&gt;only&lt;/em&gt; at token &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3&lt;/code&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x1 = [4, 9, 2, 7]&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;x2 = [4, 9, 2, 99]&lt;/code&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Run &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt;&lt;/strong&gt; (disabling dropout!) and compute &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y1 = model(x1)&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;y2 = model(x2)&lt;/code&gt; of shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(1, 4, V)&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Measure the absolute difference at positions &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0, 1, 2&lt;/code&gt;&lt;/strong&gt;:
\(\Delta_t = \max_v |y_1[0, t, v] - y_2[0, t, v]| \quad \text{for } t \in \{0, 1, 2\}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pass/Fail criterion&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Pass&lt;/strong&gt;: \(\Delta_0 = \Delta_1 = \Delta_2 = 0.0\) (to machine precision \(&amp;lt; 10^{-6}\)), while \(\Delta_3 &amp;gt; 0\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Fail&lt;/strong&gt;: If \(\Delta_2 &amp;gt; 0\), your causal mask is transposed, inverted, or missing!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;transformer-core-implementation&quot;&gt;Transformer Core Implementation&lt;/h1&gt;

&lt;p&gt;This lesson implements the &lt;strong&gt;building blocks&lt;/strong&gt; of a Transformer encoder (and the attention core shared with decoders). Code is written for clarity and correct shapes first; production systems then swap in fused kernels (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scaled_dot_product_attention&lt;/code&gt;) and larger configs.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;We will implement, bottom-up:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Scaled dot-product attention&lt;/li&gt;
  &lt;li&gt;Multi-head attention&lt;/li&gt;
  &lt;li&gt;Sinusoidal positional encoding&lt;/li&gt;
  &lt;li&gt;Position-wise FFN&lt;/li&gt;
  &lt;li&gt;Encoder layer + encoder stack&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Each piece is a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Module&lt;/code&gt; with an explicit forward signature so you can unit-test it in isolation.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-mathematical-reminder&quot;&gt;2. Mathematical Reminder&lt;/h2&gt;

\[\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V\]

\[\mathrm{PE}_{(pos,2i)}=\sin(pos/10000^{2i/d}),\quad
\mathrm{PE}_{(pos,2i+1)}=\cos(pos/10000^{2i/d})\]

&lt;p&gt;Encoder layer (Pre-LN style used below for stability in deep stacks):&lt;/p&gt;

\[\begin{aligned}
X &amp;amp;\leftarrow X + \mathrm{MHA}(\mathrm{LN}(X)) \\
X &amp;amp;\leftarrow X + \mathrm{FFN}(\mathrm{LN}(X))
\end{aligned}\]

&lt;hr /&gt;

&lt;h2 id=&quot;3-example--intuition-for-the-demos&quot;&gt;3. Example / Intuition for the demos&lt;/h2&gt;

&lt;p&gt;We run random token ids through an encoder and check:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;output shape equals \((B, L, d_{\mathrm{model}})\),&lt;/li&gt;
  &lt;li&gt;causal/pad masks zero out forbidden weights,&lt;/li&gt;
  &lt;li&gt;a short forward pass is differentiable (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss.backward()&lt;/code&gt; works).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Training a &lt;em&gt;real&lt;/em&gt; language model is not the goal here—plumbing correctness is.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ScaledDotProductAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    q,k,v: (B, H, L, d_k)  [v last dim may be d_v == d_k here]
    mask:  broadcastable to (B, H, Lq, Lk); True = keep, False = mask out
           (we use bool keep-mask; convert to -inf fill)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;masked_fill&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;~&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-inf&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ScaledDotProductAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# (B, L, d) -&amp;gt; (B, H, L, dk)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# (B, H, L, dk) -&amp;gt; (B, L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;contiguous&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# q,k,v: (B, L, d_model)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PositionalEncoding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Fixed sin-cos PE (Vaswani et al.).
    - pos: 0..L-1
    - i: 0..d_model/2-1  →  even dim 2i = sin, odd dim 2i+1 = cos
    - forward: token_emb + PE  (same shape)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;div&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;arange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;10000.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sin&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;div&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2i
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;div&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2i+1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;register_buffer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (1, max_len, d)
&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, L, d)  — usually token embeddings
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PositionwiseFFN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;net&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;net&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;EncoderLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pre-LN encoder layer.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LayerNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self_attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LayerNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ff&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PositionwiseFFN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;self_attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TransformerEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embed&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;PositionalEncoding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ModuleList&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;EncoderLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln_f&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LayerNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;token_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# token_ids: (B, L)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;embed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;token_ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln_f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;subsequent_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bool keep-mask for causal attention: (1, 1, L, L).&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tril&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# -------------------- smoke tests --------------------
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__name__&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;__main__&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;manual_seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TransformerEncoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ids&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ids&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;encoder out&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# causal mask path through MHA directly
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subsequent_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# forbidden future: upper triangle of weights ~ 0
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;future&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diagonal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;future&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;future&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;atol&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;causal multi-head OK&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;backward OK&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;mask-convention-note&quot;&gt;Mask convention note&lt;/h3&gt;

&lt;p&gt;This code uses a &lt;strong&gt;boolean keep-mask&lt;/strong&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;True&lt;/code&gt; = attend allowed). Many APIs use the opposite bool meaning or additive float masks. Always read the docstring of the function you call—mask polarity bugs are the #1 Transformer footgun.&lt;/p&gt;

&lt;h3 id=&quot;hook-for-padding&quot;&gt;Hook for padding&lt;/h3&gt;

&lt;p&gt;For variable lengths, build a mask of shape \((B,1,1,L)\) (broadcast over heads and queries) with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;False&lt;/code&gt; on pad keys, or combine with causal via logical AND for decoders.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.TransformerEncoder&lt;/code&gt;&lt;/strong&gt; — library equivalent of this stack.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decoder layer&lt;/strong&gt; — add a second MHA block for cross-attention + causal mask on self-attn.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Weight tying&lt;/strong&gt; — share input embedding and output projection in LMs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SDPA / FlashAttention&lt;/strong&gt; — same math, fused kernels.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-fundamental-papers-implementation-relevant&quot;&gt;6. Fundamental Papers (implementation-relevant)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Vaswani et al., 2017&lt;/a&gt; — reference module list and base hyperparameters.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2207.09238&quot;&gt;Phuong &amp;amp; Hutter, 2022&lt;/a&gt; — formal algorithms; excellent when reimplementing.&lt;/li&gt;
  &lt;li&gt;PyTorch: &lt;a href=&quot;https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.Transformer&lt;/code&gt;&lt;/a&gt; — production-oriented API.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-common-pitfalls-and-tricks&quot;&gt;7. Common Pitfalls and Tricks&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Pitfall&lt;/th&gt;
      &lt;th&gt;Fix&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;PE length &amp;lt; sequence length&lt;/td&gt;
      &lt;td&gt;Raise &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max_len&lt;/code&gt; or use relative/RoPE schemes&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Dropout left on at eval&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.no_grad()&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Scale embedding by \(\sqrt{d}\) forgotten&lt;/td&gt;
      &lt;td&gt;Matches original paper; keep consistent&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Wrong residual branch&lt;/td&gt;
      &lt;td&gt;Add &lt;em&gt;input&lt;/em&gt; of sublayer, not normalized-only path without residual&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;In-place ops on tensors needed for grad&lt;/td&gt;
      &lt;td&gt;Avoid in-place on views used backward&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Trick:&lt;/strong&gt; test each module with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.autograd.gradcheck&lt;/code&gt; on tiny float64 inputs when writing custom attention.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-key-takeaways&quot;&gt;8. Key Takeaways&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Implement &lt;strong&gt;attention → multi-head → PE → FFN → layer stack&lt;/strong&gt; in that order.&lt;/li&gt;
  &lt;li&gt;Pre-LN residual blocks are a stable default for deep stacks.&lt;/li&gt;
  &lt;li&gt;Masks are part of the API contract—document polarity.&lt;/li&gt;
  &lt;li&gt;Smoke tests on shapes, causal structure, and backward are mandatory before training.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Next: demos, papers in narrative form, and operational pitfalls.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1306224801415127&quot;&gt;Position Encoding in Transformers (step by step)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, English. The core modules. The video is long; it is the canonical from-scratch implementation of this lesson.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. Keep the data-flow picture beside the notebook.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Positional embeddings in transformers EXPLAINED&lt;/td&gt;
          &lt;td&gt;Demystifying positional encodings.](https://www.youtube.com/watch?v=1biZfFLPRSY) — AI Coffee Break with Letitia, English. Add this when the token embeddings have no position and the model ignores order.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08-01-01 Transformer Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_01_01_Transformer_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_01_01_Transformer_Theory</id>
   <content type="html">&lt;p&gt;Every sub-component inside a Transformer block was forged to solve a specific mathematical instability. Remove LayerNorm or place it poorly at high learning rates, and deep Transformers diverge; remove the \(4\times\) expansion inside the position-wise FFN, and the model loses its nonlinear representational capacity; remove sinusoidal/relative phase shifts, and attention cannot distinguish word order. Reading the Transformer block as a unified dynamical system—residual stream, normalization, attention mixing, and FFN expansion—makes every hyperparameter choice transparent.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-mathematical-theory-of-the-transformer-block&quot;&gt;Key ideas: Mathematical Theory of the Transformer Block&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Sinusoidal Positional Encodings &amp;amp; Linear Shift Property&lt;/strong&gt;: Encoding position \(p\) with \(\sin(p / 10000^{2i/d})\) and \(\cos(p / 10000^{2i/d})\) ensures that any fixed offset \(\Delta\) corresponds to an exact \(2 \times 2\) orthogonal rotation matrix independent of \(p\), letting attention compute relative distances via linear projections.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pre-LN vs. Post-LN Residual Dynamics&lt;/strong&gt;: The original 2017 paper used Post-LN (\(\text{LN}(x + F(x))\)), which required delicate learning-rate warmup to prevent early gradient explosion. Modern LLMs use Pre-LN (\(x + F(\text{LN}(x))\)), keeping a completely clean, unnormalized identity residual highway from input to output.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Position-Wise Feed-Forward Network (FFN)&lt;/strong&gt;: Applied identically to each token position, \(\text{FFN}(x) = W_2 \sigma(W_1 x + b_1) + b_2\) expands dimension \(d_{\text{model}} \to 4 d_{\text{model}} \to d_{\text{model}}\) and actually holds &lt;strong&gt;two-thirds&lt;/strong&gt; of a standard Transformer block’s parameters!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-Entropy Label Smoothing &amp;amp; Weight Tying&lt;/strong&gt;: Sharing the input token embedding matrix with the final output unembedding projection (\(W_{\text{out}} = W_{\text{emb}}^\top\)) saves tens of millions of parameters while regularizing the logit space.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-exact-parameter-audit-of-one-transformer-block&quot;&gt;Worked example: Exact Parameter Audit of One Transformer Block&lt;/h3&gt;

&lt;p&gt;Consider a canonical Transformer encoder/decoder block with \(d_{\text{model}} = 512\), \(h = 8\) heads, and $$d_{\text{ff}} = 4 d_{\text{model}} = 2{,}048$ (including biases):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Multi-Head Self-Attention (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;W_Q, W_K, W_V, W_O&lt;/code&gt;)&lt;/strong&gt;:
\(4 \times (512 \times 512 + 512) = 4 \times 262{,}656 = 1{,}050{,}624.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Position-wise FFN (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;512 -&amp;gt; 2048 -&amp;gt; 512&lt;/code&gt;)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;First linear: \(512 \times 2{,}048 + 2{,}048 = 1{,}050{,}624\).&lt;/li&gt;
      &lt;li&gt;Second linear: \(2{,}048 \times 512 + 512 = 1{,}049{,}088\).&lt;/li&gt;
      &lt;li&gt;FFN subtotal: \(2{,}099{,}712\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Two LayerNorm layers&lt;/strong&gt; (\(\gamma, \beta \in \mathbb{R}^{512}\) each):
\(2 \times (2 \times 512) = 2{,}048.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Grand total per block&lt;/strong&gt;:
\(1{,}050{,}624 + 2{,}099{,}712 + 2{,}048 = 3{,}152{,}384 \approx 12 d_{\text{model}}^2.\)
Notice the iconic rule of thumb: &lt;strong&gt;\(12 d_{\text{model}}^2\)&lt;/strong&gt; parameters per Transformer block—with &lt;strong&gt;\(66.6\%\)&lt;/strong&gt; inside the FFN and &lt;strong&gt;\(33.3\%\)&lt;/strong&gt; inside self-attention!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;transformer-theory&quot;&gt;Transformer Theory&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_architecture.png&quot; alt=&quot;Transformer Architecture&quot; /&gt;
&lt;em&gt;Encoder–decoder Transformer (Vaswani et al., 2017). Source: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;The Transformer is an architecture for sequence (and “sequence-like”) data built primarily from &lt;strong&gt;multi-head attention&lt;/strong&gt; and &lt;strong&gt;position-wise feed-forward networks&lt;/strong&gt;, wrapped in residual connections and layer normalization. Introduced by Vaswani et al. (2017) for machine translation, it discarded recurrence and convolution as the main sequence operators.&lt;/p&gt;

&lt;h3 id=&quot;what-was-wrong-with-just-use-a-better-rnn&quot;&gt;What was wrong with “just use a better RNN”?&lt;/h3&gt;

&lt;p&gt;Even excellent RNNs (LSTM/GRU) have structural constraints:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Constraint&lt;/th&gt;
      &lt;th&gt;Effect&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Left-to-right state updates&lt;/td&gt;
      &lt;td&gt;Hard to parallelize over length during training&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Long dependency path&lt;/td&gt;
      &lt;td&gt;Early tokens must survive many steps to affect late predictions&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Fixed-size hidden state&lt;/td&gt;
      &lt;td&gt;Soft bottleneck for very rich context&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Attention already showed that models can &lt;em&gt;look up&lt;/em&gt; relevant states. The Transformer’s claim was sharper: &lt;strong&gt;you do not need recurrence at all&lt;/strong&gt; if every layer lets every position attend to every other position (with masks when needed) and then applies a strong local MLP.&lt;/p&gt;

&lt;h3 id=&quot;three-product-families-from-one-architecture&quot;&gt;Three product families from one architecture&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Family&lt;/th&gt;
      &lt;th&gt;Structure&lt;/th&gt;
      &lt;th&gt;Examples&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Encoder-only&lt;/td&gt;
      &lt;td&gt;Bidirectional self-attention&lt;/td&gt;
      &lt;td&gt;BERT, RoBERTa&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Decoder-only&lt;/td&gt;
      &lt;td&gt;Causal self-attention&lt;/td&gt;
      &lt;td&gt;GPT-2/3/4, LLaMA&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Encoder–decoder&lt;/td&gt;
      &lt;td&gt;Encoder + cross-attn decoder&lt;/td&gt;
      &lt;td&gt;Original Transformer, T5, BART&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Same layer primitives; different attention patterns and training objectives.&lt;/p&gt;

&lt;h3 id=&quot;building-blocks-preview&quot;&gt;Building blocks (preview)&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;Token + positional embeddings&lt;/li&gt;
  &lt;li&gt;Stacked encoder layers: self-attn → FFN (each with residual + norm)&lt;/li&gt;
  &lt;li&gt;Stacked decoder layers: &lt;em&gt;masked&lt;/em&gt; self-attn → cross-attn → FFN&lt;/li&gt;
  &lt;li&gt;Output projection to vocabulary (generation) or task heads (classification)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/tf_full_arch_multihead_zoom.jpg&quot; alt=&quot;Full architecture + Multi-Head / Scaled Dot-Product zoom&quot; /&gt;
&lt;em&gt;Figure: Encoder–decoder with multi-head and scaled dot-product attention zoomed in. (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Chapter 07 already covered attention math. This lesson places that math inside the &lt;strong&gt;full system&lt;/strong&gt;, with special focus on &lt;strong&gt;order&lt;/strong&gt; (positional encoding) and &lt;strong&gt;layer composition&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;h3 id=&quot;21-input-representation&quot;&gt;2.1 Input representation&lt;/h3&gt;

&lt;p&gt;Let tokens be indices \(t_1,\ldots,t_L\). An embedding matrix \(E\) maps them to vectors:&lt;/p&gt;

\[\mathbf{x}_i^{(0)} = E_{t_i} + \mathbf{p}_i \in \mathbb{R}^{d_{\mathrm{model}}}\]

&lt;p&gt;where \(\mathbf{p}_i\) is a &lt;strong&gt;positional encoding&lt;/strong&gt; (fixed or learned). Stack rows:&lt;/p&gt;

\[\mathbf{X}^{(0)} \in \mathbb{R}^{L \times d_{\mathrm{model}}}.\]

&lt;p&gt;(Batch dimension \(B\) is always present in code: \((B,L,d)\).)&lt;/p&gt;

&lt;h3 id=&quot;22-scaled-multi-head-self-attention-model-interface&quot;&gt;2.2 Scaled multi-head self-attention (model interface)&lt;/h3&gt;

&lt;p&gt;With learned projections (see Chapter 07 for details):&lt;/p&gt;

\[\mathrm{MultiHead}(\mathbf{X})
= \mathrm{Concat}_h\!\left(
  \mathrm{Attention}(\mathbf{X}W_h^Q,\mathbf{X}W_h^K,\mathbf{X}W_h^V)
\right) W^O\]

\[\mathrm{Attention}(Q,K,V)=\mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V\]

&lt;p&gt;where \(M\) is an optional additive mask (padding and/or causal).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Role in the Transformer:&lt;/strong&gt; this is the &lt;em&gt;communication&lt;/em&gt; step—positions exchange information.&lt;/p&gt;

&lt;h3 id=&quot;23-position-wise-feed-forward-network-ffn&quot;&gt;2.3 Position-wise feed-forward network (FFN)&lt;/h3&gt;

&lt;p&gt;Applied &lt;strong&gt;independently&lt;/strong&gt; to each position (same weights for all positions):&lt;/p&gt;

\[\mathrm{FFN}(\mathbf{z}) = W_2\,\sigma(W_1\mathbf{z}+\mathbf{b}_1)+\mathbf{b}_2\]

&lt;p&gt;with typical widths \(d_{\mathrm{model}} \to d_{\mathrm{ff}} \to d_{\mathrm{model}}\) and \(d_{\mathrm{ff}} \approx 4\,d_{\mathrm{model}}\). Activation \(\sigma\) was ReLU in the original paper; modern models often use GELU or SwiGLU variants.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why FFN exists:&lt;/strong&gt; multi-head attention is essentially a &lt;em&gt;data-dependent linear mixture&lt;/em&gt; of values (plus projections). Without a nonlinear MLP per position, stacking attention layers has limited per-token computational power. Attention mixes; FFN &lt;em&gt;computes&lt;/em&gt;.&lt;/p&gt;

&lt;h3 id=&quot;24-residual-connections-and-layernorm&quot;&gt;2.4 Residual connections and LayerNorm&lt;/h3&gt;

&lt;p&gt;Original (“Post-LN”) encoder sublayer:&lt;/p&gt;

\[\mathbf{Y} = \mathrm{LayerNorm}\big(\mathbf{X} + \mathrm{Sublayer}(\mathbf{X})\big)\]

&lt;p&gt;where Sublayer is MultiHead or FFN. Many modern models use &lt;strong&gt;Pre-LN&lt;/strong&gt;:&lt;/p&gt;

\[\mathbf{Y} = \mathbf{X} + \mathrm{Sublayer}\big(\mathrm{LayerNorm}(\mathbf{X})\big)\]

&lt;p&gt;which often trains more stably at depth.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Residuals&lt;/strong&gt; keep gradient highways; &lt;strong&gt;LayerNorm&lt;/strong&gt; stabilizes activation scales across tokens and layers.&lt;/p&gt;

&lt;h3 id=&quot;25-full-encoder-layer&quot;&gt;2.5 Full encoder layer&lt;/h3&gt;

&lt;p&gt;Post-LN form (as in the original paper):&lt;/p&gt;

\[\begin{aligned}
\mathbf{U} &amp;amp;= \mathrm{LayerNorm}\big(\mathbf{X} + \mathrm{MultiHeadSelfAttn}(\mathbf{X})\big) \\
\mathbf{Z} &amp;amp;= \mathrm{LayerNorm}\big(\mathbf{U} + \mathrm{FFN}(\mathbf{U})\big)
\end{aligned}\]

&lt;p&gt;Stack \(N\) such layers (often \(N=6\) in the base model, far more in LLMs).&lt;/p&gt;

&lt;h3 id=&quot;26-full-decoder-layer&quot;&gt;2.6 Full decoder layer&lt;/h3&gt;

&lt;p&gt;Three sublayers:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Masked self-attention&lt;/strong&gt; over previously generated tokens (causal mask).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-attention&lt;/strong&gt; where queries come from the decoder stream and keys/values come from encoder outputs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FFN&lt;/strong&gt; as above.&lt;/li&gt;
&lt;/ol&gt;

\[\begin{aligned}
\mathbf{U} &amp;amp;= \mathrm{LN}\big(\mathbf{Y} + \mathrm{MaskedSelfAttn}(\mathbf{Y})\big) \\
\mathbf{V} &amp;amp;= \mathrm{LN}\big(\mathbf{U} + \mathrm{CrossAttn}(\mathbf{U}, \mathbf{H}_{\mathrm{enc}}, \mathbf{H}_{\mathrm{enc}})\big) \\
\mathbf{Z} &amp;amp;= \mathrm{LN}\big(\mathbf{V} + \mathrm{FFN}(\mathbf{V})\big)
\end{aligned}\]

&lt;p&gt;&lt;strong&gt;Causal mask:&lt;/strong&gt; for query position \(i\), forbid keys \(j &amp;gt; i\) so the model cannot “see the future” when trained with teacher forcing.&lt;/p&gt;

&lt;h3 id=&quot;27-positional-encoding-sinusoidal&quot;&gt;2.7 Positional encoding (sinusoidal)&lt;/h3&gt;

&lt;p&gt;Attention alone is &lt;strong&gt;permutation-equivariant&lt;/strong&gt; in content: without position signals, order is invisible. The original PE:&lt;/p&gt;

\[\begin{aligned}
PE_{(pos,2i)} &amp;amp;= \sin\!\big(pos / 10000^{2i/d_{\mathrm{model}}}\big) \\
PE_{(pos,2i+1)} &amp;amp;= \cos\!\big(pos / 10000^{2i/d_{\mathrm{model}}}\big)
\end{aligned}\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_formula_and_token_matrix.jpg&quot; alt=&quot;PE formulas + token matrix&quot; /&gt;
&lt;em&gt;Figure: Each token has a \(d_{\mathrm{model}}\) vector; PE uses sin/cos of \(pos\) and frequency index \(i\). (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_pos_index_sentence.jpg&quot; alt=&quot;pos = token index in the sentence&quot; /&gt;
&lt;em&gt;Figure: \(pos = 0,1,2,\ldots\) in token order. (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reading dimension indices.&lt;/strong&gt; For \(d_{\mathrm{model}}=512\), frequency index \(i\) runs \(0\ldots 255\): each \(i\) produces &lt;strong&gt;two&lt;/strong&gt; dimensions — even \(2i\) uses &lt;strong&gt;sin&lt;/strong&gt;, odd \(2i+1\) uses &lt;strong&gt;cos&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_i_range_sin_cos_dims.jpg&quot; alt=&quot;Table i → sin/cos dimensions&quot; /&gt;
&lt;em&gt;Figure: \(i=0\to\) dims 0 (sin), 1 (cos); …; \(i=255\to\) dims 510, 511. (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_even_odd_dims.jpg&quot; alt=&quot;Even dims sin / odd dims cos&quot; /&gt;
&lt;em&gt;Figure: Sin fills even slots, cos fills odd slots of the PE vector. (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_sin_cos_formula_plot.jpg&quot; alt=&quot;Sin and cos&quot; /&gt;
&lt;em&gt;Figure: Sin/cos pair at the same frequency — the wave basis for PE. (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_multiple_frequencies_i.jpg&quot; alt=&quot;Multiple frequencies by i&quot; /&gt;
&lt;em&gt;Figure: Each \(i\) has a different frequency; small \(i\) = slow waves, large \(i\) = fast waves. (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sampling a PE vector at one position.&lt;/strong&gt; Fix \(pos\); for each \(i\) read one point on sin and one on cos → stack into a length-\(d_{\mathrm{model}}\) vector.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_sample_values_pos0.jpg&quot; alt=&quot;Sample PE at pos=0&quot; /&gt;
&lt;em&gt;Figure: Column at \(pos=0\) — PE components for the first token. (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_sample_values_pos3.jpg&quot; alt=&quot;Sample PE at pos=3&quot; /&gt;
&lt;em&gt;Figure: Same procedure at \(pos=3\) — a different vector because the waves have phase-shifted. (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Add to the embedding.&lt;/strong&gt; Token embedding and PE share the same width; the actual input is usually:&lt;/p&gt;

\[\mathbf{x}_{pos} = \mathrm{TokenEmb}(w_{pos}) + \mathrm{PE}_{pos}\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_input_emb_vs_positional.jpg&quot; alt=&quot;Token emb vs PE (same 512-d)&quot; /&gt;
&lt;em&gt;Figure: Two same-\(d_{\mathrm{model}}\) vectors — elementwise sum “glues” order onto content. (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_token_emb_plus_pe_columns.jpg&quot; alt=&quot;Token emb columns (purple) + PE columns (green)&quot; /&gt;
&lt;em&gt;Figure: Each position has a token-embedding column and a matching PE column. (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Properties:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Deterministic; no learned parameters.&lt;/li&gt;
  &lt;li&gt;Unique “fingerprint” per position via multi-frequency sinusoids.&lt;/li&gt;
  &lt;li&gt;Relative offsets are linear transforms of PE vectors, which helps learning relative-distance patterns.&lt;/li&gt;
  &lt;li&gt;Can, in principle, extrapolate beyond training lengths better than naive learned absolute embeddings (though real extrapolation still needs care).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Alternatives:&lt;/strong&gt; learned absolute embeddings (BERT/GPT), relative bias (T5, Shaw), RoPE (modern LLMs). The &lt;em&gt;problem&lt;/em&gt; is always the same: inject order into a content-based mixer.&lt;/p&gt;

&lt;h3 id=&quot;28-complexity&quot;&gt;2.8 Complexity&lt;/h3&gt;

&lt;p&gt;Dense self-attention costs \(O(L^2 d)\) time and \(O(L^2)\) memory for scores. That is the tax paid for global communication. For long documents, sparse/linear attention variants become necessary; for typical sentence/paragraph lengths, dense attention is the default.&lt;/p&gt;

&lt;h3 id=&quot;29-training-objective-sketch-original-mt-model&quot;&gt;2.9 Training objective sketch (original MT model)&lt;/h3&gt;

&lt;p&gt;Encoder reads source tokens; decoder predicts next target token with cross-entropy under teacher forcing. Modern encoder-only models use masked LM; decoder-only models use next-token LM. Architecture stays related; &lt;strong&gt;objective + mask pattern&lt;/strong&gt; change the product behavior.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;h3 id=&quot;31-one-encoder-tokens-journey&quot;&gt;3.1 One encoder token’s journey&lt;/h3&gt;

&lt;p&gt;Sentence: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;I love deep learning&lt;/code&gt;. Focus on position &lt;strong&gt;learning&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In layer 1 self-attention, its query may put large weight on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;deep&lt;/code&gt; and itself, producing a mixture that already means “deep learning” rather than bare “learning.” The FFN then nonlinearly reshapes that mixture. Deeper layers further refine roles (syntax, semantics) as attention patterns become more abstract.&lt;/p&gt;

&lt;p&gt;All four positions do this &lt;strong&gt;in parallel&lt;/strong&gt; via matrix multiplies—unlike an RNN that would need four sequential steps.&lt;/p&gt;

&lt;h3 id=&quot;32-one-decoder-step&quot;&gt;3.2 One decoder step&lt;/h3&gt;

&lt;p&gt;Generating French &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;profond&lt;/code&gt; after &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;J&apos; aime l&apos;apprentissage&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Masked self-attn&lt;/strong&gt; attends only to earlier French tokens (coherence of the hypothesis so far).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-attn&lt;/strong&gt; looks at English encoder states; mass should concentrate on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;deep&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FFN + softmax over vocab&lt;/strong&gt; proposes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;profond&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If the causal mask is wrong, the model cheats during training and collapses at true autoregressive inference.&lt;/p&gt;

&lt;h3 id=&quot;33-encoder-only-vs-decoder-only&quot;&gt;3.3 Encoder-only vs decoder-only&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;BERT (encoder-only):&lt;/strong&gt; bidirectional self-attn + masked LM → strong &lt;em&gt;understanding&lt;/em&gt; representations.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GPT (decoder-only):&lt;/strong&gt; causal self-attn + next-token LM → strong &lt;em&gt;generation&lt;/em&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Same MultiHead/FFN blocks; different masks and data flow.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-code-snippet-equation-facing&quot;&gt;4. Code Snippet (equation-facing)&lt;/h2&gt;

&lt;p&gt;Minimal shapes for one Pre-LN encoder layer:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyEncoderLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LayerNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MultiheadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LayerNorm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ff&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key_padding_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key_padding_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key_padding_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ln2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ff&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;layer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TinyEncoderLayer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 10, 64)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Full from-scratch modules appear in the implementation lessons.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Seq2seq RNNs&lt;/strong&gt; — same encode/decode idea; Transformer replaces recurrence with attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convolution&lt;/strong&gt; — fixed local kernels vs dynamic global mixing.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Residual nets&lt;/strong&gt; — depth without gradient death.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pretraining paradigms&lt;/strong&gt; — MLM vs CLM vs span corruption (T5).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vision Transformer&lt;/strong&gt; — image patches as tokens; same encoder math.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Vaswani et al., 2017 — Attention Is All You Need&lt;/a&gt; — original architecture.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;Devlin et al., 2019 — BERT&lt;/a&gt; — bidirectional encoder pretraining.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf&quot;&gt;Radford et al., 2019 — GPT-2&lt;/a&gt; — large causal LMs + zero-shot.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2010.11929&quot;&gt;Dosovitskiy et al., 2021 — ViT&lt;/a&gt; — Transformers for images.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2207.09238&quot;&gt;Phuong &amp;amp; Hutter, 2022 — Formal Algorithms for Transformers&lt;/a&gt; — precise reference definitions.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-common-pitfalls-and-tricks&quot;&gt;7. Common Pitfalls and Tricks&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Forgetting &lt;strong&gt;positional&lt;/strong&gt; information → order-blind model.&lt;/li&gt;
  &lt;li&gt;Causal mask with &lt;strong&gt;0&lt;/strong&gt; instead of &lt;strong&gt;−∞&lt;/strong&gt; before softmax → future leakage.&lt;/li&gt;
  &lt;li&gt;Missing &lt;strong&gt;pad&lt;/strong&gt; masks in batched training.&lt;/li&gt;
  &lt;li&gt;Omitting \(1/\sqrt{d_k}\) at large width.&lt;/li&gt;
  &lt;li&gt;Confusing &lt;strong&gt;Post-LN vs Pre-LN&lt;/strong&gt; when porting recipes (learning rates differ).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trick:&lt;/strong&gt; unit-test causal attention with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;triu(weights,1)≈0&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trick:&lt;/strong&gt; start with a 2-layer tiny model before scaling depth/width.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-key-takeaways&quot;&gt;8. Key Takeaways&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;A Transformer layer is &lt;strong&gt;attend (communicate) + FFN (compute)&lt;/strong&gt; with residual/norm.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Masks&lt;/strong&gt; define the product family: bidirectional, causal, or cross.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Positional encodings&lt;/strong&gt; fix order blindness of pure attention.&lt;/li&gt;
  &lt;li&gt;Encoder/decoder stacks compose the same layer types into translation or other seq2seq systems.&lt;/li&gt;
  &lt;li&gt;BERT/GPT/ViT are mask + objective + data choices on top of this template.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Next: implement these blocks carefully in &lt;strong&gt;08-01-02&lt;/strong&gt;.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1007473105556936&quot;&gt;Attention in Transformers (Self, Masked, Cross, Multi-Head)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1306224801415127&quot;&gt;Position Encoding in Transformers (step by step)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. Embeddings, attention, MLP, softmax, and temperature are the theory lesson’s pieces.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, English. The attention step inside that block, at the resolution the math section needs.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Positional embeddings in transformers EXPLAINED&lt;/td&gt;
          &lt;td&gt;Demystifying positional encodings.](https://www.youtube.com/watch?v=1biZfFLPRSY) — AI Coffee Break with Letitia, English. Positional encodings, the piece a bag of tokens otherwise lacks.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>08 The Transformer Architecture</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter08/08_00_Introduction</id>
   <content type="html">&lt;p&gt;In June 2017, eight researchers published a 15-page paper with a disarmingly bold title: &lt;em&gt;Attention Is All You Need&lt;/em&gt;. Until that moment, attention was merely an accessory bolted onto LSTM encoders and decoders. Vaswani et al. ripped out every single recurrent loop and convolutional filter, leaving an architecture built purely from &lt;strong&gt;multi-head attention&lt;/strong&gt;, &lt;strong&gt;position-wise MLPs&lt;/strong&gt;, &lt;strong&gt;residual connections&lt;/strong&gt;, &lt;strong&gt;LayerNorm&lt;/strong&gt;, and &lt;strong&gt;positional encodings&lt;/strong&gt;. The result trained in a fraction of the time on GPUs because every token in a sequence could be processed simultaneously—and within five years, that single blueprint gave rise to BERT, GPT, Vision Transformers, Whisper, and AlphaFold 2.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-architectural-anatomy-of-the-transformer&quot;&gt;Key ideas: The Architectural Anatomy of the Transformer&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Recurrence-Free Parallelism&lt;/strong&gt;: Eliminating \(h_{t-1} \to h_t\) sequential dependencies allows all \(T\) tokens to flow through matrix multiplications simultaneously during training, unlocking massive GPU/TPU scaling laws.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Positional Information Injection&lt;/strong&gt;: Because self-attention is permutation-equivariant (treating inputs as a bag of vectors), Transformers must explicitly inject token order via sinusoidal, learned, or rotary (RoPE) positional encodings.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Three Attention Slots&lt;/strong&gt;: The original encoder–decoder Transformer uses (1) &lt;strong&gt;bidirectional encoder self-attention&lt;/strong&gt;, (2) &lt;strong&gt;causal masked decoder self-attention&lt;/strong&gt;, and (3) &lt;strong&gt;encoder–decoder cross-attention&lt;/strong&gt;—and slicing these blocks yields Encoder-only (BERT), Decoder-only (GPT), and Encoder–Decoder (T5) families.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Residual Stream + Feed-Forward Memory&lt;/strong&gt;: Modern interpretability views the residual pathway \(x \leftarrow x + \text{Attn}(\text{LN}(x))\), \(x \leftarrow x + \text{FFN}(\text{LN}(x))\) as a shared communication bus where attention &lt;em&gt;moves&lt;/em&gt; information between tokens and the FFN &lt;em&gt;processes/stores&lt;/em&gt; factual knowledge per token.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-positional-encoding-is-strictly-necessary&quot;&gt;Worked example: Why Positional Encoding Is Strictly Necessary&lt;/h3&gt;

&lt;p&gt;Suppose an unpositioned self-attention layer receives the two 2-token sentences:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Sentence A: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;dog bites&quot;&lt;/code&gt; \(\to X_A = \begin{bmatrix} v_{\text{dog}} \\ v_{\text{bites}} \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;Sentence B: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;bites dog&quot;&lt;/code&gt; \(\to X_B = P X_A = \begin{bmatrix} v_{\text{bites}} \\ v_{\text{dog}} \end{bmatrix}\), where \(P = \begin{bmatrix} 0 &amp;amp; 1 \\ 1 &amp;amp; 0 \end{bmatrix}\) is the swap permutation matrix.&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Transform Q, K, V under permutation \(P\)&lt;/strong&gt;:
\(Q_B = P Q_A,\quad K_B = P K_A,\quad V_B = P V_A.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute attention scores for Sentence B&lt;/strong&gt;:
\(Q_B K_B^\top = (P Q_A)(P K_A)^\top = P (Q_A K_A^\top) P^\top.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply row-wise softmax and multiply by \(V_B\)&lt;/strong&gt; (using \(P^\top P = I\)):
\(\operatorname{Attn}(X_B) = P \operatorname{softmax}\!\left(\frac{Q_A K_A^\top}{\sqrt{d_k}}\right) P^\top P V_A = P \operatorname{Attn}(X_A).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;: Without positional encodings (or a causal mask), the output vector for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;dog&quot;&lt;/code&gt; in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;dog bites&quot;&lt;/code&gt; is &lt;strong&gt;bit-for-bit identical&lt;/strong&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;dog&quot;&lt;/code&gt; in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;bites dog&quot;&lt;/code&gt;—proving algebraically why positional encoding is mandatory!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;chapter-08--the-transformer-architecture&quot;&gt;Chapter 08 — The Transformer Architecture&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/transformer_architecture.png&quot; alt=&quot;Transformer Architecture&quot; /&gt;
&lt;em&gt;Full Transformer (encoder–decoder) from “Attention Is All You Need.” Source: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;why-this-chapter-exists&quot;&gt;Why this chapter exists&lt;/h2&gt;

&lt;p&gt;Chapter 07 built &lt;strong&gt;attention&lt;/strong&gt; as a general mechanism: soft lookup with queries, keys, and values. The Transformer takes that idea to its logical extreme: &lt;strong&gt;almost the entire architecture is attention&lt;/strong&gt;, plus small position-wise MLPs, residuals, and normalization.&lt;/p&gt;

&lt;p&gt;That design choice solved three chronic problems of RNN sequence models at once:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Parallelism&lt;/strong&gt; — all positions process in one matrix-parallel step (no left-to-right loop at training time).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Long-range paths&lt;/strong&gt; — any token can influence any other token in a single layer (\(O(1)\) path length).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scalability&lt;/strong&gt; — the same block stacks cleanly to tens or hundreds of layers and transfers across tasks.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The result is the dominant template of modern AI: BERT-style encoders, GPT-style decoders, T5-style encoder–decoders, Vision Transformers, and many multimodal systems.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/sa_transformer_multihead_overview.jpg&quot; alt=&quot;Transformer overview + Multi-Head&quot; /&gt;
&lt;em&gt;Figure: Encoder–decoder with multi-head attention (several scaled-dot-product heads in parallel). (Illustration from an intro Transformer / Self-Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Link to Chapter 18 (word embeddings):&lt;/strong&gt; Word2Vec/GloVe assign &lt;strong&gt;one&lt;/strong&gt; fixed vector per word type. Transformers/BERT produce &lt;strong&gt;contextual&lt;/strong&gt; representations — the same token “Apple” (fruit vs company) gets different vectors depending on the sentence. Attention (Chapters 07–08) is the mechanism that mixes that context.&lt;/p&gt;

&lt;h3 id=&quot;three-attention-slots-in-the-encoderdecoder&quot;&gt;Three attention slots in the encoder–decoder&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/tf_masked_mha_highlight.jpg&quot; alt=&quot;Masked MHA on the decoder&quot; /&gt;
&lt;em&gt;Figure: &lt;strong&gt;Masked multi-head attention&lt;/strong&gt; — the decoder must not see future tokens. (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/tf_cross_vs_masked_labels.jpg&quot; alt=&quot;Cross vs Masked&quot; /&gt;
&lt;em&gt;Figure: &lt;strong&gt;Cross-attention&lt;/strong&gt; (K,V from encoder, Q from decoder) vs &lt;strong&gt;masked self-attention&lt;/strong&gt;. (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/tf_cross_attn_kv_from_encoder.jpg&quot; alt=&quot;Cross-attention: K,V from encoder&quot; /&gt;
&lt;em&gt;Figure: K/V flow from the encoder into the decoder via cross-attention. (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Positional encoding (PE):&lt;/strong&gt; self-attention is order-blind if it only sees token content. Sin-cos PE gives each \(pos\) a multi-frequency vector, then &lt;strong&gt;adds&lt;/strong&gt; it to the token embedding — full step-by-step (\(pos\), \(i\), sin/cos, \(d=512\)) in the Transformer Theory lesson.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/pe_input_emb_vs_positional.jpg&quot; alt=&quot;Input embedding + positional encoding&quot; /&gt;
&lt;em&gt;Figure: Same \(d_{\mathrm{model}}\) width — elementwise sum before the stack. (Illustration from a Position Encoding video)&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;learning-goals&quot;&gt;Learning goals&lt;/h2&gt;

&lt;p&gt;By the end of this chapter you should be able to:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Draw the &lt;strong&gt;encoder stack&lt;/strong&gt;, &lt;strong&gt;decoder stack&lt;/strong&gt;, and data flow between them.&lt;/li&gt;
  &lt;li&gt;Explain &lt;strong&gt;self-attention&lt;/strong&gt;, &lt;strong&gt;masked self-attention&lt;/strong&gt;, and &lt;strong&gt;cross-attention&lt;/strong&gt; roles.&lt;/li&gt;
  &lt;li&gt;Derive and implement &lt;strong&gt;positional encodings&lt;/strong&gt; (why pure attention is order-blind).&lt;/li&gt;
  &lt;li&gt;Write the equations for a full &lt;strong&gt;Transformer layer&lt;/strong&gt; (attention + FFN + residual + norm).&lt;/li&gt;
  &lt;li&gt;Implement a small Transformer in PyTorch with correct masks and shapes.&lt;/li&gt;
  &lt;li&gt;Name the core papers (Vaswani, BERT, GPT-2, ViT) and common training/inference pitfalls (warmup, KV-cache, quadratic cost).&lt;/li&gt;
  &lt;li&gt;Use &lt;strong&gt;Transformer Explainer&lt;/strong&gt; to inspect embeddings, attention weights, temperature, and sampling on a live GPT-2 model in the browser.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;roadmap&quot;&gt;Roadmap&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Lesson&lt;/th&gt;
      &lt;th&gt;Focus&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-01 Architecture (overview)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Map of theory vs implementation&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-01-01 Theory&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Self-attention in the full model, PE, encoder/decoder layers&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02 Implementation (overview)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Checklist and module map&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02-01 Core code&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Building blocks from scratch&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-01-02-02 Demos, papers, pitfalls&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Toy training, literature, debugging&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;08-02 Transformer Explainer&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Interactive in-browser GPT-2 visualization&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Chapter 07 attention (scaled dot-product, multi-head, causal/padding masks)&lt;/li&gt;
  &lt;li&gt;Residuals and LayerNorm at a conceptual level&lt;/li&gt;
  &lt;li&gt;Softmax, embeddings, basic PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Module&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;mental-model&quot;&gt;Mental model&lt;/h2&gt;

&lt;p&gt;Think of a Transformer layer as two operators stacked repeatedly:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Communicate&lt;/strong&gt; — multi-head attention mixes information across positions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute&lt;/strong&gt; — a position-wise feed-forward network transforms each position independently.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Order is injected once (or continuously, in relative-PE variants) so that “who talks to whom” can depend on sequence structure, not only on content.&lt;/p&gt;

&lt;p&gt;When you can walk through &lt;em&gt;one&lt;/em&gt; encoder layer and &lt;em&gt;one&lt;/em&gt; decoder step with masks drawn on paper, you are ready for the theory and code lessons that follow.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/930207546288223&quot;&gt;What is a Transformer? Self-Attention for beginners (Part 1)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1007473105556936&quot;&gt;Attention in Transformers (Self, Masked, Cross, Multi-Head)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1306224801415127&quot;&gt;Position Encoding in Transformers (step by step)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1501843101324752&quot;&gt;Word embeddings and how Transformers understand language&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Interactive visualization:&lt;/strong&gt; After the theory and demos, use &lt;strong&gt;08-02 Transformer Explainer&lt;/strong&gt; to walk a live GPT-2 (small) model in the browser: tokenization, attention heads, temperature, and top-k / top-p sampling.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After the Transformer architecture notes, see &lt;strong&gt;08-99 Modern Applications and Updates&lt;/strong&gt; for RoPE, KV-cache, open LLMs, and serving stacks (vLLM, llama.cpp).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dedicated LLM track:&lt;/strong&gt; When you can walk one decoder layer and one decode step, continue in &lt;strong&gt;Chapter 26&lt;/strong&gt; (Large Language Models) for pretraining, prompting, alignment, serving, distillation, and the modern-block / FLOP sketch in &lt;strong&gt;26-07&lt;/strong&gt;. Chapter 08 stays the architecture derivation; Chapter 26 is the product-scale hub.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. The transformer block (attention, then MLP) is this chapter.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zxQyTK8quyY&quot;&gt;Transformer Neural Networks, ChatGPT’s foundation, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. A fully labeled walk through the same block.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dqoEU9Ac3ek&quot;&gt;MIT 6.S191 (2024): Recurrent Neural Networks, Transformers, and Attention&lt;/a&gt; — Alexander Amini, English. The MIT lecture that arrives at the transformer from RNNs.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Standard attention looks effortless on a whiteboard, yet at sequence length \(T = 32{,}768\), materializing the \(T \times T\) score matrix in GPU High-Bandwidth Memory (HBM) consumes gigabytes of VRAM per head and stalls Tensor Cores waiting on memory reads. Between 2022 and 2026, systems breakthroughs—&lt;strong&gt;FlashAttention&lt;/strong&gt; (IO-aware tiling + online softmax), &lt;strong&gt;PagedAttention&lt;/strong&gt; (virtual memory for KV-caches), and &lt;strong&gt;Grouped-Query Attention (GQA)&lt;/strong&gt;—rewrote how attention executes on silicon, making 128K–1M-token LLMs practical without changing a single mathematical digit of exact attention.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-io-aware-kernels-kv-cache-compression-and-long-context&quot;&gt;Key ideas: IO-Aware Kernels, KV-Cache Compression, and Long Context&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;FlashAttention (Online Softmax Tiling)&lt;/strong&gt;: GPU SRAM is \(&amp;gt;10\times\) faster than HBM but tiny (~20 MB). FlashAttention streams blocks of \(Q, K, V\) into SRAM and computes exact softmax incrementally using running max and normalizer statistics—reducing HBM memory from \(O(T^2)\) to \(O(T)\) while cutting wall-clock time \(2\times\text{–}4\times\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;KV-Cache Memory Wall &amp;amp; GQA/MQA&lt;/strong&gt;: During autoregressive decoding, caching past \(K, V\) tensors dominates GPU memory. &lt;strong&gt;Multi-Query Attention (MQA)&lt;/strong&gt; shares 1 KV head across all query heads; &lt;strong&gt;Grouped-Query Attention (GQA)&lt;/strong&gt; shares \(h_{\text{kv}}\) KV heads across groups of \(h_q / h_{\text{kv}}\) query heads (e.g., Llama 3), slashing KV-cache size by \(4\times\text{–}8\times\) with near-zero quality loss.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;PagedAttention (vLLM)&lt;/strong&gt;: Borrowing virtual memory paging from operating systems, PagedAttention stores KV-caches in non-contiguous fixed-size blocks, eliminating memory fragmentation and enabling dynamic batching and shared-prefix caching.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sliding-Window &amp;amp; Sparse Attention&lt;/strong&gt;: Restricting local layers to a window \(W\) (e.g., Mistral’s 4K sliding window) bounds attention compute to \(O(T \cdot W)\) while stacked layers still propagate information globally.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-kv-cache-memory-savings-of-gqa-vs-mha&quot;&gt;Worked example: KV-Cache Memory Savings of GQA vs. MHA&lt;/h3&gt;

&lt;p&gt;Consider a 32-layer LLM with \(d_{\text{model}} = 4{,}096\), \(h_q = 32\) query heads (\(d_k = 128\)), context length \(T = 8{,}192\) tokens, stored in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bf16&lt;/code&gt; (2 bytes per element) for a single request:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standard Multi-Head Attention (MHA: \(h_{\text{kv}} = 32\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Per layer, K and V each store \(T \times h_{\text{kv}} \times d_k = 8{,}192 \times 32 \times 128 = 33{,}554{,}432\) elements.&lt;/li&gt;
      &lt;li&gt;Both K and V in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bf16&lt;/code&gt;: \(2 \times 33{,}554{,}432 \times 2\text{ bytes} = 134{,}217{,}728\text{ bytes} = 128\text{ MiB/layer}\).&lt;/li&gt;
      &lt;li&gt;Across 32 layers: \(32 \times 128\text{ MiB} = 4{,}096\text{ MiB} = 4.0\text{ GiB}\) for just &lt;em&gt;one&lt;/em&gt; user sequence!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Grouped-Query Attention (GQA with \(h_{\text{kv}} = 8\), group size 4)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;KV heads drop by \(4\times\) (\(32 \to 8\)).&lt;/li&gt;
      &lt;li&gt;Total KV-cache across 32 layers: \(4.0\text{ GiB} / 4 = 1.0\text{ GiB}\)—immediately allowing \(4\times\) larger serving batch sizes on the exact same GPU!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-attention-kernels-serving-and-multi-query-variants&quot;&gt;Optional: attention kernels, serving, and multi-query variants&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace scaled-dot-product or multi-head math. It covers the systems and architectural variants that made attention deployable at LLM scale.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The score is still&lt;/p&gt;

\[\mathrm{Attn}(Q,K,V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d}}\right)V.\]

&lt;p&gt;From 2022 to 2026 the fight moved to &lt;strong&gt;IO&lt;/strong&gt;, &lt;strong&gt;KV-cache layout&lt;/strong&gt;, and &lt;strong&gt;fewer key/value heads&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;1-flashattention-exact-attention-better-memory-traffic&quot;&gt;1. FlashAttention: exact attention, better memory traffic&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;Dao et al., 2022&lt;/a&gt; tile \(Q,K,V\) so the \(T\times T\) matrix never sits in HBM. &lt;a href=&quot;https://arxiv.org/abs/2307.08691&quot;&gt;FlashAttention-2&lt;/a&gt; (2023) improves parallelism; &lt;a href=&quot;https://arxiv.org/abs/2407.08608&quot;&gt;FlashAttention-3&lt;/a&gt; (2024) targets Hopper (asynchrony + FP8). PyTorch’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scaled_dot_product_attention&lt;/code&gt; dispatches to these kernels when shapes allow.&lt;/p&gt;

&lt;p&gt;This is the same softmax as the theory lesson. The novelty is the &lt;strong&gt;algorithmic implementation&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;pagedattention-and-llm-serving&quot;&gt;PagedAttention and LLM serving&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2309.06180&quot;&gt;Kwon et al., 2023&lt;/a&gt; (vLLM) store the KV cache in paged blocks so many decoded sequences can share GPU memory without reservation waste. That is attention &lt;em&gt;serving&lt;/em&gt;, not a new score function.&lt;/p&gt;

&lt;h3 id=&quot;gqa--mqa&quot;&gt;GQA / MQA&lt;/h3&gt;

&lt;p&gt;Multi-query (&lt;a href=&quot;https://arxiv.org/abs/1911.02150&quot;&gt;Shazeer, 2019&lt;/a&gt;) and grouped-query attention (&lt;a href=&quot;https://arxiv.org/abs/2305.13245&quot;&gt;Ainslie et al., 2023&lt;/a&gt;, GQA) let many query heads share one or a few KV heads. Llama 2/3 and Mistral use GQA so the cache is&lt;/p&gt;

\[\text{KV bytes} \propto T \cdot n_{\text{kv}} \cdot d, \quad n_{\text{kv}} \ll n_{\text{heads}}.\]

&lt;h3 id=&quot;sliding-window-and-linear-attention&quot;&gt;Sliding-window and linear attention&lt;/h3&gt;

&lt;p&gt;Mistral-style &lt;strong&gt;sliding-window&lt;/strong&gt; attention and various linear-attention papers trade the full \(T\times T\) pattern for \(O(T)\) cost. Use them when the Chapter 07 quadratic warning becomes a product constraint.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;F.scaled_dot_product_attention&lt;/code&gt; (SDPA) / &lt;a href=&quot;https://github.com/Dao-AILab/flash-attention&quot;&gt;FlashAttention&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt; — PagedAttention serving.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/xformers&quot;&gt;xFormers&lt;/a&gt; — memory-efficient attention ops.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;FlashAttention (Dao et al., 2022)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2307.08691&quot;&gt;FlashAttention-2 (Dao, 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2407.08608&quot;&gt;FlashAttention-3 (Shah et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2309.06180&quot;&gt;Efficient Memory Management for Large Language Model Serving with PagedAttention (Kwon et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.13245&quot;&gt;GQA: Training Generalized Multi-Query Transformer Models (Ainslie et al., 2023)&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Write the NumPy attention and multi-head pitfalls first. This lesson only adds &lt;strong&gt;kernels, KV-cache, and GQA&lt;/strong&gt; — the products you will meet in every LLM codebase. Chapter &lt;strong&gt;26-07&lt;/strong&gt; retells FlashAttention as tiling + online softmax (no CUDA) and puts GQA next to the decoder-block diagram; &lt;strong&gt;26-04&lt;/strong&gt; is the serving-time KV-cache.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=gBMO1JZav44&quot;&gt;How FlashAttention Accelerates Generative AI Revolution&lt;/a&gt; — Jia-Bin Huang, English. FlashAttention computes the same attention with less memory traffic, which is this note’s claim.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[FlashAttention - Tri Dao&lt;/td&gt;
          &lt;td&gt;Stanford MLSys #67](https://www.youtube.com/watch?v=gMOAud7hZg4) — Stanford MLSys Seminars, English. Tri Dao’s own seminar on that algorithm. It is long and canonical; use it after the short version.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, English. The exact attention formula FlashAttention is not approximating away.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-02-02 Attention Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_02_02_Attention_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_02_02_Attention_Implementation</id>
   <content type="html">&lt;p&gt;Implementing attention cleanly is where conceptual clarity meets production engineering. This implementation hub links the core single-head &amp;amp; Bahdanau reference implementations with full multi-head PyTorch modules, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.MultiheadAttention&lt;/code&gt; API comparisons, and a pre-flight debugging checklist covering shapes, masks, scaling, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; guards.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-attention-engineering-checklist&quot;&gt;Key ideas: Attention Engineering Checklist&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Shape Discipline&lt;/strong&gt;: Consistently tracking &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, h, T_q, d_k)&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, h, T_k, d_k)&lt;/code&gt; across self-attention (\(T_q = T_k\)) and cross-attention (\(T_q \ne T_k\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mask Semantics&lt;/strong&gt;: Verifying whether a framework API expects &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;True = masked/ignored&lt;/code&gt; (PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;key_padding_mask&lt;/code&gt;) or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1 = keep&lt;/code&gt; (custom teaching code) before training.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Built-in vs. Teaching Modules&lt;/strong&gt;: Reconciling your transparent teaching code with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.MultiheadAttention&lt;/code&gt; and PyTorch’s fused &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;F.scaled_dot_product_attention&lt;/code&gt; (which automatically dispatches FlashAttention on modern GPUs).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-catching-the-silent-viewb-h-t-d_k-bug&quot;&gt;Worked example: Catching the Silent &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.view(B, h, T, d_k)&lt;/code&gt; Bug&lt;/h3&gt;

&lt;p&gt;Suppose \(B = 1, T = 2, h = 2, d_k = 2\) (\(d_{\text{model}} = 4\)) and token embeddings are:
\(\text{Token 0} = [1, 2, 3, 4], \quad \text{Token 1} = [5, 6, 7, 8].\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Correct split (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view(1, 2, 2, 2).transpose(1, 2)&lt;/code&gt;)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Head 0 sees: Token 0 \(= [1, 2]\), Token 1 \(= [5, 6]\).&lt;/li&gt;
      &lt;li&gt;Head 1 sees: Token 0 \(= [3, 4]\), Token 1 \(= [7, 8]\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Buggy split (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view(1, 2, 2, 2)&lt;/code&gt; directly without transpose)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Head 0 gets &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[[1, 2], [3, 4]]&lt;/code&gt; (both from Token 0!) and Head 1 gets &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[[5, 6], [7, 8]]&lt;/code&gt; (both from Token 1!)—completely mixing sequence positions with feature channels without throwing any Python exception!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;07-02-02-attention-implementation&quot;&gt;07-02-02 Attention Implementation&lt;/h1&gt;

&lt;p&gt;Mathematics tells you &lt;em&gt;what&lt;/em&gt; attention computes. Implementation tells you whether you actually built that object—shapes, masks, stability, and APIs included.&lt;/p&gt;

&lt;h2 id=&quot;lessons-in-this-section&quot;&gt;Lessons in this section&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Core Implementation&lt;/strong&gt;&lt;br /&gt;
Bahdanau attention from scratch, scaled self-attention, translation-style demos, and a clear NumPy → PyTorch path.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Multi-Head, Papers, and Pitfalls&lt;/strong&gt;&lt;br /&gt;
Multi-head modules, causal masking, a minimal seq2seq-with-attention sketch, canonical papers, and a debugging checklist used in real training runs.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;implementation-checklist-keep-this-open-while-coding&quot;&gt;Implementation checklist (keep this open while coding)&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Check&lt;/th&gt;
      &lt;th&gt;Why it matters&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Softmax over the &lt;strong&gt;key&lt;/strong&gt; axis&lt;/td&gt;
      &lt;td&gt;Weights must form a distribution over memory slots&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Scale by \(\sqrt{d_k}\)&lt;/td&gt;
      &lt;td&gt;Prevents saturated attention at large width&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mask &lt;strong&gt;before&lt;/strong&gt; softmax with large negatives&lt;/td&gt;
      &lt;td&gt;Correct zeros + correct gradients&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Causal mask for autoregressive decoders&lt;/td&gt;
      &lt;td&gt;Stops future leakage&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Padding mask in batched training&lt;/td&gt;
      &lt;td&gt;Stops attending to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PAD&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Multi-head reshape: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B,L,H,d)&lt;/code&gt; ↔ &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B,H,L,d)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Wrong transpose silently scrambles features&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Start with &lt;strong&gt;Core Implementation&lt;/strong&gt;, then continue to multi-head and pitfalls.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, English. So the code lessons are implementing a formula you have already computed once.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mmzRYGCfTzc&quot;&gt;A Dive Into Multihead Attention, Self-Attention and Cross-Attention&lt;/a&gt; — Machine Learning Studio, English. The module map: self, cross, and multi-head.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, English. Attention written in Python, which is the coding lesson’s target.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-02-02-02 Multi-Head Attention, Papers, and Pitfalls</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_02_02_02_MultiHead_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_02_02_02_MultiHead_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Single-head attention has a subtle blind spot: because a single softmax outputs one weighted average across all tokens, trying to attend simultaneously to a pronoun’s grammatical subject &lt;em&gt;and&lt;/em&gt; its adjacent verb averages their two value vectors into an ambiguous blur. &lt;strong&gt;Multi-Head Attention&lt;/strong&gt; solves this by projecting the same \(d_{\text{model}}\) representation into \(h\) independent low-dimensional subspaces—so Head 1 can track subject–verb agreement, Head 2 can track coreference, and Head 3 can track local punctuation—all in parallel for the exact same total FLOPs as one big head!&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-multi-head-attention-mechanics--common-pitfalls&quot;&gt;Key ideas: Multi-Head Attention Mechanics &amp;amp; Common Pitfalls&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Parallel Subspace Projections&lt;/strong&gt;: Instead of one \(d_{\text{model}}\)-wide attention pass, splitting into \(h\) heads of dimension \(d_k = d_{\text{model}}/h\) lets each head learn its own similarity metric \(W_Q^{(i)} (W_K^{(i)})^\top\) while keeping total projection parameters fixed at \(4 d_{\text{model}}^2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Critical &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transpose&lt;/code&gt; Ordering&lt;/strong&gt;: To split heads in PyTorch, you MUST reshape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, T, d_model) -&amp;gt; (B, T, h, d_k)&lt;/code&gt; &lt;em&gt;first&lt;/em&gt; and then &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transpose(1, 2) -&amp;gt; (B, h, T, d_k)&lt;/code&gt;. Calling &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.view(B, h, T, d_k)&lt;/code&gt; directly scrambles tokens across heads without raising an error!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;All-Masked Row &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; Pitfall&lt;/strong&gt;: If a padding mask hides &lt;em&gt;every&lt;/em&gt; key in a row (e.g., an all-pad dummy sequence), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softmax([-inf, -inf, ...])&lt;/code&gt; evaluates to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0/0 = NaN&lt;/code&gt; and poisons gradients across the entire batch.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Attention Dropout Placement&lt;/strong&gt;: Dropout is applied to the &lt;em&gt;attention probability weights&lt;/em&gt; (after softmax, before multiplying by \(V\)) and again after the output projection \(W_O\)—preventing heads from co-adapting to a single deterministic token.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-proving-multi-head-has-the-same-projection-parameters-as-single-head&quot;&gt;Worked example: Proving Multi-Head Has the Same Projection Parameters as Single-Head&lt;/h3&gt;

&lt;p&gt;Let \(d_{\text{model}} = 512\) and compare \(h = 1\) head (\(d_k = 512\)) against \(h = 8\) heads (\(d_k = 64\)), omitting biases for clarity:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Single-head projection matrices&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(W_Q, W_K, W_V, W_O\) are each \(512 \times 512 = 262{,}144\) weights.&lt;/li&gt;
      &lt;li&gt;Total: \(4 \times 262{,}144 = 1{,}048{,}576\) weights.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;8-head projection matrices&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Each head \(i \in \{1, \dots, 8\}\) has \(W_Q^{(i)}, W_K^{(i)}, W_V^{(i)} \in \mathbb{R}^{512 \times 64}\), which is \(3 \times 512 \times 64 = 98{,}304\) weights per head.&lt;/li&gt;
      &lt;li&gt;Across all 8 heads: \(8 \times 98{,}304 = 786{,}432\) weights (identical to fused \(W_Q, W_K, W_V \in \mathbb{R}^{512 \times 512}\)!).&lt;/li&gt;
      &lt;li&gt;Plus output mixer \(W_O \in \mathbb{R}^{512 \times 512} = 262{,}144\) weights.&lt;/li&gt;
      &lt;li&gt;Total: \(786{,}432 + 262{,}144 = 1{,}048{,}576\) weights — &lt;strong&gt;zero extra parameters&lt;/strong&gt; for \(8\times\) richer relational specialization!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;multi-head-attention-papers-and-pitfalls&quot;&gt;Multi-Head Attention, Papers, and Pitfalls&lt;/h1&gt;

&lt;p&gt;You can implement single-head attention and still miss what makes Transformers work in practice: &lt;strong&gt;several attention patterns in parallel&lt;/strong&gt;, correct packaging of heads, causal decoding, and the failure modes that appear only after you scale up. This lesson completes the implementation track.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Multi-head attention is not “attention but slower.” It is a capacity mechanism: each head uses its own projections \((W_h^Q, W_h^K, W_h^V)\), so each head can learn a different similarity notion and a different soft routing over positions. Concatenating heads preserves those channels; the output matrix \(W^O\) mixes them into the model dimension.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter08/tf_full_arch_multihead_zoom.jpg&quot; alt=&quot;Transformer architecture + Multi-Head / Scaled Dot-Product zoom&quot; /&gt;
&lt;em&gt;Figure: Multi-head = several Linear(Q,K,V) branches → scaled attention → concat → Linear. (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_multihead_dk_split.jpg&quot; alt=&quot;$$d_k = d_{\mathrm{model}}/H$$&quot; /&gt;
&lt;em&gt;Figure: Example \(512/8=64\) — width per head. (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_multihead_output_stack.jpg&quot; alt=&quot;Multi-head output stack&quot; /&gt;
&lt;em&gt;Figure: Concat heads before linear \(W^O\). (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Operationally, multi-head attention is:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Project \(\mathbf{X}\) to Q, K, V in full \(d_{\mathrm{model}}\).&lt;/li&gt;
  &lt;li&gt;Reshape to \((B, H, L, d_k)\) with \(d_k=d_{\mathrm{model}}/H\).&lt;/li&gt;
  &lt;li&gt;Run scaled attention &lt;strong&gt;per head&lt;/strong&gt; (batched).&lt;/li&gt;
  &lt;li&gt;Merge heads → \((B, L, d_{\mathrm{model}})\).&lt;/li&gt;
  &lt;li&gt;Final linear map \(W^O\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Get the reshape/transpose wrong and shapes still look right while information is scrambled—hence the tests below.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

\[\mathrm{head}_h = \mathrm{Attention}(X W_h^Q,\ X W_h^K,\ X W_h^V)\]

\[\mathrm{MultiHead}(X)=\mathrm{Concat}_h(\mathrm{head}_h)\,W^O\]

&lt;p&gt;With shared big matrices (common in code), one projects to \(d_{\mathrm{model}}\) once, then &lt;strong&gt;views&lt;/strong&gt; the last dimension as \(H \times d_k\):&lt;/p&gt;

\[Q = X W^Q \in \mathbb{R}^{B\times L\times (H d_k)}
\ \xrightarrow{\text{reshape/transpose}}\ 
\mathbb{R}^{B\times H\times L\times d_k}.\]

&lt;p&gt;Causal decoding uses&lt;/p&gt;

\[M_{ij}=\begin{cases}0 &amp;amp; j\le i\\ -\infty &amp;amp; j&amp;gt;i\end{cases}\]

&lt;p&gt;added to scores inside every head (same mask broadcast across heads).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;On a sentence like “The cat sat,” different heads often specialize after training:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Head A: local bigrams (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cat&lt;/code&gt;↔&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;The&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sat&lt;/code&gt;↔&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cat&lt;/code&gt;)&lt;/li&gt;
  &lt;li&gt;Head B: weakly syntactic (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sat&lt;/code&gt; attends subject &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cat&lt;/code&gt;)&lt;/li&gt;
  &lt;li&gt;Head C: almost positional (strong diagonal)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You do not program these roles; separate parameters + multi-task pressure from the loss encourage diversity. Visualization of per-head maps is the practical way to see specialization.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;h3 id=&quot;41-multi-head-self-attention-pytorch-teaching-version&quot;&gt;4.1 Multi-head self-attention (PyTorch, teaching version)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadSelfAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wqkv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;drop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# (B, L, d) -&amp;gt; (B, H, L, dk)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# (B, H, L, dk) -&amp;gt; (B, L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;contiguous&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (B, L, d_model)
        attn_mask: additive mask broadcastable to (B, 1, L, L) or (B, H, L, L)
                   0 = keep, -inf = forbid
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;qkv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wqkv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, L, 3d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;qkv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;chunk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;drop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, H, L, L)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;build_causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# (1, 1, L, L) for broadcasting over batch and heads
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;full&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-inf&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;device&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;diagonal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Smoke test
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadSelfAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;build_causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;diagonal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;atol&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;multi-head causal OK&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;42-using-the-built-in-module&quot;&gt;4.2 Using the built-in module&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;official&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MultiheadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embed_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# key_padding_mask: (B, L) True = ignore (padding)
# attn_mask: (L, L) True/float mask depending on version — read docs carefully
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;official&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;average_attn_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Always double-check the mask convention for your PyTorch version (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bool&lt;/code&gt; vs additive float).&lt;/p&gt;

&lt;h3 id=&quot;43-minimal-seq2seq-with-attention-sketch&quot;&gt;4.3 Minimal seq2seq-with-attention sketch&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Seq2SeqWithAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Tiny educational encoder-decoder:
    - encoder GRU over source embeddings
    - decoder GRU step
    - Luong-style dot attention over encoder outputs
    Not production NMT; shapes are the lesson.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;src_vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt_vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;src_emb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;src_vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tgt_emb&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Embedding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tgt_vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;GRU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;GRU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt_vocab&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;attend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dec_h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# dec_h: (B, 1, d), enc_out: (B, Ls, d)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# scores: (B, 1, Ls)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dec_h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (B, 1, d)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;src&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# src: (B, Ls), tgt: (B, Lt)  — teacher forcing inputs
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;encoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;src_emb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;src&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dec_in&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tgt_emb&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dec_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;decoder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dec_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# attend each decoder position to encoder (batched)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dec_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# (B, Lt, Ls)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;enc_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;# (B, Lt, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dec_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ctx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Seq2SeqWithAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;120&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;src&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;120&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;src&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2,3,120), (2,3,4)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;44-visualizing-one-head-optional&quot;&gt;4.4 Visualizing one head (optional)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;plot_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_labels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Attention&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;weights_2d: (Lq, Lk) numpy array&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;figure&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;imshow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights_2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;aspect&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;auto&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;interpolation&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;nearest&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;colorbar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xticks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rotation&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;45&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;right&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_labels&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;yticks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Key positions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Query positions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example with the causal multi-head weights from above
# plot_attention(w[0, 0].detach().numpy())  # batch 0, head 0
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Residuals + LayerNorm&lt;/strong&gt; around multi-head blocks (Pre-LN vs Post-LN) dominate trainability.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Relative position bias&lt;/strong&gt; (T5, Shaw et al.) adds distance terms into scores.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-attention&lt;/strong&gt; in encoder–decoder Transformers reuses the same multi-head code with Q from decoder and K,V from encoder.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FlashAttention / SDPA&lt;/strong&gt; fuse the matmul-softmax-matmul for memory efficiency; math is unchanged.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sparse attention&lt;/strong&gt; (Longformer, BigBird) restricts the support of \(\alpha\) for long \(L\).&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Bahdanau et al., 2015&lt;/a&gt;&lt;/strong&gt; — &lt;em&gt;Neural Machine Translation by Jointly Learning to Align and Translate.&lt;/em&gt;&lt;br /&gt;
Foundational additive attention; decoder soft-searches source states. Established learned alignment without explicit supervision.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Luong et al., 2015&lt;/a&gt;&lt;/strong&gt; — &lt;em&gt;Effective Approaches to Attention-based NMT.&lt;/em&gt;&lt;br /&gt;
Multiplicative scores, global vs local attention, practical decoder tricks (input feeding).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1502.03044&quot;&gt;Xu et al., 2015&lt;/a&gt;&lt;/strong&gt; — &lt;em&gt;Show, Attend and Tell.&lt;/em&gt;&lt;br /&gt;
Visual attention for captioning; soft vs hard attention; multimodal generality of the idea.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Vaswani et al., 2017&lt;/a&gt;&lt;/strong&gt; — &lt;em&gt;Attention Is All You Need.&lt;/em&gt;&lt;br /&gt;
Multi-head scaled self-attention as the primary sequence operator; template for modern stacks.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1803.02155&quot;&gt;Shaw et al., 2018&lt;/a&gt;&lt;/strong&gt; — &lt;em&gt;Self-Attention with Relative Position Representations.&lt;/em&gt;&lt;br /&gt;
Relative distances inside attention logits; improves length generalization in many variants.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-common-pitfalls-and-tricks&quot;&gt;7. Common Pitfalls and Tricks&lt;/h2&gt;

&lt;h3 id=&quot;critical-bugs&quot;&gt;Critical bugs&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Softmax over the wrong axis&lt;/strong&gt; — must be the key/memory axis.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mask after softmax&lt;/strong&gt; — use additive &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt; on logits.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Forgetting \(1/\sqrt{d_k}\)&lt;/strong&gt; — sharp, low-gradient attention at large width.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Incorrect head reshape&lt;/strong&gt; — always test &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view → transpose → attention → transpose → view&lt;/code&gt; on a known tensor.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Padding leakage&lt;/strong&gt; — &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;key_padding_mask&lt;/code&gt; / explicit pad positions in every batched run.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Causal leakage&lt;/strong&gt; — unit-test upper triangle of weights is ~0.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dropout on scores vs weights&lt;/strong&gt; — know which your code path uses; keep train/eval modes consistent.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;debugging-checklist&quot;&gt;Debugging checklist&lt;/h3&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;[ ] Print shapes: Q,K,V,scores,weights,output
[ ] weights.sum(dim=keys) == 1
[ ] causal: triu(weights,1) == 0
[ ] pad positions: weights[..., pad] == 0
[ ] No NaNs after long runs (check scale + max-subtraction in custom softmax)
[ ] Gradient flows to Wq/Wk/Wv (hook or .grad after backward)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;practical-tricks&quot;&gt;Practical tricks&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Start with &lt;strong&gt;one head&lt;/strong&gt; and full attention; add heads only when single-head training is stable.&lt;/li&gt;
  &lt;li&gt;Log &lt;strong&gt;entropy of attention&lt;/strong&gt; per layer: near-zero entropy means collapse; very high may mean uniform noise.&lt;/li&gt;
  &lt;li&gt;For NMT-style models, visualize a few sentence pairs every epoch—broken masks show up immediately.&lt;/li&gt;
  &lt;li&gt;Prefer fused SDPA in production; keep a slow reference implementation for tests.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-key-takeaways&quot;&gt;8. Key Takeaways&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Multi-head attention = parallel soft routers + output mix&lt;/strong&gt;, not a cosmetic ensemble.&lt;/li&gt;
  &lt;li&gt;Packaging heads is a &lt;strong&gt;layout problem&lt;/strong&gt;; treat reshape tests as mandatory.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Causal and padding masks&lt;/strong&gt; are part of the algorithm’s definition in real systems.&lt;/li&gt;
  &lt;li&gt;Classic papers (Bahdanau → Luong → Vaswani) mark the path from RNN add-on to standalone architecture.&lt;/li&gt;
  &lt;li&gt;Most “attention is broken” bugs are &lt;strong&gt;axes, masks, or scale&lt;/strong&gt;—not optimizer magic.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You now have a complete path: fundamentals → mathematics → core code → multi-head practice. Chapter 08 will stack these blocks with feed-forward layers, residuals, and positional encodings into the full Transformer.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1806844676942638&quot;&gt;Attention formula: hand-compute Q, K, V&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1007473105556936&quot;&gt;Attention in Transformers (Self, Masked, Cross, Multi-Head)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=mmzRYGCfTzc&quot;&gt;A Dive Into Multihead Attention, Self-Attention and Cross-Attention&lt;/a&gt; — Machine Learning Studio, English. Multi-head is several attention maps, not a bigger single softmax.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, English. Masking, which is the pitfall section’s causal constraint.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, English. A coded causal mask, so the pitfall is visible as an indexing bug if you omit it.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-02-02-01 Attention Core Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_02_02_01_Attention_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_02_02_01_Attention_Core_Code</id>
   <content type="html">&lt;p&gt;Translating attention math into PyTorch code is a masterclass in numerical stability and broadcasting hygiene. A single missing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;keepdim=True&lt;/code&gt; in softmax, a mask applied &lt;em&gt;after&lt;/em&gt; softmax instead of &lt;em&gt;before&lt;/em&gt;, or an unshifted &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;exp(x)&lt;/code&gt; on large logits can silently produce &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;s or leak future tokens during autoregressive training. Building both a transparent loop-based Bahdanau module and a vectorized scaled dot-product function side by side guarantees you can spot every subtle tensor bug on sight.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-core-implementation-patterns-for-attention&quot;&gt;Key ideas: Core Implementation Patterns for Attention&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Numerically Stable Softmax (Log-Sum-Exp Shift)&lt;/strong&gt;: Subtracting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;row_max = scores.max(dim=-1, keepdim=True).values&lt;/code&gt; before exponentiation never changes the mathematical probabilities, yet prevents &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float16&lt;/code&gt; overflow when scores exceed ~88 (or ~11 in fp16).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mask Broadcasting &amp;amp; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;masked_fill&lt;/code&gt;&lt;/strong&gt;: Using boolean masks where &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;True&lt;/code&gt; marks forbidden positions (or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; marks padding) with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scores = scores.masked_fill(mask == 0, float(&quot;-inf&quot;))&lt;/code&gt; cleanly broadcasts across &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, 1, 1, T_k)&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, h, T_q, T_k)&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Loop-Based Bahdanau vs. Vectorized QKV&lt;/strong&gt;: Looping over decoder time steps makes Bahdanau alignment crystal clear for teaching, whereas &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.matmul(Q, K.transpose(-2, -1))&lt;/code&gt; unlocks full GPU parallelism.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Row-Sum Invariant Checks&lt;/strong&gt;: Asserting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.allclose(attn.sum(dim=-1), torch.ones(...))&lt;/code&gt; and inspecting masked entries (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;attn[mask == 0] == 0&lt;/code&gt;) are fast unit tests that catch 90% of attention implementation bugs immediately.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-subtracting-the-row-maximum-prevents-overflow&quot;&gt;Worked example: Why Subtracting the Row Maximum Prevents Overflow&lt;/h3&gt;

&lt;p&gt;Suppose a single attention row in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float16&lt;/code&gt; produces raw scores \(z = [100.0, 101.0, 99.0]\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Naive exponentiation&lt;/strong&gt;:
\(e^{100} \approx 2.69 \times 10^{43}\) — immediately overflows &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float16&lt;/code&gt; (max \(65{,}504\)) to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf&lt;/code&gt;, causing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf / inf = NaN&lt;/code&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Shift by row maximum \(m = \max(z) = 101.0\)&lt;/strong&gt;:
\(z&apos; = z - 101.0 = [-1.0,\; 0.0,\; -2.0].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exponentiate safely&lt;/strong&gt;:
\(e^{-1} \approx 0.3679,\quad e^0 = 1.0000,\quad e^{-2} \approx 0.1353,\quad Z&apos; = 1.5032.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Normalize&lt;/strong&gt;:
\(p = \left[\frac{0.3679}{1.5032},\; \frac{1.0000}{1.5032},\; \frac{0.1353}{1.5032}\right] \approx [0.2447,\; 0.6652,\; 0.0900].\)
Every intermediate value stayed strictly inside \((0, 1]\), eliminating overflow while returning the mathematically identical softmax distribution.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;attention-core-implementation&quot;&gt;Attention Core Implementation&lt;/h1&gt;

&lt;p&gt;This lesson turns the attention equations into &lt;strong&gt;working code&lt;/strong&gt;. We implement additive (Bahdanau) attention for encoder–decoder models and scaled self-attention in both NumPy and PyTorch, with explicit shapes and numerical-stability details.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;A correct attention implementation must do four things every time:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Build &lt;strong&gt;scores&lt;/strong&gt; between queries and keys.&lt;/li&gt;
  &lt;li&gt;Apply optional &lt;strong&gt;mask&lt;/strong&gt; on logits.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Softmax&lt;/strong&gt; over keys.&lt;/li&gt;
  &lt;li&gt;Multiply weights by &lt;strong&gt;values&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The rest is API design: classes vs functions, NumPy vs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn&lt;/code&gt;, batching, and multi-head packing (next lesson).&lt;/p&gt;

&lt;p&gt;We start with &lt;strong&gt;Bahdanau&lt;/strong&gt; because the loop over encoder states makes the algorithm obvious. Then we move to &lt;strong&gt;vectorized scaled attention&lt;/strong&gt;, which is what you will use in Transformers.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-mathematical-reminder-implementation-facing&quot;&gt;2. Mathematical Reminder (implementation-facing)&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Bahdanau score&lt;/strong&gt;&lt;/p&gt;

\[e_{i} = \mathbf{v}^\top \tanh(\mathbf{W}_h\mathbf{h}_i + \mathbf{W}_s\mathbf{s}).\]

&lt;p&gt;&lt;strong&gt;Scaled attention&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{A}=\mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}+\mathbf{M}\right),\quad
\mathbf{Y}=\mathbf{A}\mathbf{V}.\]

&lt;p&gt;&lt;strong&gt;Stable softmax&lt;/strong&gt; for a vector \(\mathbf{z}\):&lt;/p&gt;

\[\mathrm{softmax}(\mathbf{z})_i=\frac{\exp(z_i-\max_j z_j)}{\sum_j\exp(z_j-\max_j z_j)}.\]

&lt;p&gt;Always subtract the max on the softmax axis in handwritten code.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-example--intuition-for-the-demos&quot;&gt;3. Example / Intuition for the demos&lt;/h2&gt;

&lt;p&gt;We will simulate a tiny translation-like setting:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Source words: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;I love deep learning&lt;/code&gt; → four encoder states.&lt;/li&gt;
  &lt;li&gt;For each target word being generated, a decoder state queries those four states.&lt;/li&gt;
  &lt;li&gt;Printed attention weights show which source tokens receive mass.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Weights are random at initialization—the point of the demo is the &lt;strong&gt;plumbing&lt;/strong&gt;, not trained alignments. After you train a real model, the same printout becomes meaningful.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;h3 id=&quot;41-utilities&quot;&gt;4.1 Utilities&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax_last&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Softmax on the last axis with max-subtraction.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;42-bahdanau-attention-clear-loop-based&quot;&gt;4.2 Bahdanau attention (clear, loop-based)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BahdanauAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Additive attention for encoder-decoder models.

    decoder_state: (d,) or (d, 1)
    encoder_states: (L, d)   — one row per source position
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Ws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_dim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,))&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__call__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decoder_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;encoder_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;asarray&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;          &lt;span class=&quot;c1&quot;&gt;# (d,)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;asarray&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;encoder_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                    &lt;span class=&quot;c1&quot;&gt;# (L, d)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ndim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;

        &lt;span class=&quot;c1&quot;&gt;# scores[i] = v^T tanh(Wh h_i + Ws s)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;proj_h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;                            &lt;span class=&quot;c1&quot;&gt;# (L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;proj_s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Ws&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;                              &lt;span class=&quot;c1&quot;&gt;# (d,)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;proj_h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;proj_s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                      &lt;span class=&quot;c1&quot;&gt;# broadcast (L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;u&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;                               &lt;span class=&quot;c1&quot;&gt;# (L,)
&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax_last&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                      &lt;span class=&quot;c1&quot;&gt;# (L,)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;                               &lt;span class=&quot;c1&quot;&gt;# (d,)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;43-demo-soft-alignment-table&quot;&gt;4.3 Demo: soft alignment table&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;encoder_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;source&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;I&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;love&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;deep&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;learning&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;J&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;aime&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;apprentissage&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;profond&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BahdanauAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Target&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | attention over source&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;decoder_state&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decoder_state&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;encoder_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;join&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;source&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pairs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;isclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;context&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;44-scaled-self-attention-vectorized-numpy&quot;&gt;4.4 Scaled self-attention (vectorized NumPy)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Supports shapes:
      (Lq, d), (Lk, d), (Lk, dv)
      or batched (..., Lq, d), (..., Lk, d), (..., Lk, dv)
    mask: broadcastable boolean mask, True = forbidden key
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;swapaxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax_last&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Self-attention on a short sequence
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;no future mass:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;atol&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;45-pytorch-module-single-head-scaled-attention&quot;&gt;4.5 PyTorch module (single-head scaled attention)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ScaledDotProductAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Q,K,V: (B, L, d)  — single head for clarity
        attn_mask: additive mask broadcastable to (B, Lq, Lk)
                   use 0 for keep, -inf for forbid
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;matmul&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSelfAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ScaledDotProductAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, L, d)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Wv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# additive causal mask: (1, L, L)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;full&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-inf&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;diagonal&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleSelfAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2,7,32), (2,7,7)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;46-shape-debugger-use-this-when-stuck&quot;&gt;4.6 Shape debugger (use this when stuck)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;show_attn_shapes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tuple&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;scores expected&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;


&lt;span class=&quot;nf&quot;&gt;show_attn_shapes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# scores: (2, 5, 9)  — each of 5 queries attends over 9 keys
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Teacher forcing&lt;/strong&gt; in seq2seq: decoder receives gold previous tokens; attention still runs each step.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Input feeding&lt;/strong&gt; (Luong): feed previous context vector into the next decoder step—often helps NMT.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.MultiheadAttention&lt;/code&gt; / SDPA&lt;/strong&gt;: production kernels; understand this lesson before treating them as magic.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Batch packing&lt;/strong&gt;: padding masks are mandatory once batch size &amp;gt; 1 with variable lengths.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-fundamental-papers-implementation-lineage&quot;&gt;6. Fundamental Papers (implementation lineage)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Bahdanau et al., 2015&lt;/a&gt; — reference algorithm for additive attention.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Luong et al., 2015&lt;/a&gt; — simpler scores widely used in RNNToolkits.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Vaswani et al., 2017&lt;/a&gt; — vectorized scaled attention + multi-head packaging.&lt;/li&gt;
  &lt;li&gt;PyTorch docs: &lt;a href=&quot;https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.MultiheadAttention&lt;/code&gt;&lt;/a&gt; — batch_first, masks, average weights.&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-common-pitfalls-and-tricks&quot;&gt;7. Common Pitfalls and Tricks&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Bug&lt;/th&gt;
      &lt;th&gt;Symptom&lt;/th&gt;
      &lt;th&gt;Fix&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Softmax on wrong dimension&lt;/td&gt;
      &lt;td&gt;Weights sum over queries or batch&lt;/td&gt;
      &lt;td&gt;Softmax over &lt;strong&gt;keys&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mask value &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0&lt;/code&gt; after softmax&lt;/td&gt;
      &lt;td&gt;Future tokens still affect grads&lt;/td&gt;
      &lt;td&gt;Add &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt; &lt;strong&gt;before&lt;/strong&gt; softmax&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Wh @ h&lt;/code&gt; vs &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h @ Wh&lt;/code&gt; confusion&lt;/td&gt;
      &lt;td&gt;Silent shape errors&lt;/td&gt;
      &lt;td&gt;Fix a convention and unit-test&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mixing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(d,)&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(d,1)&lt;/code&gt;&lt;/td&gt;
      &lt;td&gt;Broadcasting nightmares&lt;/td&gt;
      &lt;td&gt;Canonicalize with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;reshape(-1)&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;No &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;max&lt;/code&gt; subtraction&lt;/td&gt;
      &lt;td&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt; on large scores&lt;/td&gt;
      &lt;td&gt;Stable softmax&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Trick:&lt;/strong&gt; for causal self-attention, assert &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;triu(weights, 1) == 0&lt;/code&gt; every time you change mask code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trick:&lt;/strong&gt; print &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;alpha&lt;/code&gt; on a 3–4 token toy sequence before scaling up.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-key-takeaways&quot;&gt;8. Key Takeaways&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Attention code is always &lt;strong&gt;score → mask → softmax → weighted values&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Bahdanau’s loop form is the best teaching implementation; scaled matmul is the production form.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stability&lt;/strong&gt; (max-subtraction, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;sqrt(d_k)&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-inf&lt;/code&gt; masks) is part of correctness.&lt;/li&gt;
  &lt;li&gt;Unit tests on tiny shapes catch 90% of attention bugs.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Next lesson: &lt;strong&gt;multi-head attention&lt;/strong&gt;, richer demos, papers, and a seq2seq sketch.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=kCc8FmEb1nY&quot;&gt;Let’s build GPT: from scratch, in code, spelled out.&lt;/a&gt; — Andrej Karpathy, English. A line-by-line scaled dot-product implementation. It is long; the attention section is the part that matches this lesson.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, English. The shapes of Q, K, and V to check against the code.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mmzRYGCfTzc&quot;&gt;A Dive Into Multihead Attention, Self-Attention and Cross-Attention&lt;/a&gt; — Machine Learning Studio, English. What to add after the single-head core works.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-02-01 Attention Mathematics</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_02_01_Attention_Math/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_02_01_Attention_Math</id>
   <content type="html">&lt;p&gt;Why does the most famous equation in modern AI—\(\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{Q K^\top}{\sqrt{d_k}}\right) V\)—contain that seemingly tiny factor of \(1/\sqrt{d_k}\)? Remove it, train a 64- or 128-dimensional attention head, and gradients quietly flatline: the dot products grow so large in magnitude that softmax saturates into near one-hot spikes whose Jacobian approaches zero. Every symbol in scaled dot-product attention exists for a precise probabilistic and geometric reason.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-probability--linear-algebra-of-scaled-attention&quot;&gt;Key ideas: The Probability &amp;amp; Linear Algebra of Scaled Attention&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Variance Explosion of High-Dimensional Dot Products&lt;/strong&gt;: If entries of \(q, k \in \mathbb{R}^{d_k}\) are independent with mean \(0\) and variance \(1\), then \(\mathbb{E}[q^\top k] = 0\) while \(\operatorname{Var}(q^\top k) = \sum_{i=1}^{d_k} \operatorname{Var}(q_i k_i) = d_k\). Dividing by \(\sqrt{d_k}\) restores unit variance \(\operatorname{Var}(q^\top k / \sqrt{d_k}) = 1\) regardless of \(d_k\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Softmax Saturation &amp;amp; Jacobian Collapse&lt;/strong&gt;: For a probability vector \(p = \operatorname{softmax}(z)\), the Jacobian is \(J = \operatorname{diag}(p) - p p^\top\). When large logit variance pushes one entry \(p_m \to 1\) and all others \(\to 0\), every entry of \(J\) collapses to \(0\), starving \(Q\) and \(K\) of gradients.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Batched Matrix Formulation&lt;/strong&gt;: Packing \(N\) queries into \(Q \in \mathbb{R}^{N \times d_k}\) and \(M\) key-value pairs into \(K \in \mathbb{R}^{M \times d_k}, V \in \mathbb{R}^{M \times d_v}\) turns \(N\) separate lookups into two dense GEMMs—maximizing GPU Tensor Core utilization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pre-Softmax Additive Masking&lt;/strong&gt;: Adding \(-\infty\) (or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;-1e9&lt;/code&gt;) to forbidden positions before softmax guarantees \(\exp(-\infty) = 0\) so masked keys contribute zero probability mass and zero gradient.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-exact-matrix-calculation-of-scaled-dot-product-attention-with-causal-mask&quot;&gt;Worked example: Exact Matrix Calculation of Scaled Dot-Product Attention (with Causal Mask)&lt;/h3&gt;

&lt;p&gt;Let \(T = 2, d_k = 4\) (so \(\sqrt{d_k} = 2\)) with:
\(Q = \begin{bmatrix} 1 &amp;amp; 0 &amp;amp; 1 &amp;amp; 0 \\ 0 &amp;amp; 2 &amp;amp; 0 &amp;amp; 2 \end{bmatrix}, \quad K = \begin{bmatrix} 2 &amp;amp; 0 &amp;amp; 0 &amp;amp; 2 \\ 0 &amp;amp; 1 &amp;amp; 2 &amp;amp; 1 \end{bmatrix}, \quad V = \begin{bmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 4 \end{bmatrix}.\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute raw dot-product matrix \(Q K^\top\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Row 0: \(q_0 \cdot k_0 = 1(2) + 0 + 0 + 0 = 2\); \(q_0 \cdot k_1 = 0 + 0 + 1(2) + 0 = 2\).&lt;/li&gt;
      &lt;li&gt;Row 1: \(q_1 \cdot k_0 = 0 + 0 + 0 + 2(2) = 4\); \(q_1 \cdot k_1 = 0 + 2(1) + 0 + 2(1) = 4\).
\(Q K^\top = \begin{bmatrix} 2 &amp;amp; 2 \\ 4 &amp;amp; 4 \end{bmatrix}.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scale by \(1/\sqrt{d_k} = 1/2\)&lt;/strong&gt;:
\(S = \frac{Q K^\top}{2} = \begin{bmatrix} 1 &amp;amp; 1 \\ 2 &amp;amp; 2 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply causal mask&lt;/strong&gt; (token 0 cannot attend to future token 1, so set \(S_{0,1} = -\infty\)):
\(S_{\text{masked}} = \begin{bmatrix} 1 &amp;amp; -\infty \\ 2 &amp;amp; 2 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Row-wise softmax&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Row 0: \(\operatorname{softmax}([1, -\infty]) = [1.0,\; 0.0]\).&lt;/li&gt;
      &lt;li&gt;Row 1: \(\operatorname{softmax}([2, 2]) = [0.5,\; 0.5]\).
\(A = \begin{bmatrix} 1.0 &amp;amp; 0.0 \\ 0.5 &amp;amp; 0.5 \end{bmatrix}.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multiply by \(V\)&lt;/strong&gt;:
\(O = A V = \begin{bmatrix} 1.0 &amp;amp; 0.0 \\ 0.5 &amp;amp; 0.5 \end{bmatrix} \begin{bmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 4 \end{bmatrix} = \begin{bmatrix} 1.0 &amp;amp; 0.0 \\ 0.5 &amp;amp; 2.0 \end{bmatrix}.\)
Notice how token 0 sees only \(v_0 = [1, 0]\), while token 1 blends \(v_0\) and \(v_1\) equally!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;attention-mathematics&quot;&gt;Attention Mathematics&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://raw.githubusercontent.com/tensorflow/nmt/master/nmt/g3doc/img/attention_mechanism.jpg&quot; alt=&quot;Attention Mechanism Visualization&quot; /&gt;
&lt;em&gt;Classic neural machine translation attention: decoder states form queries over encoder keys/values. Source: TensorFlow NMT tutorial&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This lesson develops attention &lt;strong&gt;as a precise mathematical object&lt;/strong&gt;. Fundamentals (07-01) already introduced the story; here we unify notation, compare score families rigorously, vectorize everything for batches, and set up multi-head attention and masking as first-class equations—not afterthoughts.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;At the highest level, attention is a &lt;strong&gt;parameterized, differentiable soft lookup&lt;/strong&gt;. Given a query vector that encodes “what do I need now?”, attention compares that query to a set of keys, converts similarities into a probability distribution, and returns the corresponding mixture of values.&lt;/p&gt;

&lt;p&gt;Three design axes completely determine a concrete mechanism:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Where Q, K, V come from&lt;/strong&gt; — decoder vs encoder (cross-attention), or the same sequence (self-attention).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;How similarity is scored&lt;/strong&gt; — additive, bilinear, or scaled dot product.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What positions are allowed&lt;/strong&gt; — full attention, padding masks, causal masks, or sparse patterns.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Everything famous in the literature (Bahdanau NMT attention, Luong variants, Transformer self-attention, multi-head attention) is a point in this three-dimensional design space.&lt;/p&gt;

&lt;p&gt;A useful algebraic slogan:&lt;/p&gt;

\[\text{Attention}(\mathbf{q}, \{(\mathbf{k}_j,\mathbf{v}_j)\}_j)
= \sum_j \alpha_j \mathbf{v}_j,
\quad
\alpha = \mathrm{softmax}(\mathrm{score}(\mathbf{q},\mathbf{k}_\cdot)).\]

&lt;p&gt;Matrix forms replace the sum with a product; multi-head attention stacks several independent copies of this map.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_qk_matmul.jpg&quot; alt=&quot;Step 1: $$Q K^\top$$&quot; /&gt;
&lt;em&gt;Figure: Raw scores = product of \(Q\) with \(K^\top\) (one query row per token). (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_scaled_dot_product.jpg&quot; alt=&quot;Scaled softmax then × V&quot; /&gt;
&lt;em&gt;Figure: Divide by \(\sqrt{d_k}\), softmax, then multiply by \(V\). (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;h3 id=&quot;21-single-query-attention&quot;&gt;2.1 Single-query attention&lt;/h3&gt;

&lt;p&gt;Let&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;query \(\mathbf{q} \in \mathbb{R}^{d_q}\),&lt;/li&gt;
  &lt;li&gt;keys \(\mathbf{k}_j \in \mathbb{R}^{d_k}\), \(j=1,\ldots,L\),&lt;/li&gt;
  &lt;li&gt;values \(\mathbf{v}_j \in \mathbb{R}^{d_v}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Scores&lt;/strong&gt;&lt;/p&gt;

\[e_j = \mathrm{score}(\mathbf{q}, \mathbf{k}_j) \in \mathbb{R}.\]

&lt;p&gt;&lt;strong&gt;Weights&lt;/strong&gt;&lt;/p&gt;

\[\alpha_j = \frac{\exp(e_j)}{\sum_{\ell=1}^{L}\exp(e_\ell)}.\]

&lt;p&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{c} = \sum_{j=1}^{L} \alpha_j \mathbf{v}_j \in \mathbb{R}^{d_v}.\]

&lt;p&gt;Properties that always hold (without masking):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\alpha_j \ge 0\), \(\sum_j \alpha_j = 1\),&lt;/li&gt;
  &lt;li&gt;\(\mathbf{c}\) lies in the convex hull of \(\{\mathbf{v}_j\}\),&lt;/li&gt;
  &lt;li&gt;if one score dominates, \(\mathbf{c}\) approaches that value (soft argmax).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;22-score-families&quot;&gt;2.2 Score families&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Additive (Bahdanau)&lt;/strong&gt;&lt;/p&gt;

\[\mathrm{score}(\mathbf{q},\mathbf{k}) = \mathbf{v}_a^\top \tanh(\mathbf{W}_q\mathbf{q} + \mathbf{W}_k\mathbf{k}).\]

&lt;ul&gt;
  &lt;li&gt;Flexible: query and key can live in different raw spaces before projection.&lt;/li&gt;
  &lt;li&gt;Cost: extra nonlinearity and vector \(\mathbf{v}_a\); less GPU-friendly than pure matmuls when \(L\) is large.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Bilinear / general&lt;/strong&gt;&lt;/p&gt;

\[\mathrm{score}(\mathbf{q},\mathbf{k}) = \mathbf{q}^\top \mathbf{W} \mathbf{k}.\]

&lt;p&gt;Learns a metric. Reduces to a dot product when \(\mathbf{W}=\mathbf{I}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dot product&lt;/strong&gt;&lt;/p&gt;

\[\mathrm{score}(\mathbf{q},\mathbf{k}) = \mathbf{q}^\top \mathbf{k}.\]

&lt;p&gt;Fast and natural when \(\mathbf{q}\) and \(\mathbf{k}\) already share a space (typical after learned projections).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scaled dot product (Transformer)&lt;/strong&gt;&lt;/p&gt;

\[\mathrm{score}(\mathbf{q},\mathbf{k}) = \frac{\mathbf{q}^\top \mathbf{k}}{\sqrt{d_k}}.\]

&lt;h3 id=&quot;23-why-scaling-matters-variance-argument&quot;&gt;2.3 Why scaling matters (variance argument)&lt;/h3&gt;

&lt;p&gt;Suppose coordinates of \(\mathbf{q}\) and \(\mathbf{k}\) are i.i.d. with mean 0 and variance 1. Then&lt;/p&gt;

\[\mathrm{Var}(\mathbf{q}^\top\mathbf{k}) = d_k.\]

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;For large \(d_k\), $$&lt;/td&gt;
      &lt;td&gt;\mathbf{q}^\top\mathbf{k}&lt;/td&gt;
      &lt;td&gt;$$ tends to be large. Softmax of large-magnitude logits is nearly one-hot:&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

\[\alpha \approx \mathbf{e}_{j^\star}, \quad j^\star=\arg\max_j e_j,\]

&lt;p&gt;and gradients w.r.t. non-max positions vanish. Dividing by \(\sqrt{d_k}\) restores variance \(\approx 1\), independent of dimension, so training can learn &lt;em&gt;graded&lt;/em&gt; attention, not only hard selection.&lt;/p&gt;

&lt;h3 id=&quot;24-batched-matrix-form&quot;&gt;2.4 Batched matrix form&lt;/h3&gt;

&lt;p&gt;Pack \(L_q\) queries and \(L_k\) keys:&lt;/p&gt;

\[\mathbf{Q}\in\mathbb{R}^{L_q\times d_k},\quad
\mathbf{K}\in\mathbb{R}^{L_k\times d_k},\quad
\mathbf{V}\in\mathbb{R}^{L_k\times d_v}.\]

&lt;p&gt;Then&lt;/p&gt;

\[\mathbf{A} = \mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\in\mathbb{R}^{L_q\times L_k},
\qquad
\mathrm{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V})=\mathbf{A}\mathbf{V}\in\mathbb{R}^{L_q\times d_v}.\]

&lt;p&gt;With batch and heads:&lt;/p&gt;

\[\mathbf{Q},\mathbf{K},\mathbf{V}\in\mathbb{R}^{B\times H\times L\times d_k}
\quad\Rightarrow\quad
\text{scores }\in\mathbb{R}^{B\times H\times L_q\times L_k}.\]

&lt;p&gt;All pairwise similarities become one batched matmul—this is why attention thrives on GPUs.&lt;/p&gt;

&lt;h3 id=&quot;25-encoderdecoder-cross-attention&quot;&gt;2.5 Encoder–decoder (cross) attention&lt;/h3&gt;

&lt;p&gt;At decoder step \(t\) with state \(\mathbf{s}_t\) and encoder states \(\mathbf{H}=[\mathbf{h}_1;\ldots;\mathbf{h}_{L_x}]\in\mathbb{R}^{L_x\times d}\):&lt;/p&gt;

\[\mathbf{q}_t = f_q(\mathbf{s}_t),\quad
\mathbf{K}=\mathbf{H}\mathbf{W}^K,\quad
\mathbf{V}=\mathbf{H}\mathbf{W}^V,\]

\[\mathbf{c}_t = \mathrm{Attention}(\mathbf{q}_t,\mathbf{K},\mathbf{V}).\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_cross_qkv_projections.jpg&quot; alt=&quot;Cross-attention: Q from decoder, K/V from encoder&quot; /&gt;
&lt;em&gt;Figure: Queries from (masked) decoder output; keys/values from the encoder. (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_cross_attention_pipeline.jpg&quot; alt=&quot;Full cross-attention pipeline&quot; /&gt;
&lt;em&gt;Figure: Project → \(QK^\top\) → softmax → × V → cross-attention output. (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Classic Bahdanau uses additive score between \(\mathbf{s}_t\) and each \(\mathbf{h}_i\) without necessarily factoring separate \(\mathbf{W}^K,\mathbf{W}^V\) the Transformer way—but the &lt;em&gt;role&lt;/em&gt; decomposition is the same: query from decoder, memory from encoder.&lt;/p&gt;

&lt;h3 id=&quot;26-self-attention&quot;&gt;2.6 Self-attention&lt;/h3&gt;

&lt;p&gt;For input matrix \(\mathbf{X}\in\mathbb{R}^{L\times d_{\mathrm{model}}}\):&lt;/p&gt;

\[\mathbf{Q}=\mathbf{X}\mathbf{W}^Q,\quad
\mathbf{K}=\mathbf{X}\mathbf{W}^K,\quad
\mathbf{V}=\mathbf{X}\mathbf{W}^V,\]

\[\mathrm{SelfAttn}(\mathbf{X})=\mathrm{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V}).\]

&lt;p&gt;Row \(i\) of the output is a mixture of all value rows, with mixture weights depending on how well query \(i\) matches every key.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Path length.&lt;/strong&gt; Any position can influence any other in &lt;strong&gt;one&lt;/strong&gt; attention layer (\(O(1)\) sequential steps), versus \(O(L)\) along an RNN chain. That is the structural reason self-attention captures long-range dependencies more easily.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Complexity.&lt;/strong&gt; Dense self-attention is \(O(L^2 d)\) time and \(O(L^2)\) memory for the score matrix—fine for moderate \(L\), painful for very long documents (hence later sparse/linear attention research).&lt;/p&gt;

&lt;h3 id=&quot;27-multi-head-attention&quot;&gt;2.7 Multi-head attention&lt;/h3&gt;

&lt;p&gt;With \(H\) heads and \(d_k=d_v=d_{\mathrm{model}}/H\):&lt;/p&gt;

\[\mathrm{head}_h=\mathrm{Attention}(\mathbf{X}\mathbf{W}_h^Q,\mathbf{X}\mathbf{W}_h^K,\mathbf{X}\mathbf{W}_h^V),\]

\[\mathrm{MultiHead}(\mathbf{X})=\mathrm{Concat}(\mathrm{head}_1,\ldots,\mathrm{head}_H)\,\mathbf{W}^O.\]

&lt;p&gt;Dimensions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathbf{W}_h^Q,\mathbf{W}_h^K\in\mathbb{R}^{d_{\mathrm{model}}\times d_k}\),&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}_h^V\in\mathbb{R}^{d_{\mathrm{model}}\times d_v}\),&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}^O\in\mathbb{R}^{H d_v\times d_{\mathrm{model}}}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Why multiple heads?&lt;/strong&gt; Softmax attention is a single soft distribution per query. One distribution often collapses to one mode. Separate heads provide several distributions in parallel—empirically specializing (syntax vs locality vs rare long links)—then \(\mathbf{W}^O\) mixes them.&lt;/p&gt;

&lt;h3 id=&quot;28-masking-as-an-additive-operation-on-logits&quot;&gt;2.8 Masking as an additive operation on logits&lt;/h3&gt;

&lt;p&gt;Let \(\mathbf{S}=\mathbf{Q}\mathbf{K}^\top/\sqrt{d_k}\). Define an additive mask \(\mathbf{M}\) of the same broadcastable shape:&lt;/p&gt;

\[\mathbf{M}_{ij}=\begin{cases}
0 &amp;amp; \text{if position }j\text{ is allowed for query }i,\\
-\infty &amp;amp; \text{if forbidden.}
\end{cases}\]

&lt;p&gt;Then&lt;/p&gt;

\[\mathbf{A}=\mathrm{softmax}(\mathbf{S}+\mathbf{M}).\]

&lt;p&gt;Because \(\exp(-\infty)=0\), forbidden keys get zero weight &lt;strong&gt;and&lt;/strong&gt; correct gradients (unlike zeroing weights &lt;em&gt;after&lt;/em&gt; softmax).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Padding mask.&lt;/strong&gt; Forbid keys that are pad tokens (per batch row).&lt;br /&gt;
&lt;strong&gt;Causal mask.&lt;/strong&gt; Forbid \(j&amp;gt;i\) for autoregressive decoding: \(\mathbf{M}=\mathrm{triu}(-\infty)\) strictly above the diagonal.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_with_causal_mask_formula.jpg&quot; alt=&quot;Attention formula + causal mask&quot; /&gt;
&lt;em&gt;Figure: Add mask matrix \(M\) (\(0\) / \(-\infty\)) &lt;strong&gt;before&lt;/strong&gt; softmax. (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_mask_applied_scores.jpg&quot; alt=&quot;Mask applied to scores&quot; /&gt;
&lt;em&gt;Figure: Upper triangle set to \(-\infty\) → no looking at future tokens. (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_future_leak.jpg&quot; alt=&quot;Future leak without masking&quot; /&gt;
&lt;em&gt;Figure: Without a causal mask a blank position can “read” the rest of the sentence — training leakage. (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_causal_generation_arcs.jpg&quot; alt=&quot;Causal attention arcs while generating&quot; /&gt;
&lt;em&gt;Figure: A new token may only attend to already-generated tokens (and itself). (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;29-residual-form-used-in-practice&quot;&gt;2.9 Residual form used in practice&lt;/h3&gt;

&lt;p&gt;In deep stacks one almost always uses&lt;/p&gt;

\[\mathbf{X} \leftarrow \mathbf{X} + \mathrm{Dropout}(\mathrm{MultiHead}(\mathrm{Norm}(\mathbf{X})))\]

&lt;p&gt;(or post-norm variants). Mathematics of a single attention map does not include residuals, but &lt;strong&gt;trainability&lt;/strong&gt; of deep attention models depends on them. Keep this distinction clear: attention defines a layer map; residuals define how maps compose.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;h3 id=&quot;31-cross-attention-with-explicit-numbers&quot;&gt;3.1 Cross-attention with explicit numbers&lt;/h3&gt;

&lt;p&gt;Encoder states (already projected keys = values for simplicity), \(d=2\):&lt;/p&gt;

\[\mathbf{h}_1=\begin{bmatrix}1\\0\end{bmatrix}\ (``I&quot;),\quad
\mathbf{h}_2=\begin{bmatrix}0\\1\end{bmatrix}\ (``love&quot;),\quad
\mathbf{h}_3=\begin{bmatrix}1\\1\end{bmatrix}\ (``ML&quot;).\]

&lt;p&gt;Decoder query \(\mathbf{q}=\begin{bmatrix}0.9\\0.2\end{bmatrix}\). Dot-product scores:&lt;/p&gt;

\[e=(0.9,\ 0.2,\ 1.1).\]

&lt;p&gt;Softmax (approx.):&lt;/p&gt;

\[\alpha \approx (0.34,\ 0.17,\ 0.49).\]

&lt;p&gt;Context:&lt;/p&gt;

\[\mathbf{c}\approx 0.34\begin{bmatrix}1\\0\end{bmatrix}
+0.17\begin{bmatrix}0\\1\end{bmatrix}
+0.49\begin{bmatrix}1\\1\end{bmatrix}
=\begin{bmatrix}0.83\\0.66\end{bmatrix}.\]

&lt;p&gt;Most mass is on “ML,” but “I” still contributes—soft alignment, not hard pointer.&lt;/p&gt;

&lt;h3 id=&quot;32-self-attention-as-a-data-dependent-mixing-matrix&quot;&gt;3.2 Self-attention as a data-dependent mixing matrix&lt;/h3&gt;

&lt;p&gt;For self-attention, \(\mathbf{A}\in\mathbb{R}^{L\times L}\) is a &lt;strong&gt;row-stochastic&lt;/strong&gt; matrix (each row sums to 1). The map&lt;/p&gt;

\[\mathbf{X}\mapsto \mathbf{A}\mathbf{V}\]

&lt;p&gt;is a linear mixture of values, but \(\mathbf{A}\) &lt;em&gt;depends nonlinearly&lt;/em&gt; on \(\mathbf{X}\) through QKV projections and softmax. That input dependence is what makes attention strictly more expressive than a fixed convolution kernel of the same support.&lt;/p&gt;

&lt;h3 id=&quot;33-multi-head-as-a-block-diagonal-story&quot;&gt;3.3 Multi-head as a block diagonal story&lt;/h3&gt;

&lt;p&gt;Imagine two heads with orthogonal interests: head 1 peeks at adjacent tokens; head 2 peeks at a coreferent noun. Concatenation preserves both signals in different feature slices; \(\mathbf{W}^O\) can then build features that need &lt;em&gt;both&lt;/em&gt; adjacency and coreference. A single head would have to compromise with one distribution.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-code-snippet-math-facing&quot;&gt;4. Code Snippet (math-facing)&lt;/h2&gt;

&lt;p&gt;This snippet is intentionally short: it mirrors the equations. Full demos live in the implementation lessons.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;attention_math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Q: (Lq, dk), K: (Lk, dk), V: (Lk, dv)
    mask: (Lq, Lk) with True = forbid
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;S&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;S&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;S&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;S&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;S&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;S&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;S&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Causal self-attention on random features
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;causal&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;attention_math&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;causal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;atol&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# no future mass
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Kernel smoothing / Nadaraya–Watson estimators&lt;/strong&gt; — attention is a learned kernel smoother over values.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Content-addressable memory&lt;/strong&gt; — keys address content; queries retrieve.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Graph message passing&lt;/strong&gt; — self-attention on a complete graph with data-dependent edge weights.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convolutions&lt;/strong&gt; — fixed local kernels vs dynamic global weights.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sparse attention / linear attention&lt;/strong&gt; — approximations when \(O(L^2)\) is unacceptable.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Bahdanau et al., 2015 — Align and Translate&lt;/a&gt; — additive attention for NMT.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Luong et al., 2015 — Effective Approaches…&lt;/a&gt; — multiplicative scores, local/global attention.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Vaswani et al., 2017 — Attention Is All You Need&lt;/a&gt; — scaled multi-head self-attention.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1803.02155&quot;&gt;Shaw et al., 2018 — Relative Position Representations&lt;/a&gt; — inject relative distance into attention logits.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2006.16236&quot;&gt;Katharopoulos et al., 2020 — Transformers are RNNs&lt;/a&gt; — linear-time attention variants (optional advanced reading).&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-common-pitfalls-and-tricks&quot;&gt;7. Common Pitfalls and Tricks&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Mixing up \(L_q\) and \(L_k\) axes&lt;/strong&gt; when implementing masks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Applying mask after softmax&lt;/strong&gt; — wrong gradients and residual leakage.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Omitting scale&lt;/strong&gt; at large \(d_k\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Assuming \(\mathbf{A}\) is symmetric&lt;/strong&gt; in self-attention — it is not; rows are distributions over keys, not undirected edges.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trick:&lt;/strong&gt; verify causal attention with the test &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;triu(A,1)≈0&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trick:&lt;/strong&gt; unit-test multi-head reshape by checking total element count and a tiny hand example.&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-key-takeaways&quot;&gt;8. Key Takeaways&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;Attention is always &lt;strong&gt;score → softmax → weighted values&lt;/strong&gt;; only score, sources of QKV, and masks change.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scaling&lt;/strong&gt; is a variance-control device required for high-dimensional dot products.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matrix form&lt;/strong&gt; \(\mathrm{softmax}(QK^\top/\sqrt{d_k})V\) is the industrial interface.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Self-attention&lt;/strong&gt; gives \(O(1)\) path length at \(O(L^2)\) cost.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multi-head&lt;/strong&gt; = several soft distributions + output mix.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Masks modify logits&lt;/strong&gt;, not post-hoc weights.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Next: implement these equations carefully in &lt;strong&gt;07-02-02&lt;/strong&gt;, starting with core attention modules.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1467113421464723&quot;&gt;LLM Ep.4: Attention Mechanism (Q–K–V, fully connected relations)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1806844676942638&quot;&gt;Attention formula: hand-compute Q, K, V&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1007473105556936&quot;&gt;Attention in Transformers (Self, Masked, Cross, Multi-Head)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, English. Softmax(QK^T / sqrt(d)) V is derived, not only named.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PSs6nxngL6k&quot;&gt;Attention for Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. A smaller numerical story of the same weighted sum.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mmzRYGCfTzc&quot;&gt;A Dive Into Multihead Attention, Self-Attention and Cross-Attention&lt;/a&gt; — Machine Learning Studio, English. How the single formula becomes several heads.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-02 Attention Mechanisms in Depth</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_01_Attention_Mechanisms/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_01_Attention_Mechanisms</id>
   <content type="html">&lt;p&gt;Once you see how Bahdanau alignment rescues an RNN translator from the fixed-vector bottleneck, the next natural leap is mathematical abstraction: strip away the RNN entirely and ask what happens when attention operates as a standalone, batched matrix operator with scaled dot products and multiple parallel heads. This module bridges conceptual intuition to the exact linear algebra, variance scaling, and PyTorch multi-head code that power modern Transformers.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-deepening-attention-from-alignment-to-multi-head-tensors&quot;&gt;Key ideas: Deepening Attention from Alignment to Multi-Head Tensors&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Exact Scaled Dot-Product Algebra&lt;/strong&gt;: Deriving why dividing \(Q K^\top\) by \(\sqrt{d_k}\) stabilizes softmax variance across growing head dimensions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Masking Geometry&lt;/strong&gt;: Constructing padding masks (to ignore &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&amp;lt;PAD&amp;gt;&lt;/code&gt; tokens) and causal upper-triangular masks (to enforce autoregressive causality) by injecting \(-\infty\) &lt;em&gt;before&lt;/em&gt; softmax.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multi-Head Subspace Decomposition&lt;/strong&gt;: Splitting \(d_{\text{model}}\) into \(h\) heads of dimension \(d_k = d_{\text{model}}/h\) so the model can simultaneously track syntactic dependencies, coreference, and positional proximity.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-shape--cost-audit-of-batched-attention&quot;&gt;Worked example: Shape &amp;amp; Cost Audit of Batched Attention&lt;/h3&gt;

&lt;p&gt;Consider a batch of \(B = 4\) sentences of length \(T = 16\) with model dimension \(d_{\text{model}} = 64\) split into \(h = 8\) heads (\(d_k = 64 / 8 = 8\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Projected Q, K, V shapes after head splitting&lt;/strong&gt;:
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Q, K, V&lt;/code&gt; each have shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, h, T, d_k) = (4, 8, 16, 8)&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Attention score matrix &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Q @ K.T&lt;/code&gt;&lt;/strong&gt;:
Shape is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 8, 16, 16)&lt;/code&gt; — holding \(4 \times 8 \times 256 = 8{,}192\) pairwise alignment scores.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Weighted value output &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;attn @ V&lt;/code&gt; and head re-concatenation&lt;/strong&gt;:
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 8, 16, 16) @ (4, 8, 16, 8) -&amp;gt; (4, 8, 16, 8)&lt;/code&gt;, which transposes and reshapes cleanly back to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4, 16, 64)&lt;/code&gt; before the final output projection \(W_O \in \mathbb{R}^{64 \times 64}\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;07-02-attention-mechanisms-in-depth&quot;&gt;07-02 Attention Mechanisms in Depth&lt;/h1&gt;

&lt;p&gt;This block goes &lt;strong&gt;beyond the fundamentals lesson&lt;/strong&gt;. You already know &lt;em&gt;why&lt;/em&gt; attention exists and the basic formulas. Here we tighten the mathematics, then implement every moving part carefully.&lt;/p&gt;

&lt;h2 id=&quot;what-you-will-study&quot;&gt;What you will study&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Attention Mathematics&lt;/strong&gt;&lt;br /&gt;
Unified score functions, vectorized QKV forms, self-attention as an \(L\times L\) interaction, multi-head algebra, padding and causal masks as pre-softmax operations, complexity and path-length arguments.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Attention Implementation&lt;/strong&gt;&lt;br /&gt;
From-scratch Bahdanau and scaled attention, multi-head modules, masking demos, a minimal seq2seq-with-attention sketch, papers, and production pitfalls.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;how-to-read-this-block&quot;&gt;How to read this block&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Order&lt;/th&gt;
      &lt;th&gt;Lesson&lt;/th&gt;
      &lt;th&gt;Outcome&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;07-02-01 Attention Mathematics&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;You can write every formula without looking it up&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;07-02-02 Implementation&lt;/strong&gt; (overview)&lt;/td&gt;
      &lt;td&gt;Map math → code modules&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;07-02-02-01 Core Implementation&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Working Bahdanau + self-attention code&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;4&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;07-02-02-02 Multi-Head, Papers, Pitfalls&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Multi-head, causal masks, literature, debugging checklist&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;If a formula in 07-02-01 feels abstract, jump to the matching demo in 07-02-02-01, then return. Math and code are meant to reinforce each other, not compete.&lt;/p&gt;

&lt;h2 id=&quot;connection-to-the-rest-of-the-course&quot;&gt;Connection to the rest of the course&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Back to 07-01&lt;/strong&gt; for intuition and historical motivation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Forward to Chapter 08 (Transformers)&lt;/strong&gt; for stacking self-attention with feed-forward blocks, residuals, and positional encodings.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Proceed to &lt;strong&gt;Attention Mathematics&lt;/strong&gt; when ready.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, English. The chapter’s deep block: scaled dot-product attention.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PSs6nxngL6k&quot;&gt;Attention for Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. The sequence-model version, so self-attention is not the only pattern.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=mmzRYGCfTzc&quot;&gt;A Dive Into Multihead Attention, Self-Attention and Cross-Attention&lt;/a&gt; — Machine Learning Studio, English. Multi-head, self-attention, and cross-attention, which this block separates.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07-01 Attention Mechanism Fundamentals</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_01_Attention_Basics/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_01_Attention_Basics</id>
   <content type="html">&lt;p&gt;When Dzmitry Bahdanau, Kyunghyun Cho, and Yoshua Bengio published &lt;em&gt;Neural Machine Translation by Jointly Learning to Align and Translate&lt;/em&gt; (2015), they included a now-iconic heatmap of French-to-English attention weights: the diagonal tracked word-for-word correspondence, and at the phrase &lt;em&gt;“zone économique européenne”&lt;/em&gt; \(\to\) &lt;em&gt;“European Economic Area”&lt;/em&gt;, the model’s attention weights spontaneously jumped backward in exact reverse order to match French adjective placement. That visual proof showed that soft alignment could be learned purely from end-to-end translation loss—without a single hand-coded grammar rule.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-encoderdecoder-alignment-and-additive-attention&quot;&gt;Key ideas: Encoder–Decoder Alignment and Additive Attention&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Seq2Seq Compression Bottleneck&lt;/strong&gt;: In Sutskever et al. (2014), the encoder’s final state \(h_T\) had to encode every noun, tense, and clause of the entire input sentence. Mutual information between early source tokens and \(h_T\) decays with sequence length.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bahdanau (Additive) Score Function&lt;/strong&gt;: Given decoder state \(s_{t-1}\) and encoder annotation \(h_j\), additive attention scores alignment via a small 1-hidden-layer MLP: \(e_{t,j} = v_a^\top \tanh(W_a s_{t-1} + U_a h_j)\), allowing \(s_{t-1}\) and \(h_j\) to have completely different dimensions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Luong (Multiplicative / Dot-Product) Score Function&lt;/strong&gt;: Luong et al. (2015) showed that simpler bilinear/dot-product scoring \(e_{t,j} = s_t^\top W_a h_j\) runs much faster on GPUs because it reduces to matrix multiplication rather than broadcasting a 3D addition tensor.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Soft vs. Hard Alignment&lt;/strong&gt;: Soft attention computes a smooth expectation \(\sum_j \alpha_{t,j} h_j\) (differentiable via standard backpropagation), whereas hard attention samples a single index \(j^* \sim \text{Cat}(\alpha_t)\) (requiring REINFORCE / high-variance policy gradients).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-hand-computing-bahdanau-additive-attention&quot;&gt;Worked example: Hand-Computing Bahdanau Additive Attention&lt;/h3&gt;

&lt;p&gt;Suppose at decoder step \(t\), we have scalar decoder state \(s_{t-1} = 1.0\) and two encoder states \(h_1 = 2.0, h_2 = -1.0\), with parameters \(W_a = 0.5, U_a = 0.5, v_a = 2.0\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute additive alignment energies \(e_{t,j} = v_a \tanh(W_a s_{t-1} + U_a h_j)\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;For \(j = 1\): \(W_a s_{t-1} + U_a h_1 = 0.5(1.0) + 0.5(2.0) = 1.5 \implies \tanh(1.5) \approx 0.9051 \implies e_{t,1} = 2.0(0.9051) = 1.8102\).&lt;/li&gt;
      &lt;li&gt;For \(j = 2\): \(W_a s_{t-1} + U_a h_2 = 0.5(1.0) + 0.5(-1.0) = 0.0 \implies \tanh(0.0) = 0.0 \implies e_{t,2} = 2.0(0.0) = 0.0000\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply softmax over the source positions&lt;/strong&gt;:
\(e^{1.8102} \approx 6.112,\quad e^{0} = 1.000,\quad Z = 7.112.\)
\(\alpha_{t,1} = \frac{6.112}{7.112} \approx 0.8594,\quad \alpha_{t,2} = \frac{1.000}{7.112} \approx 0.1406.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Form the dynamic context vector \(c_t\)&lt;/strong&gt;:
\(c_t = \alpha_{t,1} h_1 + \alpha_{t,2} h_2 = 0.8594(2.0) + 0.1406(-1.0) = 1.7188 - 0.1406 = 1.5782.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Contrast with fixed-vector Seq2Seq&lt;/strong&gt;: Rather than being stuck with \(h_2 = -1.0\) (the encoder’s final state), the decoder pulls \(85.9\%\) of its context directly from \(h_1\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;attention-mechanism-fundamentals&quot;&gt;Attention Mechanism Fundamentals&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/multihead_attention.png&quot; alt=&quot;Multi-Head Attention&quot; /&gt;
&lt;em&gt;Multi-head attention schematic (as used in Transformers). Source: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Attention&lt;/strong&gt; is a mechanism that lets a model &lt;em&gt;dynamically focus&lt;/em&gt; on different parts of its input when producing each piece of output. Instead of forcing all information through a single fixed-size summary, attention computes a &lt;strong&gt;soft selection&lt;/strong&gt;: for every output step, it assigns weights to input positions and forms a weighted combination of their representations.&lt;/p&gt;

&lt;p&gt;That idea sounds simple, but it solved a structural failure of early sequence models and later became the backbone of modern NLP (and much of vision).&lt;/p&gt;

&lt;h3 id=&quot;the-bottleneck-that-made-attention-necessary&quot;&gt;The bottleneck that made attention necessary&lt;/h3&gt;

&lt;p&gt;Classic &lt;strong&gt;encoder–decoder&lt;/strong&gt; (seq2seq) models for machine translation work as follows:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;An &lt;strong&gt;encoder&lt;/strong&gt; RNN reads the source sentence word by word.&lt;/li&gt;
  &lt;li&gt;The encoder compresses the whole sentence into one final hidden state (a fixed-size vector).&lt;/li&gt;
  &lt;li&gt;A &lt;strong&gt;decoder&lt;/strong&gt; RNN starts from that vector and generates the target sentence.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Schematically:&lt;/p&gt;

&lt;div class=&quot;language-text highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&quot;The cat sat on the mat&quot;
        │
        ▼
   [Encoder RNN]
        │
        ▼
   fixed context vector  z ∈ R^d     ← bottleneck
        │
        ▼
   [Decoder RNN] → &quot;Le chat était assis sur le tapis&quot;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Two problems appear immediately.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Information bottleneck.&lt;/strong&gt; Whether the source is 5 words or 50, everything must fit in \(z\). Long sentences lose detail; rare but critical words get washed out.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Fixed “one summary for every target word.”&lt;/strong&gt; Human translators do not re-read the &lt;em&gt;same&lt;/em&gt; summary for every target word. When producing “chat,” they focus on “cat”; when producing “tapis,” they focus on “mat.” A single fixed \(z\) cannot provide that &lt;em&gt;dynamic alignment&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Attention’s solution:&lt;/strong&gt; keep &lt;em&gt;all&lt;/em&gt; encoder states \(\mathbf{h}_1, \ldots, \mathbf{h}_T\), and at each decoder step \(t\), compute a new context vector&lt;/p&gt;

\[\mathbf{c}_t = \sum_{i=1}^{T} \alpha_{t,i}\,\mathbf{h}_i\]

&lt;p&gt;where the weights \(\alpha_{t,i}\) are &lt;em&gt;learned&lt;/em&gt; and &lt;em&gt;depend on the current decoder state&lt;/em&gt;. Different target words get different soft alignments over the source.&lt;/p&gt;

&lt;h3 id=&quot;everyday-analogy&quot;&gt;Everyday analogy&lt;/h3&gt;

&lt;p&gt;Think of writing an answer while an open textbook lies on the desk. You do not memorize the whole chapter into one sentence and then answer from that sentence alone. For each sentence you write, you glance back at different paragraphs. Attention is that “glance”: a differentiable, learned version of looking up the right place in the input.&lt;/p&gt;

&lt;h3 id=&quot;why-this-chapter-starts-here&quot;&gt;Why this chapter starts here&lt;/h3&gt;

&lt;p&gt;This lesson builds the &lt;strong&gt;conceptual and historical core&lt;/strong&gt; of attention:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;encoder–decoder attention (Bahdanau / Luong),&lt;/li&gt;
  &lt;li&gt;the query–key–value view,&lt;/li&gt;
  &lt;li&gt;scaled dot-product attention,&lt;/li&gt;
  &lt;li&gt;self-attention vs cross-attention,&lt;/li&gt;
  &lt;li&gt;multi-head attention at an introductory level.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Later lessons in this chapter deepen the mathematics and implementations. Transformers (next chapter) assemble these pieces into a full architecture.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;h3 id=&quot;21-encoderdecoder-attention-in-general-form&quot;&gt;2.1 Encoder–decoder attention in general form&lt;/h3&gt;

&lt;p&gt;At decoder step \(t\):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Symbol&lt;/th&gt;
      &lt;th&gt;Meaning&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\mathbf{s}_t\)&lt;/td&gt;
      &lt;td&gt;decoder hidden state (what we are trying to generate &lt;em&gt;now&lt;/em&gt;)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\mathbf{h}_i\)&lt;/td&gt;
      &lt;td&gt;encoder hidden state at source position \(i\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(e_{t,i}\)&lt;/td&gt;
      &lt;td&gt;unnormalized &lt;strong&gt;alignment score&lt;/strong&gt; between decoder step \(t\) and source \(i\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\alpha_{t,i}\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;attention weight&lt;/strong&gt; (how much to focus on source \(i\))&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(\mathbf{c}_t\)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;context vector&lt;/strong&gt; (soft summary of the source for step \(t\))&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Step 1 — scores.&lt;/strong&gt; Compare the decoder state to every encoder state:&lt;/p&gt;

\[e_{t,i} = \mathrm{score}(\mathbf{s}_t, \mathbf{h}_i)\]

&lt;p&gt;&lt;strong&gt;Step 2 — normalize with softmax.&lt;/strong&gt;&lt;/p&gt;

\[\alpha_{t,i} = \frac{\exp(e_{t,i})}{\sum_{j=1}^{T}\exp(e_{t,j})}\]

&lt;p&gt;so \(\alpha_{t,i} \ge 0\) and \(\sum_i \alpha_{t,i} = 1\). The weights form a probability distribution over source positions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3 — context as a weighted sum.&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{c}_t = \sum_{i=1}^{T} \alpha_{t,i}\,\mathbf{h}_i\]

&lt;p&gt;&lt;strong&gt;Step 4 — use context for prediction.&lt;/strong&gt; Typically combine context and decoder state, then predict the next token:&lt;/p&gt;

\[\tilde{\mathbf{s}}_t = \tanh\!\big(\mathbf{W}_c[\mathbf{c}_t;\mathbf{s}_t]\big), \qquad
p(y_t \mid y_{&amp;lt;t}, x) = \mathrm{softmax}(\mathbf{W}_o\tilde{\mathbf{s}}_t)\]

&lt;p&gt;(Exact combination layers vary by paper; the important idea is: &lt;strong&gt;prediction depends on \(\mathbf{c}_t\), not only on a fixed bottleneck.&lt;/strong&gt;)&lt;/p&gt;

&lt;h3 id=&quot;22-bahdanau-attention-additive-attention-2015&quot;&gt;2.2 Bahdanau attention (additive attention, 2015)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Bahdanau et al.&lt;/a&gt; introduced a trainable score:&lt;/p&gt;

\[e_{t,i} = \mathbf{v}_a^\top \tanh\!\big(\mathbf{W}_a\mathbf{s}_t + \mathbf{U}_a\mathbf{h}_i\big)\]

&lt;p&gt;&lt;strong&gt;Why it works.&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathbf{W}_a\) and \(\mathbf{U}_a\) project decoder and encoder states into a shared space before comparison.&lt;/li&gt;
  &lt;li&gt;\(\tanh\) adds nonlinearity so “relevance” is not a pure linear dot product.&lt;/li&gt;
  &lt;li&gt;\(\mathbf{v}_a\) collapses the projected vector to a scalar score.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is often called &lt;strong&gt;additive&lt;/strong&gt; attention because query and key features are &lt;em&gt;added&lt;/em&gt; inside the \(\tanh\).&lt;/p&gt;

&lt;p&gt;Historically, this was the first widely used neural attention for NMT and made long-sentence translation dramatically more reliable than pure bottleneck seq2seq.&lt;/p&gt;

&lt;h3 id=&quot;23-luong-attention-multiplicative--general-forms-2015&quot;&gt;2.3 Luong attention (multiplicative / general forms, 2015)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Luong et al.&lt;/a&gt; studied simpler score functions that are often faster and work well in practice:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dot product&lt;/strong&gt;&lt;/p&gt;

\[e_{t,i} = \mathbf{s}_t^\top \mathbf{h}_i\]

&lt;p&gt;&lt;strong&gt;General (bilinear)&lt;/strong&gt;&lt;/p&gt;

\[e_{t,i} = \mathbf{s}_t^\top \mathbf{W}_a \mathbf{h}_i\]

&lt;p&gt;&lt;strong&gt;Concat&lt;/strong&gt; (similar spirit to Bahdanau)&lt;/p&gt;

\[e_{t,i} = \mathbf{v}_a^\top \tanh\!\big(\mathbf{W}_a[\mathbf{s}_t;\mathbf{h}_i]\big)\]

&lt;p&gt;&lt;strong&gt;Intuition.&lt;/strong&gt; Dot product measures directional alignment: if the decoder “wants” something in the same direction as an encoder state, the score is large. The general form inserts a learned metric \(\mathbf{W}_a\) so alignment can be more flexible when \(\mathbf{s}_t\) and \(\mathbf{h}_i\) live in different spaces.&lt;/p&gt;

&lt;h3 id=&quot;24-the-querykeyvalue-q-k-v-view&quot;&gt;2.4 The query–key–value (Q, K, V) view&lt;/h3&gt;

&lt;p&gt;Modern attention is usually written with three roles:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Role&lt;/th&gt;
      &lt;th&gt;Question it answers&lt;/th&gt;
      &lt;th&gt;Typical source&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Query&lt;/strong&gt; \(\mathbf{q}\)&lt;/td&gt;
      &lt;td&gt;“What am I looking for right now?”&lt;/td&gt;
      &lt;td&gt;decoder state, or position \(i\) in self-attention&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Key&lt;/strong&gt; \(\mathbf{k}_j\)&lt;/td&gt;
      &lt;td&gt;“What does item \(j\) offer for matching?”&lt;/td&gt;
      &lt;td&gt;encoder states, or all positions&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Value&lt;/strong&gt; \(\mathbf{v}_j\)&lt;/td&gt;
      &lt;td&gt;“What content should I retrieve if I match \(j\)?”&lt;/td&gt;
      &lt;td&gt;often same vectors as keys, or a separate projection&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Attention then does:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;score queries against keys,&lt;/li&gt;
  &lt;li&gt;softmax → weights,&lt;/li&gt;
  &lt;li&gt;weighted sum of values.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This abstraction covers &lt;strong&gt;cross-attention&lt;/strong&gt; (query from one sequence, keys/values from another) and &lt;strong&gt;self-attention&lt;/strong&gt; (query, key, value all from the same sequence).&lt;/p&gt;

&lt;p&gt;In LLMs the same pipeline is often described as a &lt;em&gt;fully connected relational network&lt;/em&gt;: embeddings in → split Q/K/V → attention scores → Softmax → (many heads in parallel) → fused context out.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/llm_attn_qkv_pipeline_active.jpg&quot; alt=&quot;LLM-style attention pipeline&quot; /&gt;
&lt;em&gt;Figure: Q–K–V flow → Softmax → multi-head → context fusion. (Illustration from an LLM Attention Mechanism video)&lt;/em&gt;&lt;/p&gt;

&lt;h4 id=&quot;numeric-walkthrough-3-token-sentence--q-k-v&quot;&gt;Numeric walkthrough: 3-token sentence → Q, K, V&lt;/h4&gt;

&lt;p&gt;Take a toy 3-word sentence (e.g. “I / love / you”), each word already a 2-d embedding (illustration; real models often use \(d_{\mathrm{model}}=512\)):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_toy_sentence_embeddings.jpg&quot; alt=&quot;3-word embeddings&quot; /&gt;
&lt;em&gt;Figure: Input matrix \(\mathbf{X}\) — 3 tokens × \(d\). (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Three learned weight matrices \(W^Q, W^K, W^V\) project \(\mathbf{X}\) into query/key/value spaces:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_weights_wq_wk_wv.jpg&quot; alt=&quot;W^Q, W^K, W^V&quot; /&gt;
&lt;em&gt;Figure: Three separate projection matrices. (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_project_x_to_qkv.jpg&quot; alt=&quot;X × W → Q, K, V&quot; /&gt;
&lt;em&gt;Figure: \(\mathbf{Q}=\mathbf{X}W^Q\), \(\mathbf{K}=\mathbf{X}W^K\), \(\mathbf{V}=\mathbf{X}W^V\). (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;25-scaled-dot-product-attention&quot;&gt;2.5 Scaled dot-product attention&lt;/h3&gt;

&lt;p&gt;The standard building block of Transformers is:&lt;/p&gt;

\[\mathrm{Attention}(\mathbf{Q},\mathbf{K},\mathbf{V})
= \mathrm{softmax}\!\left(\frac{\mathbf{Q}\mathbf{K}^\top}{\sqrt{d_k}}\right)\mathbf{V}\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_matrices_and_formula.jpg&quot; alt=&quot;Q, K, V and the Attention formula&quot; /&gt;
&lt;em&gt;Figure: Projected matrices + scaled SDP formula. (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;with shapes (for one sequence, ignoring batch for a moment):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
\[\mathbf{Q} \in \mathbb{R}^{L_q \times d_k}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbf{K} \in \mathbb{R}^{L_k \times d_k}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbf{V} \in \mathbb{R}^{L_k \times d_v}\]
  &lt;/li&gt;
  &lt;li&gt;output \(\in \mathbb{R}^{L_q \times d_v}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Hand calculation (same 3-word example).&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Dot products&lt;/strong&gt; — each query row × columns of \(K^\top\) (one score per token pair):&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_dot_product_row_example.jpg&quot; alt=&quot;Per-entry QK^T&quot; /&gt;
&lt;em&gt;Figure: Example: the “I” query dotted with every key. (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_unscaled_similarities.jpg&quot; alt=&quot;Unscaled similarity matrix&quot; /&gt;
&lt;em&gt;Figure: \(\mathbf{Q}K^\top\) — Unscaled Dot-Product Similarities. (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Scale&lt;/strong&gt; — divide by \(\sqrt{d_k}\) (here \(d_k=2\) → \(\sqrt{2}\)):&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_scale_by_sqrt_dk.jpg&quot; alt=&quot;Divide by √d_k&quot; /&gt;
&lt;em&gt;Figure: Unscaled → Scaled Dot-Product Similarities. (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why divide by \(\sqrt{d_k}\)?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If query/key coordinates are roughly independent with variance 1, then a raw dot product has variance about \(d_k\). For large \(d_k\) (e.g. 64–512), scores become huge, softmax becomes nearly one-hot, and gradients vanish. Scaling keeps scores in a healthier range so the model can learn &lt;em&gt;soft&lt;/em&gt; distributions, not only hard argmax-like attention.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Row-wise softmax&lt;/strong&gt; — each query becomes a distribution over keys:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_softmax_over_rows.jpg&quot; alt=&quot;Softmax over rows&quot; /&gt;
&lt;em&gt;Figure: Softmax runs along each row. (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_attention_weights.jpg&quot; alt=&quot;Attention weights&quot; /&gt;
&lt;em&gt;Figure: Weight matrix (each row sums to ≈ 1). (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;× V&lt;/strong&gt; — mix values by those weights → attention output:&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_weights_times_v.jpg&quot; alt=&quot;Weights × V&quot; /&gt;
&lt;em&gt;Figure: Attention Weights × V = Attention Output. (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;26-self-attention-vs-cross-attention&quot;&gt;2.6 Self-attention vs cross-attention&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Cross-attention (encoder–decoder attention).&lt;/strong&gt;&lt;br /&gt;
Queries come from the decoder; keys and values come from the encoder. This is the original NMT attention: “when generating this target word, which source words matter?”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Self-attention.&lt;/strong&gt;&lt;br /&gt;
Queries, keys, and values all come from the &lt;em&gt;same&lt;/em&gt; sequence. Every position can gather context from every other position:&lt;/p&gt;

\[\mathbf{Q} = \mathbf{X}\mathbf{W}^Q,\quad
\mathbf{K} = \mathbf{X}\mathbf{W}^K,\quad
\mathbf{V} = \mathbf{X}\mathbf{W}^V\]

&lt;p&gt;Each token starts as a numeric vector; then every token builds its own Q/K/V:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_tokens_as_vectors.jpg&quot; alt=&quot;Tokens as numeric columns&quot; /&gt;
&lt;em&gt;Figure: A sentence represented as embedding vectors. (Illustration from an intro Transformer / Self-Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_per_token_qkv_columns.jpg&quot; alt=&quot;Per-token Q/K/V columns&quot; /&gt;
&lt;em&gt;Figure: Self-attention forms Q, K, V for *each&lt;/em&gt; position. (Illustration from an intro Transformer / Self-Attention video)*&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_qkv_roles_apple_phone_orange.jpg&quot; alt=&quot;Q/K/V roles by word&quot; /&gt;
&lt;em&gt;Figure: Same QKV pipeline on “apple / phone / orange” — match context, then mix values. (Illustration from an intro Transformer / Self-Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Example: in the sentence&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;The animal didn’t cross the street because &lt;strong&gt;it&lt;/strong&gt; was too tired.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Self-attention can learn that “it” should attend strongly to “animal.” That long-range link does not need to travel step-by-step through an RNN.&lt;/p&gt;

&lt;h3 id=&quot;27-multi-head-attention-introductory-view&quot;&gt;2.7 Multi-head attention (introductory view)&lt;/h3&gt;

&lt;p&gt;A single attention head can specialize in one kind of pattern. Language (and other structured data) has many simultaneous relations: syntax, coreference, adjacency, semantic similarity, etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Multi-head attention&lt;/strong&gt; runs \(H\) attention operations in parallel with different projections, then concatenates and mixes them:&lt;/p&gt;

\[\mathrm{head}_h = \mathrm{Attention}(\mathbf{Q}\mathbf{W}_h^Q, \mathbf{K}\mathbf{W}_h^K, \mathbf{V}\mathbf{W}_h^V)\]

\[\mathrm{MultiHead}(\mathbf{Q},\mathbf{K},\mathbf{V})
= \mathrm{Concat}(\mathrm{head}_1,\ldots,\mathrm{head}_H)\,\mathbf{W}^O\]

&lt;p&gt;Often \(d_k = d_v = d_{\mathrm{model}} / H\) so total compute stays comparable to one full-width head, while representational capacity increases through diversity of heads.&lt;/p&gt;

&lt;p&gt;Common numbers: \(d_{\mathrm{model}}=512\), \(H=8\) → each head uses \(d_k=64\):&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_multihead_dk_split.jpg&quot; alt=&quot;Split d_model across heads&quot; /&gt;
&lt;em&gt;Figure: \(512/8=64\) — Q/K/V width per head. (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/qkv_multihead_output_stack.jpg&quot; alt=&quot;Stacked multi-head outputs&quot; /&gt;
&lt;em&gt;Figure: 8 heads × (L × 64) then concat → (L × 512). (Illustration from a QKV Attention formula video)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;28-masking-what-you-must-know-early&quot;&gt;2.8 Masking (what you must know early)&lt;/h3&gt;

&lt;p&gt;Two masks appear constantly:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Padding mask.&lt;/strong&gt; In a batch, shorter sequences are padded. Attention must not put mass on pad tokens. Implementation: add a large negative number to masked logits before softmax so those weights ≈ 0.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Causal (look-ahead) mask.&lt;/strong&gt; In autoregressive generation (language modeling, decoder-only Transformers), position \(i\) must not attend to future positions \(j &amp;gt; i\). Use an upper-triangular mask.&lt;/p&gt;

&lt;p&gt;Without the right mask, models “cheat” by looking at tokens they should not see yet, or by attending to meaningless padding.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;h3 id=&quot;31-soft-alignment-in-translation&quot;&gt;3.1 Soft alignment in translation&lt;/h3&gt;

&lt;p&gt;Source: &lt;strong&gt;I love deep learning&lt;/strong&gt; (4 tokens)&lt;br /&gt;
Target step producing something like &lt;strong&gt;apprentissage&lt;/strong&gt; (“learning”).&lt;/p&gt;

&lt;p&gt;Suppose the decoder query at that step scores the four source positions as:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Source token&lt;/th&gt;
      &lt;th&gt;raw score \(e\)&lt;/th&gt;
      &lt;th&gt;after softmax \(\alpha\)&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;I&lt;/td&gt;
      &lt;td&gt;0.2&lt;/td&gt;
      &lt;td&gt;0.05&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;love&lt;/td&gt;
      &lt;td&gt;0.5&lt;/td&gt;
      &lt;td&gt;0.07&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;deep&lt;/td&gt;
      &lt;td&gt;1.5&lt;/td&gt;
      &lt;td&gt;0.20&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;learning&lt;/td&gt;
      &lt;td&gt;2.8&lt;/td&gt;
      &lt;td&gt;0.68&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The context vector is mostly “learning,” with a useful contribution from “deep.” The model did not need a hard symbolic alignment table; it &lt;em&gt;learned&lt;/em&gt; a soft alignment from data.&lt;/p&gt;

&lt;p&gt;When generating a different target word (e.g. “J’aime” / “I love”), the weight mass would shift toward “I” and “love.”&lt;/p&gt;

&lt;h3 id=&quot;32-self-attention-as-contextualization&quot;&gt;3.2 Self-attention as contextualization&lt;/h3&gt;

&lt;p&gt;Take three tokens with toy 2-D values (already projected for simplicity):&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Token&lt;/th&gt;
      &lt;th&gt;value vector&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;The&lt;/td&gt;
      &lt;td&gt;\((1, 0)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;cat&lt;/td&gt;
      &lt;td&gt;\((0, 1)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;sat&lt;/td&gt;
      &lt;td&gt;\((1, 1)\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;If “sat” attends with weights \([0.1, 0.6, 0.3]\) to (The, cat, sat), its output becomes&lt;/p&gt;

\[0.1(1,0) + 0.6(0,1) + 0.3(1,1) = (0.4,\ 0.9)\]

&lt;p&gt;The representation of “sat” is no longer isolated; it is &lt;strong&gt;mixed with context&lt;/strong&gt;, especially “cat.” That is the essence of contextual embeddings produced by self-attention stacks (BERT, GPT, etc.).&lt;/p&gt;

&lt;h3 id=&quot;33-attention-is-not-magic-memory&quot;&gt;3.3 Attention is not magic memory&lt;/h3&gt;

&lt;p&gt;Attention gives &lt;em&gt;access&lt;/em&gt; to representations that already exist. It does not by itself invent long-term storage like an LSTM cell state. If the encoder states are weak, attention can only reweight weak information. Good attention needs good underlying features—and later, positional signals (Transformers add positional encodings precisely because pure self-attention is permutation-sensitive without them).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;h3 id=&quot;41-scaled-dot-product-attention-numpy&quot;&gt;4.1 Scaled dot-product attention (NumPy)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# numerical stability
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;e&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;e&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Q: (..., Lq, dk)
    K: (..., Lk, dk)
    V: (..., Lk, dv)
    mask: broadcastable to (..., Lq, Lk); True/1 means &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mask out&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    returns: output (..., Lq, dv), weights (..., Lq, Lk)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;swapaxes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (..., Lq, Lk)
&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Toy self-attention example
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# For demo: use X as Q, K, V (no learned projections yet)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;# (4, 8)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# (4, 4)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;rows sum to 1:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;allclose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;42-causal-mask&quot;&gt;4.2 Causal mask&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;mask[i, j] = True if j &amp;gt; i (forbid attending to the future).&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;triu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;causal_mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;round&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Upper triangle (future) should be ~0
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;43-multi-head-attention-conceptual-numpy&quot;&gt;4.3 Multi-head attention (conceptual NumPy)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;default_rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.02&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rng&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, L, d_model) -&amp;gt; (B, H, L, dk)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# x: (B, H, L, dk) -&amp;gt; (B, L, d_model)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Self-attention for simplicity
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wk&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;scaled_dot_product_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;K&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;V&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mask&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_merge&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;B&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;MultiHeadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 6, 32)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 4, 6, 6)  — batch, heads, query pos, key pos
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;44-pytorch-what-you-will-use-in-practice&quot;&gt;4.4 PyTorch (what you will use in practice)&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;torch_sdp_attention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    q,k,v: (B, H, L, d) or (B, L, d)
    attn_mask: additive mask broadcastable to scores; use -inf on forbidden positions
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;q&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;q&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;transpose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn_mask&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;scores&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Built-in module (preferred for real models)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MultiheadAttention&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;embed_dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_heads&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;need_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;average_attn_weights&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;attn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;In production code, prefer &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.MultiheadAttention&lt;/code&gt; or fused scaled-dot-product kernels (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.functional.scaled_dot_product_attention&lt;/code&gt;) for speed and numerical stability.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;RNNs / LSTMs.&lt;/strong&gt; Attention was first popularized &lt;em&gt;on top of&lt;/em&gt; RNN encoders. RNNs provide sequential states; attention selects among them. Transformers later &lt;em&gt;replace&lt;/em&gt; recurrence with self-attention + positional encoding.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Seq2seq bottleneck.&lt;/strong&gt; Attention is the direct fix for fixed-length context vectors in encoder–decoder models (Chapters 5–6 background).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Softmax as soft selection.&lt;/strong&gt; Attention weights are a softmax over scores—the same primitive used in classification, but applied over &lt;em&gt;positions&lt;/em&gt; (or memory slots).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Memory / retrieval view.&lt;/strong&gt; Keys are addresses, values are stored contents, queries are lookup requests. This view connects attention to differentiable memory and retrieval-augmented models.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Transformers.&lt;/strong&gt; A Transformer layer is largely: multi-head self-attention + feed-forward network + residual connections + normalization. This lesson’s QKV machinery is the core of that design (next chapter).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interpretability.&lt;/strong&gt; Attention heatmaps are a useful debugging tool, but they are not a complete causal explanation of model decisions. Treat them as &lt;em&gt;evidence of focus&lt;/em&gt;, not proof of reasoning.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.0473&quot;&gt;Neural Machine Translation by Jointly Learning to Align and Translate (Bahdanau et al., 2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Introduced additive attention for NMT; decoder soft-searches source positions while generating each target word. The paper that made neural attention mainstream.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1508.04025&quot;&gt;Effective Approaches to Attention-based Neural Machine Translation (Luong et al., 2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Compared global/local attention and simple multiplicative scoring functions; practical recipes still cited today.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;Attention Is All You Need (Vaswani et al., 2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Replaced recurrence with multi-head self-attention (the Transformer). Scaled dot-product attention and multi-head design became the default template for modern sequence models.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1502.03044&quot;&gt;Show, Attend and Tell (Xu et al., 2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Visual attention for image captioning: demonstrated that attention generalizes beyond text-to-text alignment.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1810.04805&quot;&gt;BERT (Devlin et al., 2019)&lt;/a&gt;&lt;/strong&gt; / &lt;strong&gt;&lt;a href=&quot;https://cdn.openai.com/research-covers/language-unsupervised/language_understanding_paper.pdf&quot;&gt;GPT lineage (Radford et al.)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
Large-scale proof that stacks of self-attention produce powerful language representations and generators.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-common-pitfalls-and-tricks&quot;&gt;7. Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Pitfall: confusing scores with weights.&lt;/strong&gt;&lt;br /&gt;
\(e_{t,i}\) are raw logits; only after softmax do you get \(\alpha_{t,i}\) that sum to 1. Never average encoder states with unnormalized scores and call it attention.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pitfall: forgetting \(\sqrt{d_k}\).&lt;/strong&gt;&lt;br /&gt;
Without scaling, large \(d_k\) makes attention overly sharp and training unstable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pitfall: wrong mask polarity.&lt;/strong&gt;&lt;br /&gt;
Be explicit: does &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1&lt;/code&gt; mean “keep” or “mask out”? Off-by-convention bugs silently leak future tokens or kill real tokens.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pitfall: attending to padding.&lt;/strong&gt;&lt;br /&gt;
Always mask pads in batched training; otherwise the model wastes capacity on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;PAD&lt;/code&gt; and metrics look mysteriously bad.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pitfall: treating attention weights as ground-truth explanations.&lt;/strong&gt;&lt;br /&gt;
Weights are useful visualizations, not guaranteed causal attributions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trick: temperature / sharpness.&lt;/strong&gt;&lt;br /&gt;
Dividing scores by a temperature \(\tau\) before softmax (or using sparsemax variants) can control how peaked attention is—useful for analysis and some specialized models.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trick: residual + layer norm around attention.&lt;/strong&gt;&lt;br /&gt;
In deep stacks, always wrap attention blocks with residuals (and usually LayerNorm). Bare attention layers are harder to train deeply.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trick: start with cross-attention intuition, then self-attention.&lt;/strong&gt;&lt;br /&gt;
If multi-head self-attention feels abstract, first master “decoder looks at encoder,” then replace both sides with the same sequence.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-key-takeaways&quot;&gt;8. Key Takeaways&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Attention replaces a fixed bottleneck with a dynamic weighted readout&lt;/strong&gt; over input states.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scores → softmax weights → weighted values&lt;/strong&gt; is the universal skeleton (Bahdanau, Luong, Transformer).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Q, K, V&lt;/strong&gt; unify cross-attention and self-attention in one language.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scaling by \(\sqrt{d_k}\)&lt;/strong&gt; keeps softmax well-behaved in high dimensions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multi-head attention&lt;/strong&gt; learns multiple relation patterns in parallel.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Masking&lt;/strong&gt; (padding, causal) is part of the algorithm, not an optional extra.&lt;/li&gt;
  &lt;li&gt;Attention is the conceptual bridge from RNN seq2seq to &lt;strong&gt;Transformers&lt;/strong&gt;—the next chapter.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When you can explain, with a small numerical example, how a decoder step forms \(\mathbf{c}_t\) from encoder states, you have the foundation needed for every modern attention model in this course.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1467113421464723&quot;&gt;LLM Ep.4: Attention Mechanism (Q–K–V, fully connected relations)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/930207546288223&quot;&gt;What is a Transformer? Self-Attention for beginners (Part 1)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1806844676942638&quot;&gt;Attention formula: hand-compute Q, K, V&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PSs6nxngL6k&quot;&gt;Attention for Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Attention as an extra path from each input to each step, before any transformer block.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, English. The Q, K, V arithmetic the lesson then writes in full.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=L8HKweZIOmg&quot;&gt;Sequence-to-Sequence (seq2seq) Encoder-Decoder Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. The encoder-decoder the original attention path was bolted onto.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>07 Attention Mechanisms</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter07/07_00_Introduction</id>
   <content type="html">&lt;p&gt;Imagine trying to translate a 60-word German legal sentence into English after being forced to memorize the entire sentence as one fixed-length 512-number summary—without ever being allowed to glance back at the original page. That exact “fixed-vector bottleneck” crippled early RNN encoder–decoder translation models: the moment source sentences grew beyond 25 words, BLEU scores collapsed. In 2014–2015, Bahdanau, Cho, and Bengio changed deep learning forever by letting the decoder &lt;strong&gt;look back dynamically&lt;/strong&gt; at every source token and compute a fresh, content-weighted mixture at every step. That simple mechanism—&lt;strong&gt;Attention&lt;/strong&gt;—soon outgrew RNNs altogether and became the relational engine of modern AI.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-why-attention-replaced-fixed-vector-compression&quot;&gt;Key ideas: Why Attention Replaced Fixed-Vector Compression&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Information Bottleneck &amp;amp; Dynamic Memory Access&lt;/strong&gt;: Instead of compressing a length-\(T\) sequence into one static vector \(c \in \mathbb{R}^d\), attention keeps all \(T\) encoder states \(H = [h_1, \dots, h_T]\) in memory and performs a soft, differentiable lookup conditioned on the current query.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Query–Key–Value (QKV) Relational Abstraction&lt;/strong&gt;: Attention generalizes a Python dictionary lookup from exact hard-key matching to continuous vector geometry: a &lt;strong&gt;Query&lt;/strong&gt; \(q\) scores its similarity against every &lt;strong&gt;Key&lt;/strong&gt; \(k_i\), normalizes those scores with softmax into convex weights \(\alpha_i\), and returns the weighted average \(\sum_i \alpha_i v_i\) of the &lt;strong&gt;Values&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Four Core Attention Flavors&lt;/strong&gt;: Distinguishing &lt;strong&gt;cross-attention&lt;/strong&gt; (decoder queries encoder), &lt;strong&gt;bidirectional self-attention&lt;/strong&gt; (every token sees every token, as in BERT), &lt;strong&gt;causal/masked self-attention&lt;/strong&gt; (tokens only see the past, as in GPT), and &lt;strong&gt;multi-head attention&lt;/strong&gt; (parallel relational subspaces) unlocks the entire Transformer family.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Constant Path Length (\(O(1)\) Hop Distance)&lt;/strong&gt;: Whereas an RNN takes \(O(T)\) sequential steps to connect token 1 to token \(T\), self-attention connects any two tokens in a single matrix multiplication—at the trade-off of \(O(T^2)\) pairwise score computation.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-soft-dictionary-lookup-on-3-tokens&quot;&gt;Worked example: Soft Dictionary Lookup on 3 Tokens&lt;/h3&gt;

&lt;p&gt;Suppose a query vector \(q = [1, 0]\) attends over three key-value pairs (no scaling needed since \(d_k = 2\), or using raw dot products for clarity):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Token 1 (“bank”): \(k_1 = [2, 0],\; v_1 = [10, 0]\)&lt;/li&gt;
  &lt;li&gt;Token 2 (“river”): \(k_2 = [1, 1],\; v_2 = [0, 10]\)&lt;/li&gt;
  &lt;li&gt;Token 3 (“the”): \(k_3 = [0, 2],\; v_3 = [5, 5]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute raw similarity scores \(e_i = q \cdot k_i\)&lt;/strong&gt;:
\(e_1 = 1(2) + 0(0) = 2,\quad e_2 = 1(1) + 0(1) = 1,\quad e_3 = 1(0) + 0(2) = 0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Normalize with softmax&lt;/strong&gt;:
\(e^2 \approx 7.389,\quad e^1 \approx 2.718,\quad e^0 = 1.000,\quad Z = 11.107.\)
\(\alpha_1 = \frac{7.389}{11.107} \approx 0.665,\quad \alpha_2 = \frac{2.718}{11.107} \approx 0.245,\quad \alpha_3 = \frac{1.000}{11.107} \approx 0.090.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the attended context vector \(c = \sum_{i=1}^3 \alpha_i v_i\)&lt;/strong&gt;:
\(c = 0.665[10, 0] + 0.245[0, 10] + 0.090[5, 5] = [6.65 + 0.45,\; 2.45 + 0.45] = [7.10,\; 2.90].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Interpretation&lt;/strong&gt;: The query smoothly retrieves mostly Token 1’s value while blending contextual evidence from Token 2, and every weight \(\alpha_i\) is end-to-end differentiable with respect to \(q, k_i, v_i\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;chapter-07--attention-mechanisms&quot;&gt;Chapter 07 — Attention Mechanisms&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attention_encoder_decoder.png&quot; alt=&quot;Attention Encoder-Decoder&quot; /&gt;
&lt;em&gt;Encoder–decoder with attention: the decoder looks back over all encoder states at each generation step. Source: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;why-this-chapter-exists&quot;&gt;Why this chapter exists&lt;/h2&gt;

&lt;p&gt;Recurrent models (Chapters 5–6) process sequences step by step and compress history into a hidden state. That design works, but it creates two chronic problems for long sequences:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Information bottleneck&lt;/strong&gt; — especially in classic encoder–decoder models, where the whole source must fit in one fixed vector.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hard long-range routing&lt;/strong&gt; — information from position \(i\) to position \(j\) must travel through many sequential steps, which is fragile under vanishing gradients.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Attention&lt;/strong&gt; attacks both problems with one idea: &lt;em&gt;dynamically re-read&lt;/em&gt; the relevant parts of the input (or of the sequence itself) when forming each representation or prediction. Instead of one frozen summary, the model learns a soft distribution over positions and forms a weighted combination of their features.&lt;/p&gt;

&lt;p&gt;That idea began as an add-on to RNN translation systems. It then became the computational heart of &lt;strong&gt;Transformers&lt;/strong&gt;, which power modern language models, many vision systems, and multimodal architectures. This chapter builds attention from first principles so the Transformer chapter is a composition of familiar pieces, not a black box.&lt;/p&gt;

&lt;h3 id=&quot;quick-map-4-attention-flavors-in-transformers&quot;&gt;Quick map: 4 attention flavors in Transformers&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Kind&lt;/th&gt;
      &lt;th&gt;Q from&lt;/th&gt;
      &lt;th&gt;K, V from&lt;/th&gt;
      &lt;th&gt;Mask?&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Self-attention&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;same sequence&lt;/td&gt;
      &lt;td&gt;same sequence&lt;/td&gt;
      &lt;td&gt;optional (full / pad)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Masked (causal) self-attention&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;decoder&lt;/td&gt;
      &lt;td&gt;decoder&lt;/td&gt;
      &lt;td&gt;block the “future”&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Cross-attention&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;decoder&lt;/td&gt;
      &lt;td&gt;encoder&lt;/td&gt;
      &lt;td&gt;usually pad only&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Multi-head&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;as above, several heads in parallel&lt;/td&gt;
      &lt;td&gt;as above&lt;/td&gt;
      &lt;td&gt;as above&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/attn_scaled_dot_product.jpg&quot; alt=&quot;Scaled dot-product attention&quot; /&gt;
&lt;em&gt;Figure: Self-attention — \(\mathrm{softmax}(QK^\top/\sqrt{d})\,V\). (Illustration from a Transformer Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;self-attention-in-plain-language-which-words-relate-to-which&quot;&gt;Self-attention in plain language: “which words relate to which?”&lt;/h3&gt;

&lt;p&gt;Sentences with ambiguous words (e.g. “Apple” = fruit vs tech company) only resolve when you &lt;strong&gt;look at the other tokens&lt;/strong&gt;. Self-attention is the mechanism that assigns “attention arcs” among tokens in the same sentence.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_context_arcs_disambiguation.jpg&quot; alt=&quot;Context attention arcs&quot; /&gt;
&lt;em&gt;Figure: Words such as “orange” / “phone” pull attention toward “Apple” in the company sense. (Illustration from an intro Transformer / Self-Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_scaled_sdp_block_diagram.jpg&quot; alt=&quot;Scaled Dot-Product block diagram&quot; /&gt;
&lt;em&gt;Figure: Pipeline Q,K → scale → optional mask → softmax → × V. (Illustration from an intro Transformer / Self-Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/sa_qkv_database_metaphor.jpg&quot; alt=&quot;Q/K/V as a table lookup&quot; /&gt;
&lt;em&gt;Figure: Query = question, Key = match column, Value = content retrieved. (Illustration from an intro Transformer / Self-Attention video)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;llm-view-a-fully-connected-relational-computation-network&quot;&gt;LLM view: a “fully connected relational computation network”&lt;/h3&gt;

&lt;p&gt;In large language models, embeddings give each token a vector; &lt;strong&gt;attention&lt;/strong&gt; is the layer where tokens &lt;em&gt;talk&lt;/em&gt; to each other: every position can link to every other position (a full / fully connected graph), with &lt;strong&gt;dynamic&lt;/strong&gt; link weights driven by content.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/llm_attn_title_fully_connected.jpg&quot; alt=&quot;Title: attention = fully connected relations&quot; /&gt;
&lt;em&gt;Figure: Attention as fully connected relational computation; Q–K–V build dynamic link weights. (Illustration from an LLM Attention Mechanism video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter07/llm_attn_qkv_pipeline_diagram.jpg&quot; alt=&quot;Pipeline Q → scores → Softmax → multi-head → context&quot; /&gt;
&lt;em&gt;Figure: Input → Query / Key / Value → score matrix → Softmax → (multi-head) → context fusion → output. (Illustration from an LLM Attention Mechanism video)&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;learning-goals&quot;&gt;Learning goals&lt;/h2&gt;

&lt;p&gt;By the end of this chapter you should be able to:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Explain the encoder–decoder bottleneck and how attention removes it.&lt;/li&gt;
  &lt;li&gt;Write the general attention pattern: &lt;strong&gt;scores → softmax weights → weighted values&lt;/strong&gt;.&lt;/li&gt;
  &lt;li&gt;Contrast &lt;strong&gt;Bahdanau (additive)&lt;/strong&gt; and &lt;strong&gt;Luong (multiplicative)&lt;/strong&gt; attention.&lt;/li&gt;
  &lt;li&gt;Use the &lt;strong&gt;query / key / value&lt;/strong&gt; language for both cross-attention and self-attention.&lt;/li&gt;
  &lt;li&gt;Derive why &lt;strong&gt;scaled&lt;/strong&gt; dot-product attention needs \(1/\sqrt{d_k}\).&lt;/li&gt;
  &lt;li&gt;Implement attention and multi-head attention with correct shapes, masks, and numerical stability.&lt;/li&gt;
  &lt;li&gt;Name the classic papers and the failure modes that break real systems (padding, causal masks, missing scale).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;roadmap&quot;&gt;Roadmap&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Lesson&lt;/th&gt;
      &lt;th&gt;Focus&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;07-01 Fundamentals&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Intuition, history, Bahdanau/Luong, QKV, scaled attention, intro multi-head&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;07-02 In depth&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Deeper mathematics and full implementations&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;07-02-01 Mathematics&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Score functions, self-attention algebra, multi-head, masking theory&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;07-02-02 Implementation&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;From-scratch NumPy/PyTorch, demos, papers, pitfalls&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Read &lt;strong&gt;07-01&lt;/strong&gt; first even if you already “know” Transformers. The vocabulary introduced there (context vector, alignment, QKV, mask) is used everywhere afterward.&lt;/p&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;Neural network basics (linear layers, softmax, backprop)&lt;/li&gt;
  &lt;li&gt;Sequence models: RNNs/LSTMs at a conceptual level (encoder hidden states, decoder steps)&lt;/li&gt;
  &lt;li&gt;Comfort with matrix shapes: batch, length, embedding dimension&lt;/li&gt;
  &lt;li&gt;Softmax as a probability distribution over discrete choices&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;mental-model-to-keep&quot;&gt;Mental model to keep&lt;/h2&gt;

&lt;p&gt;Attention is &lt;strong&gt;content-addressable soft memory&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Query&lt;/strong&gt; = what you are looking for now&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Keys&lt;/strong&gt; = what each memory slot offers for matching&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Values&lt;/strong&gt; = what you retrieve if that slot matches&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Everything else—Bahdanau vs Luong, multi-head, causal masks—is a design choice around that core loop.&lt;/p&gt;

&lt;p&gt;When you can draw that loop on paper for both &lt;em&gt;translation&lt;/em&gt; (decoder attends to encoder) and &lt;em&gt;self-attention&lt;/em&gt; (sequence attends to itself), you are ready for the rest of the chapter—and for Transformers.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1467113421464723&quot;&gt;LLM Ep.4: Attention Mechanism (Q–K–V, fully connected relations)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/930207546288223&quot;&gt;What is a Transformer? Self-Attention for beginners (Part 1)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1806844676942638&quot;&gt;Attention formula: hand-compute Q, K, V&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1007473105556936&quot;&gt;Attention in Transformers (Self, Masked, Cross, Multi-Head)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After attention math, see &lt;strong&gt;07-99 Modern Applications and Updates&lt;/strong&gt; for FlashAttention, PagedAttention, and grouped-query attention in LLM stacks.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Attention in transformers, step-by-step&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 6](https://www.youtube.com/watch?v=eMlx5fFNoYc) — 3Blue1Brown, English. Queries, keys, and values are the loop this chapter will not leave.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PSs6nxngL6k&quot;&gt;Attention for Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Attention added to a sequence model, which is the pre-transformer story the introduction starts from.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dqoEU9Ac3ek&quot;&gt;MIT 6.S191 (2024): Recurrent Neural Networks, Transformers, and Attention&lt;/a&gt; — Alexander Amini, English. MIT’s 2024 lecture that carries the same loop into a transformer.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Just when many assumed LSTMs were permanently relegated to historical footnotes, Sepp Hochreiter’s own research group published &lt;strong&gt;xLSTM (Extended Long Short-Term Memory)&lt;/strong&gt; in 2024—asking a sharp scientific question: &lt;em&gt;what happens if we fix the three original limitations of the 1997 LSTM?&lt;/em&gt; By replacing sigmoid gates with exponential gating (stabilized in log-space) and upgrading the scalar cell state into a &lt;strong&gt;matrix-valued memory&lt;/strong&gt; (\(C_t \in \mathbb{R}^{d \times d}\) updated via outer products \(v_t k_t^\top\)), xLSTM scales to billions of parameters while preserving linear-time inference—proving gated recurrence still has vital roles in streaming audio, finance, edge robotics, and hybrid LLM stacks.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-modern-gated-recurrence-xlstm--streaming-systems&quot;&gt;Key ideas: Modern Gated Recurrence (xLSTM &amp;amp; Streaming Systems)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Exponential Gating (sLSTM)&lt;/strong&gt;: Classical sigmoid gates saturate in \((0, 1)\), making it hard to revise a strongly stored memory value. Exponential gates \(i_t = \exp(\tilde{i}_t)\) and \(f_t = \exp(\tilde{f}_t)\) (stabilized with a running log-normalizer \(m_t\)) allow decisive memory overrides when a surprising token arrives.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matrix Memory &amp;amp; Associative Retrieval (mLSTM)&lt;/strong&gt;: Replacing the vector cell \(c_t \in \mathbb{R}^d\) with a covariance-like matrix \(C_t = f_t C_{t-1} + i_t v_t k_t^\top\) expands storage capacity from \(O(d)\) to \(O(d^2)\) and lets queries retrieve stored values via \(C_t q_t\)—bridging LSTMs directly to linear attention!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Streaming &amp;amp; Edge Domains&lt;/strong&gt;: In real-time speech recognition, industrial sensor telemetry, and ultra-low-latency tabular event streams, compact LSTM/GRU models still outperform Transformers on hardware with strict memory and causal latency budgets.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parallelizable Matrix Recurrence&lt;/strong&gt;: Because mLSTM removes hidden-to-hidden recurrent mixing inside the cell update, it trains in parallel across sequence length just like Transformers and Mamba.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-associative-matrix-memory-update-in-mlstm&quot;&gt;Worked example: Associative Matrix Memory Update in mLSTM&lt;/h3&gt;

&lt;p&gt;Suppose a tiny mLSTM cell has dimension \(d = 2\), initial matrix memory \(C_0 = \begin{bmatrix} 0 &amp;amp; 0 \\ 0 &amp;amp; 0 \end{bmatrix}\), and receives two orthogonal unit key-value pairs with \(f_t = 1, i_t = 1\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Step 1: key \(k_1 = \begin{bmatrix} 1 \\ 0 \end{bmatrix}\), value \(v_1 = \begin{bmatrix} 3 \\ 5 \end{bmatrix}\).&lt;/li&gt;
  &lt;li&gt;Step 2: key \(k_2 = \begin{bmatrix} 0 \\ 1 \end{bmatrix}\), value \(v_2 = \begin{bmatrix} -2 \\ 4 \end{bmatrix}\).&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Step 1 outer-product write&lt;/strong&gt;:
\(C_1 = C_0 + v_1 k_1^\top = \begin{bmatrix} 3 \\ 5 \end{bmatrix} \begin{bmatrix} 1 &amp;amp; 0 \end{bmatrix} = \begin{bmatrix} 3 &amp;amp; 0 \\ 5 &amp;amp; 0 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step 2 outer-product write&lt;/strong&gt;:
\(C_2 = C_1 + v_2 k_2^\top = \begin{bmatrix} 3 &amp;amp; 0 \\ 5 &amp;amp; 0 \end{bmatrix} + \begin{bmatrix} 0 &amp;amp; -2 \\ 0 &amp;amp; 4 \end{bmatrix} = \begin{bmatrix} 3 &amp;amp; -2 \\ 5 &amp;amp; 4 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Associative read with query \(q = k_1 = \begin{bmatrix} 1 \\ 0 \end{bmatrix}\)&lt;/strong&gt;:
\(C_2 q = \begin{bmatrix} 3 &amp;amp; -2 \\ 5 &amp;amp; 4 \end{bmatrix} \begin{bmatrix} 1 \\ 0 \end{bmatrix} = \begin{bmatrix} 3 \\ 5 \end{bmatrix} = v_1!\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why this is a breakthrough&lt;/strong&gt;: Unlike a classical vector LSTM that would blur \(v_1\) and \(v_2\) together by addition, the \(d \times d\) matrix memory stores up to \(d\) orthogonal key-value associations simultaneously with zero interference!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-gated-recurrence-after-lstms--xlstm-and-when-gates-still-win&quot;&gt;Optional: gated recurrence after LSTMs — xLSTM and when gates still win&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; rewrite LSTM/GRU gate theory. It covers 2024 gated-RNN revivals and the production niches where LSTM/GRU remain the right tool.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The LSTM cell state&lt;/p&gt;

\[\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t\]

&lt;p&gt;is still the cleanest picture of a &lt;strong&gt;writable memory&lt;/strong&gt;. Transformers stole large-scale NLP; they did not delete every gated recurrent model.&lt;/p&gt;

&lt;h2 id=&quot;1-xlstm-2024-exponential-gates--matrix-memory&quot;&gt;1. xLSTM (2024): exponential gates + matrix memory&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2405.04517&quot;&gt;Beck et al., 2024&lt;/a&gt; revisit LSTM with:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;sLSTM&lt;/strong&gt; — scalar memory with exponential input/forget gates and a normalizer (stable revision of the classic cell),&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;mLSTM&lt;/strong&gt; — a &lt;em&gt;matrix&lt;/em&gt; memory updated with a covariance-like rule, trainable in parallel like a Transformer block.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The paper reports language-modeling results that close much of the gap to Transformers at modest scale. Treat xLSTM as evidence that &lt;strong&gt;gating + memory&lt;/strong&gt; is not a 1997 idea only — not as a reason to skip attention.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;time-series-and-tabular-event-streams&quot;&gt;Time series and tabular event streams&lt;/h3&gt;

&lt;p&gt;Forecasting stacks (retail demand, ICU vitals, industrial sensors) still ship &lt;strong&gt;LSTM/GRU encoders&lt;/strong&gt;, often under a Temporal Fusion Transformer or a simple seq2seq head. The gate analysis from this chapter is exactly why they survive noisy, irregular sampling.&lt;/p&gt;

&lt;h3 id=&quot;speech-and-streaming&quot;&gt;Speech and streaming&lt;/h3&gt;

&lt;p&gt;On-device wake-word and some streaming ASR encoders keep GRUs because the state is a few kilobytes. Large ASR (Whisper, Chapter 19) is Transformer-based; the split is &lt;strong&gt;latency / memory&lt;/strong&gt;, not accuracy on LibriSpeech.&lt;/p&gt;

&lt;h3 id=&quot;hybrid-stacks&quot;&gt;Hybrid stacks&lt;/h3&gt;

&lt;p&gt;A common 2024–2026 pattern: Transformer (or Mamba) for the backbone, &lt;strong&gt;LSTM decoder&lt;/strong&gt; or &lt;strong&gt;GRU controller&lt;/strong&gt; for an action head in robotics and recommendation session models.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.GRU&lt;/code&gt; — production-quality CuDNN/cuDNN-like kernels.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/NX-AI/xlstm&quot;&gt;NX-AI/xlstm&lt;/a&gt; — official xLSTM implementations.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/sktime/sktime&quot;&gt;sktime&lt;/a&gt; / &lt;a href=&quot;https://github.com/awslabs/gluonts&quot;&gt;GluonTS&lt;/a&gt; — forecasting libraries that still expose RNN estimators.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2405.04517&quot;&gt;xLSTM: Extended Long Short-Term Memory (Beck et al., 2024)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2312.00752&quot;&gt;Mamba (Gu &amp;amp; Dao, 2023)&lt;/a&gt; — the other “recurrence is back” line; compare with xLSTM rather than duplicating Chapter 05.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1912.09363&quot;&gt;Temporal Fusion Transformers for Interpretable Multi-horizon Time Series Forecasting (Lim et al., 2021)&lt;/a&gt; — widely deployed 2022–2026; LSTM encoders + attention.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Derive forget/input/output gates from the theory lesson first. This note only adds &lt;strong&gt;xLSTM&lt;/strong&gt; and the remaining industrial LSTM/GRU use cases — it does not change the gate equations.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=0aWGTNS03PU&quot;&gt;XLSTM - Extended LSTMs with sLSTM and mLSTM (paper explained)&lt;/a&gt; — AI Bites, English. xLSTM (exponential gates and a matrix memory) is the 2024 update this note is about.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, English. The 1997 cell xLSTM is extending, so the new gates have a baseline.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker, English. The gate diagrams you need in order to see what sLSTM and mLSTM change.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-01 Long Short-Term Memory Networks</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_01_LSTM_Architecture/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_01_LSTM_Architecture</id>
   <content type="html">&lt;p&gt;Why did the LSTM architecture remain one of the most cited inventions in computer science for nearly thirty years? Because it turned an impossible optimization problem—propagating gradients across dozens of nonlinear recurrent steps—into a smooth, controllable additive highway. This chapter hub guides you through both the formal mathematical theory of LSTM/GRU cells and their hands-on code implementation, gate visualization, and pitfall diagnostics.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-navigating-the-lstm-architecture-module&quot;&gt;Key ideas: Navigating the LSTM Architecture Module&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Theory &amp;amp; Gradient Flow&lt;/strong&gt;: Understanding the Constant Error Carousel, the four-gate equations, and why additive cell updates bypass the vanishing Jacobian product of vanilla RNNs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Core Code &amp;amp; Memory Tasks&lt;/strong&gt;: Writing explicit LSTM cells in NumPy and PyTorch and testing them on long-range memory tasks where vanilla RNNs fail.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gate Inspection &amp;amp; GRU Comparison&lt;/strong&gt;: Measuring live gate saturation, contrasting 4-gate LSTMs with 3-gate GRUs, and mastering production best practices (forget-bias init, gradient clipping, sequence packing).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-comparing-effective-depth--state-bandwidth&quot;&gt;Worked example: Comparing Effective Depth &amp;amp; State Bandwidth&lt;/h3&gt;

&lt;p&gt;Consider a 2-layer stacked LSTM with \(d_h = 256\) processing a sequence of length \(T = 60\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Recurrent state vector carried between steps&lt;/strong&gt;:
Each layer maintains both \(h_t \in \mathbb{R}^{256}\) and \(C_t \in \mathbb{R}^{256}\), so total state per sequence is \(2 \text{ layers} \times 2 \text{ vectors} \times 256 = 1{,}024\) floats (\(4\text{ KiB}\) in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Computational path length&lt;/strong&gt;:
A token at \(t = 1\) reaches \(t = 60\) through \(59\) additive cell-state hops—constant \(4\text{ KiB}\) memory regardless of whether \(T = 60\) or \(T = 60{,}000\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bridge to Chapter 07&lt;/strong&gt;: Compressing all 60 tokens into a fixed \(1{,}024\)-float bottleneck is amazingly memory-efficient, yet it eventually causes an &lt;strong&gt;information bottleneck&lt;/strong&gt; in machine translation—motivating Attention in the very next chapter.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers LSTM and related gated recurrent architectures:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;LSTM and GRU Theory&lt;/strong&gt; — gates, cell state, math, and intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LSTM Implementation&lt;/strong&gt; — full code, papers, pitfalls, and takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, English. Before the theory and code split.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker, English. The gate-by-gate picture the code lesson implements.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Simple Explanation of GRU (Gated Recurrent Units)&lt;/td&gt;
          &lt;td&gt;Deep Learning Tutorial 37 (Tensorflow &amp;amp; Python)](https://www.youtube.com/watch?v=tOuXgORsXJ4) — codebasics, English. GRU as the smaller gate set.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-01-02 LSTM Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_01_02_LSTM_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_01_02_LSTM_Implementation</id>
   <content type="html">&lt;p&gt;Coding gated recurrence cleanly requires moving seamlessly from low-level cell arithmetic to high-level diagnostic analysis. This implementation hub links the two halves of practical LSTM/GRU engineering: building and training the core LSTM cell from scratch (and in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM&lt;/code&gt;), followed by inspecting live gate activations, benchmarking LSTM against GRU, and avoiding recurrent dropout and padding pitfalls.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-practical-engineering-checklist-for-lstmgru&quot;&gt;Key ideas: Practical Engineering Checklist for LSTM/GRU&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cell-Level Verification&lt;/strong&gt;: Implementing a manual NumPy LSTM cell with explicit &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(f, i, g, o)&lt;/code&gt; gates and verifying its forward/backward outputs against PyTorch’s fused kernels.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Synthetic Memory Stress Tests&lt;/strong&gt;: Using controlled long-range benchmarks (remember-first-add-last) to verify that forget gates actually stay open across long distractor spans.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Architectural Benchmarking&lt;/strong&gt;: Comparing LSTM and GRU on identical datasets while tracking parameter counts, wall-clock speed, and validation stability.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-diagnosing-a-padded-batch-bug&quot;&gt;Worked example: Diagnosing a Padded Batch Bug&lt;/h3&gt;

&lt;p&gt;Suppose a mini-batch contains two sentences of lengths \(3\) and \(5\) padded with zeros to length \(5\), and you extract &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output[:, -1, :]&lt;/code&gt; (the last time step) for classification:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sentence 2 (true length 5)&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output[1, 4, :]&lt;/code&gt; is the true final hidden state \(h_5\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sentence 1 (true length 3, padded at steps 4 and 5)&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output[0, 4, :]&lt;/code&gt; has been overwritten by &lt;strong&gt;two extra zero-input steps&lt;/strong&gt;, decaying its true \(h_3\) by \(f_4 \cdot f_5\) and injecting bias drift!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Correct extraction&lt;/strong&gt;: Either use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pack_padded_sequence&lt;/code&gt; (so &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h_n&lt;/code&gt; stops at step 3 for Sentence 1) or index &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output[torch.arange(B), lengths - 1]&lt;/code&gt;—recovering &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output[0, 2, :]&lt;/code&gt; for Sentence 1 and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output[1, 4, :]&lt;/code&gt; for Sentence 2 with zero padding corruption.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;LSTM implementation:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Core Implementation&lt;/strong&gt; — NumPy/PyTorch LSTM training demos&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gate Analysis, GRU, and Pitfalls&lt;/strong&gt; — gate behavior, LSTM vs GRU, papers, takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker, English. Pause on each gate before writing the corresponding tensor op.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, English. The equations those ops must match.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Simple Explanation of GRU (Gated Recurrent Units)&lt;/td&gt;
          &lt;td&gt;Deep Learning Tutorial 37 (Tensorflow &amp;amp; Python)](https://www.youtube.com/watch?v=tOuXgORsXJ4) — codebasics, English. The GRU branch of the implementation lesson.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-01-02-02 Gate Analysis, GRU, and Pitfalls</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_01_02_02_Gates_GRU_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_01_02_02_Gates_GRU_and_Pitfalls</id>
   <content type="html">&lt;p&gt;Opening the hood of a trained LSTM on a noisy memory sequence—like &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[5, noise, noise, ..., 3]&lt;/code&gt;—lets you literally watch the gates think: the input gate spikes open on step 0 to store &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;5&lt;/code&gt;, slams shut across every noisy middle step while the forget gate holds near &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1.0&lt;/code&gt; to protect the stored number, and finally opens the output gate at the end. Comparing that behavior side-by-side against a &lt;strong&gt;GRU&lt;/strong&gt; clarifies when the GRU’s leaner 3-gate design matches LSTM accuracy at \(25\%\) lower cost, and when LSTM’s decoupled cell state still wins.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-gate-diagnostics-gru-trade-offs-and-practical-pitfalls&quot;&gt;Key ideas: Gate Diagnostics, GRU Trade-offs, and Practical Pitfalls&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Interpretable Gate Trajectories&lt;/strong&gt;: Plotting \(f_t, i_t, o_t\) over time exposes silent failure modes immediately—for instance, a saturated forget gate stuck near \(0.0\) means the LSTM has collapsed into a memoryless feedforward network.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LSTM vs. GRU Expressivity&lt;/strong&gt;: Because a GRU ties memory retention and new-input writing via \((1 - z_t) h_{t-1} + z_t \tilde{h}_t\), it cannot simultaneously keep \(100\%\) of old memory &lt;em&gt;and&lt;/em&gt; add a large new value; an LSTM can (\(f_t \approx 1, i_t \approx 1\)), giving LSTMs an edge on strict counting tasks (Weiss et al., 2018).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Recurrent Dropout Pitfall&lt;/strong&gt;: Applying standard naive dropout directly to the recurrent hidden-to-hidden transition corrupts memory across time steps; &lt;strong&gt;variational dropout&lt;/strong&gt; (Gal &amp;amp; Ghahramani, 2016) fixes this by using the &lt;em&gt;same&lt;/em&gt; dropout mask at every time step of a sequence, while PyTorch’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dropout&lt;/code&gt; argument applies only between stacked layers.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Padding &amp;amp; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pack_padded_sequence&lt;/code&gt;&lt;/strong&gt;: Feeding zero-padded variable-length sequences without packing wastes compute and pollutes the final hidden state with dozens of trailing zero updates.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-one-scalar-gru-step-vs-parameter-savings-over-lstm&quot;&gt;Worked example: One Scalar GRU Step vs. Parameter Savings Over LSTM&lt;/h3&gt;

&lt;p&gt;Let a scalar GRU have previous state \(h_{t-1} = 2.0\), input \(x_t = -1.0\), update gate \(z_t = \sigma(-1.5) \approx 0.1824\), reset gate \(r_t = \sigma(0.5) \approx 0.6225\), and candidate \(\tilde{h}_t = \tanh(0.5(r_t h_{t-1}) + x_t)\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the reset-modulated past state&lt;/strong&gt;:
\(r_t h_{t-1} = 0.6225 \times 2.0 = 1.2450.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the candidate hidden state&lt;/strong&gt;:
\(\tilde{h}_t = \tanh(0.5 \times 1.2450 - 1.0) = \tanh(0.6225 - 1.0) = \tanh(-0.3775) \approx -0.3605.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Interpolate old memory and new candidate via \(z_t\)&lt;/strong&gt;:
\(h_t = (1 - z_t) h_{t-1} + z_t \tilde{h}_t = (0.8176)(2.0) + (0.1824)(-0.3605) \approx 1.6352 - 0.0658 = 1.5694.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare parameter count against LSTM for \(d_x = 64, d_h = 128\)&lt;/strong&gt; (PyTorch two-bias convention):
    &lt;ul&gt;
      &lt;li&gt;LSTM: \(4 \times 128 \times (64 + 128 + 2) = 99{,}328\) params.&lt;/li&gt;
      &lt;li&gt;GRU: \(3 \times 128 \times (64 + 128 + 2) = 74{,}496\) params — an exact \(25.0\%\) reduction (\(24{,}832\) fewer weights).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Analyze gate behavior
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Analyzing LSTM Gate Activations&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create a simple manual LSTM to track gates
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm_analyze&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create sequence: [5, noise, noise, ..., 3]
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_sequence&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;extend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Forward pass tracking all gates
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hiddens&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cells&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lstm_analyze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                                         &lt;span class=&quot;n&quot;&gt;return_sequences&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gate activations through time (showing average across hidden dimensions):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Time | Forget | Input | Output | Cell State (avg)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;f_avg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;forget&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;i_avg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;o_avg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;c_avg&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cells&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Cell state magnitude
&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &amp;lt;-- Important input&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;or&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f_avg&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i_avg&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;o_avg&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  | &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c_avg&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;marker&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observations:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Forget gate often stays high (~0.9-1.0) to maintain memory&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Input gate opens for important inputs (first and last values)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Output gate controls what information is exposed&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;- Cell state accumulates information, maintaining magnitude&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now implement GRU for comparison:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GRUCell&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    GRU cell - simpler alternative to LSTM.
    
    GRU merges cell and hidden states, uses only 2 gates (vs LSTM&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s 3),
    resulting in ~25% fewer parameters. Often performs comparably to LSTM
    while being faster to train and easier to tune.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Two gates instead of three
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Reset
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Update
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Candidate
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;br&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        GRU has no separate cell state - simpler!
        
        Returns only new hidden state (which serves as both hidden and cell state)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;vstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Reset gate: how much past to use for candidate
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;r_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;br&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Update gate: how much to interpolate old vs new
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bz&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Candidate hidden state (uses reset previous state)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;combined_reset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;vstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;r_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h_tilde&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_reset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Interpolate between old and new
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# When z_t ≈ 0: keep old (h_t ≈ h_prev)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# When z_t ≈ 1: use new (h_t ≈ h_tilde)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_tilde&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;reset&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;r_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;update&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;candidate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_tilde&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Compare LSTM vs GRU on same task
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Comparing LSTM vs GRU&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LSTM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;lstm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GRUModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gru&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;GRU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;gru&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train both
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;gru_model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;GRUModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Count parameters
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lstm_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;gru_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gru_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;LSTM parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GRU parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gru_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GRU has &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gru_params&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm_params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;% fewer parameters&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Both can learn long-range dependencies effectively.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;GRU: Simpler, faster. LSTM: More flexible, sometimes better on complex tasks.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;The relationship between LSTMs and vanilla RNNs exemplifies a recurring pattern in deep learning: identifying failure modes of simple architectures and designing targeted solutions through architectural innovation. Vanilla RNNs fail on long sequences due to vanishing gradients during backpropagation through time. LSTMs solve this by creating a separate information pathway (the cell state) with additive rather than multiplicative updates, and by using gates to control information flow. This isn’t just fixing a bug—it’s a fundamental architectural change motivated by understanding the mathematics of gradient flow.&lt;/p&gt;

&lt;p&gt;The evolution from LSTM to GRU illustrates another important principle: simpler can be better when it preserves the essential mechanism. GRUs achieve similar performance to LSTMs for many tasks while having 25% fewer parameters and simpler dynamics (no separate cell state). The GRU’s design philosophy is minimalism—use the fewest mechanisms necessary to achieve the desired behavior. The update gate combines LSTM’s forget and input gates, reducing parameters while maintaining the crucial ability to control memory. The reset gate replaces the output gate’s functionality in a different way. For practitioners, this often means starting with GRU (simpler, faster) and only switching to LSTM if the task demonstrably benefits from its additional capacity.&lt;/p&gt;

&lt;p&gt;The connection to gating mechanisms in neural architectures more broadly reveals a powerful pattern. Gates—sigmoid-activated layers that output values in (0,1) used to modulate other values—appear throughout deep learning. Highway networks use gates to control skip connections. Attention mechanisms use gates (the attention weights) to select information. Neural Turing Machines use gates to control memory read/write. The pattern is consistent: when we need learnable control over information flow, we use gates. Understanding why this works—smooth differentiability, interpretability as probabilities, effectiveness at learning conditional behavior—helps appreciate this architectural motif.&lt;/p&gt;

&lt;p&gt;LSTMs and attention mechanisms have an interesting relationship. Both address long-range dependencies, but differently. LSTMs compress all past information into a fixed-size state, updated through gates. Attention allows direct access to all past states, selecting relevant ones through attention weights. This makes attention more powerful (no lossy compression) but more expensive (\(O(n^2)\) instead of \(O(n)\)). The Transformer’s success suggested that for many NLP tasks with sufficient compute, attention’s direct access outweighs LSTM’s efficiency. Yet for tasks with very long sequences or real-time constraints, LSTMs remain relevant.&lt;/p&gt;

&lt;p&gt;The concept of explicit memory management in LSTMs connects to computer science more broadly—the idea of caching important information, evicting stale data, and controlling access. Database systems, operating system memory management, and CPU caches all face similar challenges of deciding what to remember and what to forget with limited capacity. LSTMs learn analogous policies from data rather than having them hand-coded. This connection helps frame what LSTMs are doing: they’re learned, differentiable memory management systems.&lt;/p&gt;

&lt;p&gt;Finally, understanding LSTMs’ success and limitations informs architecture design more generally. LSTMs succeeded because they addressed a specific, well-understood problem (vanishing gradients) with a targeted solution (gated cell state). Their limitations (sequential processing, fixed-size state bottleneck) motivated further innovations (attention, Transformers). This progression from simple RNNs to complex LSTMs to attention-based Transformers shows how the field advances: identify limitations through analysis, design architectures addressing those limitations, discover new limitations, repeat. Each architecture teaches us something about the inductive biases and mechanisms needed for different types of sequential reasoning.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.bioinf.jku.at/publications/older/2604.pdf&quot;&gt;“Long Short-Term Memory” (1997)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Sepp Hochreiter, Jürgen Schmidhuber&lt;br /&gt;
This foundational paper introduced the LSTM architecture and rigorously analyzed why vanilla RNNs fail to learn long-range dependencies. Hochreiter and Schmidhuber showed mathematically that during backpropagation through time, gradients either vanish or explode exponentially unless the network is carefully constructed to avoid this. They proposed the LSTM with its constant error carousel (the cell state) as a solution, proving that LSTMs can in principle learn arbitrary long-range dependencies. The paper is remarkably prescient, addressing issues like memory capacity and proposing solutions that became standard (like forget gates, added in later work). While LSTMs took years to gain widespread adoption (partly due to limited computational resources and datasets at the time), this paper established the theoretical foundation and demonstrated LSTM’s advantages on carefully constructed tasks requiring long-term memory. It’s one of the most cited papers in all of deep learning and arguably enabled much of the progress in sequence modeling over the next two decades.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://doi.org/10.1162/089976600300015015&quot;&gt;“Learning to Forget: Continual Prediction with LSTM” (2000)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Felix A. Gers, Jürgen Schmidhuber, Fred Cummins&lt;br /&gt;
The original LSTM architecture lacked a mechanism to reset the cell state—it could only add information, not remove it. This led to saturation problems on long sequences where the cell state would fill up with outdated information. This paper introduced the forget gate, allowing the network to selectively clear parts of its memory when they’re no longer needed. This seemingly simple addition—one more gate that modulates the cell state update—made LSTMs dramatically more practical for real-world tasks. The paper demonstrated improved performance on continual learning tasks where the network must process multiple sequences and reset context between them. The forget gate has become a standard part of all LSTM implementations, and the paper illustrates how architectural details that seem minor can have major practical impacts. It also demonstrates the value of ongoing refinement—the best architectures often emerge through iterative improvements addressing practical issues discovered during application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1406.1078&quot;&gt;“Learning Phrase Representations using RNN Encoder-Decoder for Statistical Machine Translation” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Kyunghyun Cho, Bart van Merrienboer, Caglar Gulcehre, Dzmitry Bahdanau, Fethi Bougares, Holger Schwenk, Yoshua Bengio&lt;br /&gt;
This paper introduced the Gated Recurrent Unit (GRU) as a simpler alternative to LSTM while also proposing the encoder-decoder architecture for neural machine translation. The GRU’s design was motivated by LSTM’s complexity—could we achieve similar performance with fewer parameters and simpler dynamics? The paper showed that GRU’s two gates (reset and update) could control information flow nearly as effectively as LSTM’s three gates, while being easier to implement and faster to train. The empirical results on machine translation demonstrated that architectural simplification doesn’t necessarily hurt performance when the essential mechanisms (gating for controlling memory) are preserved. This paper influenced architecture design philosophy: favor simpler designs when they maintain the key properties, as simplicity aids debugging, tuning, and understanding. The encoder-decoder framework introduced here became standard for sequence-to-sequence tasks, whether using RNNs, LSTMs, GRUs, or eventually Transformers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1412.3555&quot;&gt;“Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Junyoung Chung, Caglar Gulcehre, KyungHyun Cho, Yoshua Bengio&lt;br /&gt;
This paper provided the first comprehensive empirical comparison of LSTM and GRU across multiple sequence modeling tasks including music modeling, speech recognition, and language modeling. The careful experimental methodology—controlling for hyperparameters, architecture depth, and training procedures—allowed fair comparison focusing on the architectural differences. The findings were nuanced: neither architecture consistently dominated across all tasks, but GRU often matched LSTM performance while training faster due to fewer parameters. The paper established that architecture choice should depend on specific task characteristics and constraints (dataset size, sequence length, computational budget) rather than being a universal recommendation. It also demonstrated how to properly evaluate architectural innovations—not just showing one good result but systematic comparison across diverse tasks with statistical rigor. This methodology has become standard in deep learning research.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1506.02078&quot;&gt;“Visualizing and Understanding Recurrent Networks” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Andrej Karpathy, Justin Johnson, Li Fei-Fei&lt;br /&gt;
This paper investigated what LSTMs learn by analyzing their internal representations on character-level language modeling. By examining activations of individual hidden units and gates, Karpathy demonstrated that LSTMs spontaneously develop interpretable internal structure. Some cells track quote characters (activating inside quotes, deactivating outside), others track indentation levels in code, others detect line endings or comment blocks. The forget gates learn to reset at sentence boundaries. This emergent structure wasn’t explicitly programmed but arose from the training objective of predicting the next character. The paper’s methodology—systematic analysis of individual units, gate activations, and error patterns—established approaches for interpretability analysis that have since been applied to all types of neural networks. It showed that LSTMs don’t just achieve good performance through opaque computation but develop meaningful internal representations that we can understand and validate. This interpretability makes LSTMs valuable not just for their performance but for providing insight into what patterns the model has discovered in data.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;The most common mistake when implementing LSTMs is initializing the forget gate bias to zero, like other biases. This causes the forget gate to start around 0.5 (from sigmoid of 0), meaning the network initially forgets half its cell state at each step. For most tasks, this aggressive forgetting early in training prevents the network from discovering that long-range dependencies matter. The solution is the “forget bias trick”: initialize \(\mathbf{b}_f = \mathbf{1}\) (a vector of ones). This makes the initial forget gate \(\sigma(0 + 1) \approx 0.73\), biasing toward retention. As training progresses, if forgetting is beneficial, the network can learn to reduce forget gate values. This simple initialization trick can mean the difference between an LSTM that trains successfully and one that never learns long-range dependencies.&lt;/p&gt;

&lt;p&gt;Exploding gradients, while less problematic in LSTMs than vanilla RNNs due to the cell state dynamics, can still occur. The issue now typically comes from the gates themselves. If forget gate saturates at 1 and input gate allows large candidate values, the cell state can grow unboundedly: \(c_t = 1 \cdot c_{t-1} + 1 \cdot \tilde{c}_t\) repeated many times gives exponential growth. This manifests as parameters becoming NaN during training or loss exploding. The standard solution remains gradient clipping, but LSTM-specific solutions include:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Constraining candidate values through tanh (which LSTM already does)&lt;/li&gt;
  &lt;li&gt;Using layer normalization to keep cell states in reasonable ranges&lt;/li&gt;
  &lt;li&gt;Careful weight initialization to prevent gate saturation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;A subtle issue is the coupling between forget and input gates. In principle, these gates can learn conflicting behaviors—forget old information (\(f_t \approx 0\)) while not adding new (\(i_t \approx 0\)), causing the cell state to vanish. GRU avoids this by coupling them: \(1 - z_t\) keeps old, \(z_t\) adds new, guaranteeing at least one is substantial. Some LSTM variants also couple gates, though the standard LSTM allows them to be independent. In practice, proper initialization and sufficient training data usually allow LSTMs to learn sensible gate coordination, but when debugging LSTM training failures, checking for pathological gate behaviors (all gates near 0 or 1) can reveal issues.&lt;/p&gt;

&lt;p&gt;The choice between LSTM and GRU has generated much discussion but few universal conclusions. As a practical heuristic: start with GRU because it’s simpler and faster. If performance plateaus and you have abundant data, try LSTM to see if its additional capacity helps. For very long sequences or complex temporal patterns, LSTM’s separate cell state often provides advantages. For tasks with limited data or where training time is constrained, GRU’s efficiency often makes it preferable. Always validate on your specific problem rather than assuming one architecture is universally better.&lt;/p&gt;

&lt;p&gt;When stacking multiple LSTM layers, a common question is whether to apply dropout between layers. The answer: yes, but carefully. Apply dropout to the outputs (hidden states) passed between layers, not to the cell states or the recurrent connections within a layer. Typical dropout rates for LSTMs are lower than for feedforward networks—0.2 to 0.3 rather than 0.5—because LSTMs are already quite regularized through their gating mechanisms. Too much dropout can prevent LSTMs from learning the long-range dependencies they’re designed for, as the random dropping disrupts information flow through time.&lt;/p&gt;

&lt;p&gt;Bidirectional LSTMs process sequences in both forward and backward directions, combining information from both at each time step: \(\mathbf{h}_t = [\overrightarrow{\mathbf{h}}_t; \overleftarrow{\mathbf{h}}_t]\). This doubles parameters and computation but provides richer representations when future context is available. However, bidirectional LSTMs can’t be used for real-time sequential prediction (where we must predict before seeing the complete sequence) or for autoregressive generation. They’re powerful for tasks like machine translation (where we have the complete source sentence) or speech recognition (where we can process the complete audio before transcribing), but inappropriate for online prediction or generation tasks.&lt;/p&gt;

&lt;p&gt;A powerful technique for analysis and debugging is visualizing gate activations over time. Plot \(f_t\), \(i_t\), \(o_t\) for each dimension as the network processes a sequence. Patterns reveal what the network has learned: forget gates dropping at sentence boundaries, input gates opening for content words and closing for function words, output gates exposing information when decisions are needed. This visualization not only helps debug training issues but provides insight into what linguistic or sequential structure the network has discovered, making LSTMs more interpretable than many other deep learning architectures.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Long Short-Term Memory networks solved the vanishing gradient problem that limited vanilla RNNs by introducing a cell state with gated connections that allow information to flow through time with minimal degradation. The architecture uses three gates—forget, input, and output—each implemented as sigmoid layers, to control what information is retained, added, or exposed at each time step. This gating mechanism enables learning dependencies spanning hundreds of time steps, making LSTMs successful for machine translation, speech recognition, and many other sequential tasks that require long-term memory. The cell state provides an additive update path where gradients can flow more easily than through the multiplicative, nonlinear updates of vanilla RNN hidden states. Gated Recurrent Units simplify LSTMs by using two gates instead of three and merging cell and hidden states, often achieving comparable performance with fewer parameters. The choice between LSTM and GRU depends on task complexity, data availability, and computational constraints, with GRU often being a good starting point due to its simplicity. Understanding LSTMs deeply means appreciating not just the equations but why each component exists—how gates enable learnable memory management, why the cell state uses additive updates, how these design choices enable gradient flow—and recognizing LSTMs as a solution to the specific challenge of learning long-range dependencies in sequential data through gradient-based optimization.&lt;/p&gt;

&lt;p&gt;The LSTM’s success demonstrates that careful architectural design informed by understanding of gradient dynamics can overcome fundamental limitations, a lesson that has influenced neural architecture design far beyond recurrent networks.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Simple Explanation of GRU (Gated Recurrent Units)&lt;/td&gt;
          &lt;td&gt;Deep Learning Tutorial 37 (Tensorflow &amp;amp; Python)](https://www.youtube.com/watch?v=tOuXgORsXJ4) — codebasics, English. GRU merges the forget and input decisions, which is this lesson’s comparison.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker, English. The LSTM gates the comparison starts from.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, English. Where those gates fail if the sequence is still longer than the cell can carry.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-01-02-01 LSTM Core Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_01_02_01_LSTM_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_01_02_01_LSTM_Core_Code</id>
   <content type="html">&lt;p&gt;Implementing an LSTM from scratch in NumPy—and then comparing it against PyTorch’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM&lt;/code&gt; on a synthetic long-range memory benchmark (such as remembering the first number in a noisy sequence and adding it to the last)—reveals two crucial engineering insights. First, fusing the four gate weight matrices into a single matrix multiply dramatically simplifies code and speeds up execution. Second, LSTM backpropagation requires carrying &lt;em&gt;two&lt;/em&gt; separate gradient tensors backward in time: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dh_next&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dc_next&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-implementation-mechanics-of-lstm-code&quot;&gt;Key ideas: Implementation Mechanics of LSTM Code&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Fused 4-Gate Matrix Multiplication&lt;/strong&gt;: Concatenating \([h_{t-1}, x_t] \in \mathbb{R}^{d_h + d_x}\) and multiplying by a single matrix \(W \in \mathbb{R}^{4 d_h \times (d_h + d_x)}\) produces all four pre-activations in one BLAS call—the exact layout used internally by PyTorch’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_ih_l0&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_hh_l0&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dual State Tuple &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(h_t, c_t)&lt;/code&gt;&lt;/strong&gt;: Unlike &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM&lt;/code&gt; takes and returns a tuple &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(h, c)&lt;/code&gt;. Forgetting to pass or detach &lt;em&gt;both&lt;/em&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;c&lt;/code&gt; across truncated BPTT chunks causes subtle memory leaks or corrupted state resets.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Forget-Gate Bias Initialization&lt;/strong&gt;: Setting the forget-gate slice of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_hh&lt;/code&gt; to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+1.0&lt;/code&gt; (Jozefowicz et al., 2015) prevents early-epoch memory erasure on synthetic copy/addition benchmarks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bidirectional &amp;amp; Multi-Layer Shapes&lt;/strong&gt;: For &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;num_layers=L&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bidirectional=True&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_first=True&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output&lt;/code&gt; has shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, T, 2*d_h)&lt;/code&gt; while &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h_n&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;c_n&lt;/code&gt; always have shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(2*L, N, d_h)&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-exact-pytorch-nnlstm-parameter-count--gate-slice-indexing&quot;&gt;Worked example: Exact PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM&lt;/code&gt; Parameter Count &amp;amp; Gate Slice Indexing&lt;/h3&gt;

&lt;p&gt;Consider &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.LSTM(input_size=16, hidden_size=32, num_layers=1, batch_first=True)&lt;/code&gt;:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Weight &amp;amp; bias tensor shapes inside PyTorch&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_ih_l0&lt;/code&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4 * 32, 16) = (128, 16)&lt;/code&gt; \(\to 2{,}048\) params.&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_hh_l0&lt;/code&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(4 * 32, 32) = (128, 32)&lt;/code&gt; \(\to 4{,}096\) params.&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_ih_l0&lt;/code&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(128,)&lt;/code&gt; \(\to 128\) params.&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_hh_l0&lt;/code&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(128,)&lt;/code&gt; \(\to 128\) params.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Total parameters&lt;/strong&gt;:
\(2{,}048 + 4{,}096 + 128 + 128 = 6{,}400.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;PyTorch gate ordering (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;i, f, g, o&lt;/code&gt;)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Indices &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0:32&lt;/code&gt; = input gate \(i_t\)&lt;/li&gt;
      &lt;li&gt;Indices &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;32:64&lt;/code&gt; = &lt;strong&gt;forget gate \(f_t\)&lt;/strong&gt; (this is the exact slice you initialize to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+1.0&lt;/code&gt;!)&lt;/li&gt;
      &lt;li&gt;Indices &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;64:96&lt;/code&gt; = cell candidate \(g_t = \tilde{C}_t\)&lt;/li&gt;
      &lt;li&gt;Indices &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;96:128&lt;/code&gt; = output gate \(o_t\)
Knowing the exact &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;32:64&lt;/code&gt; slice prevents initializing the wrong gate when tuning long-range memory models.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Let’s implement LSTM from scratch to understand every operation, then compare with PyTorch’s optimized version:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMCell&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Single LSTM cell implementing one time step of computation.
    
    This implementation makes every operation explicit. Modern frameworks
    fuse these operations for efficiency, but our goal is understanding,
    not speed. We&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ll see exactly how gates modulate information flow.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Initialize LSTM cell with careful weight initialization.
        
        We use Xavier/Glorot initialization scaled for sigmoid and tanh.
        This initialization scheme was specifically designed to maintain
        reasonable activation and gradient scales, preventing both vanishing
        and explosion early in training.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Combined input dimension (hidden + input)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initialize weights for four gates
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Using Xavier initialization: scale by 1/√(combined_size)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wi&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;WC&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;scale&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initialize biases
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Forget gate bias often initialized to 1 to encourage remembering initially
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# This is called &quot;forget bias trick&quot; - start by remembering everything
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Start with high forget gate!
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bi&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bC&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Numerically stable sigmoid&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                       &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        One LSTM time step.
        
        x_t: current input (input_size, 1)
        h_prev: previous hidden state (hidden_size, 1)
        c_prev: previous cell state (hidden_size, 1)
        
        Returns:
            h_t: new hidden state
            c_t: new cell state
            gates: dictionary of gate values (for analysis/debugging)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Concatenate previous hidden state and current input
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# This combined vector influences all gates
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;vstack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute all gates
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Each gate is a learned sigmoid function of the combined input
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;f_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Forget gate
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;i_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wi&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Input gate
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;C_tilde&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;WC&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bC&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Candidate values
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;o_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;combined&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Output gate
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Update cell state: forget old, add new
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# This is THE key equation of LSTM
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Notice: minimal nonlinearity, mostly linear combination
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;c_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C_tilde&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute new hidden state from cell state
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# tanh squashes unbounded cell state to [-1, 1]
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# output gate modulates what&apos;s exposed
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;o_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Return states and gates (gates useful for visualization/debugging)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;forget&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;input&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;o_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;candidate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C_tilde&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Full LSTM network for sequence processing.
    
    Wraps LSTMCell to process entire sequences, maintaining states across
    time steps. This is the complete LSTM as used in practice.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cell&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMCell&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Output projection (maps hidden state to predictions)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;return_sequences&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Process entire sequence.
        
        inputs: list of input vectors [x_1, ..., x_T]
        return_sequences: if True, return outputs at all time steps
                         if False, return only final output
        
        Returns:
            outputs: predictions at each time step (if return_sequences=True)
                     or just final prediction (if False)
            hidden_states: all hidden states [h_0, ..., h_T]
            cell_states: all cell states [c_0, ..., c_T]
            all_gates: gate values at each time step (for analysis)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Initialize states to zero
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Track evolution through time
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cell_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Process sequence step by step
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# LSTM cell update
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cell&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;cell_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Compute output from hidden state
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;y_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;return_sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cell_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# For sequence classification, use only final output
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cell_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;all_gates&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate LSTM learning long-range dependencies
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;LSTM: Learning Long-Range Dependencies&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create task requiring long-term memory
# Remember first number, ignore middle numbers, predict first + last
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_memory_task&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Task: Given sequence [a, x, x, x, ..., x, b], predict a + b
    
    This requires remembering &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; across seq_length-2 intervening values,
    exactly the kind of long-range dependency vanilla RNNs struggle with.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;targets_list&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Random first and last numbers
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;first&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;last&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Fill middle with noise
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;sequence&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;first&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])]&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;last&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]))&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;first&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;last&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sequence&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;targets_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets_list&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create LSTM and data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_memory_task&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_samples&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simple training loop (gradient descent on small dataset)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training LSTM on long-range dependency task...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Task: Remember first number across 13 noisy numbers, add to last number&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Process each sequence
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hiddens&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cells&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lstm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;return_sequences&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Loss (MSE)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# For demonstration, we&apos;ll skip the backward pass implementation
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# (BPTT for LSTM is complex - modern frameworks handle it)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# In practice, use PyTorch!
&lt;/span&gt;    
    &lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Average Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Note: Full LSTM backpropagation is complex - use PyTorch in practice!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Let&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s see PyTorch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s implementation...&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# PyTorch LSTM implementation
&lt;/span&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    LSTM using PyTorch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s optimized implementation.
    
    PyTorch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s LSTM is highly optimized, using cuDNN kernels on GPU
    for maximum performance. It handles all the gate computations,
    state management, and backpropagation automatically.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;LSTMNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# PyTorch LSTM module
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# num_layers &amp;gt; 1 stacks LSTMs (output of one feeds into next)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# dropout between layers helps regularize stacked LSTMs
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lstm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;LSTM&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                           &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dropout&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.0&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Output layer
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (batch, seq_len, input_size)
        hidden: optional tuple of (h_0, c_0)
        
        Returns:
            output: (batch, seq_len, output_size) if return_sequences
                    or (batch, output_size) if not
            (h_n, c_n): final hidden and cell states
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# LSTM returns:
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# - lstm_out: hidden states at all time steps
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# - (h_n, c_n): final hidden and cell states for all layers
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;lstm_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;lstm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Use final time step for sequence classification
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# or all time steps for sequence-to-sequence
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;final_hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lstm_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Last time step
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;final_hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c_n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train on memory task
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training PyTorch LSTM on Long-Range Memory Task&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Convert data to tensors
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;prepare_torch_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Convert list of sequences to batched tensors&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Find max length (for padding)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;max_len&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Pad sequences and stack
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets_list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Convert sequence to tensor and pad
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;seq_tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; 
                                  &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flatten&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Stack into batched tensor
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (n_samples, seq_len, 1)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (n_samples, 1)
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;prepare_torch_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training data shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (200, 15, 1)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Create model
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LSTMNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MSELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training loop
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;300&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# BPTT through LSTM happens here automatically
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Gradient clipping (good practice for RNNs/LSTMs)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip_grad_norm_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_norm&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test on new examples
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Testing LSTM Memory Capability&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Create test sequences
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;test_cases&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;3.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;8.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;7.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;9.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;9.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;10.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_sum&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_cases&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;seq_tensor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;unsqueeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;First: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Last: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  True sum: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_sum&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Predicted: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Error: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true_sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;LSTM successfully learned to remember first value across many steps!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This demonstrates its advantage over vanilla RNNs for long-range dependencies.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Let’s also visualize gate activations to understand what LSTM learns:&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker, English. Each gate is an affine map and a sigmoid or tanh, which is the core cell you code.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, English. Use this to name the tensors (cell versus hidden) before you allocate them.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Simple Explanation of GRU (Gated Recurrent Units)&lt;/td&gt;
          &lt;td&gt;Deep Learning Tutorial 37 (Tensorflow &amp;amp; Python)](https://www.youtube.com/watch?v=tOuXgORsXJ4) — codebasics, English. A smaller cell to implement after the LSTM cell works.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06-01-01 LSTM and GRU Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_01_01_LSTM_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_01_01_LSTM_Theory</id>
   <content type="html">&lt;p&gt;Inside an LSTM cell, four separate affine projections fire in parallel at every single time step—forget gate \(f_t\), input gate \(i_t\), candidate memory \(\tilde{C}_t\), and output gate \(o_t\). Without a clear mental map of how those four vectors interact, the equations look like an intimidating wall of subscripts. Once you trace one concrete vector through the gates and differentiate \(\partial C_t / \partial C_{t-1}\), however, the entire architecture snaps into crystalline clarity: the LSTM is simply a differentiable computer register with learned read, write, and erase instructions.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-exact-equations-and-calculus-of-lstm--gru&quot;&gt;Key ideas: Exact Equations and Calculus of LSTM &amp;amp; GRU&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;The Four-Gate Decomposition&lt;/strong&gt;: Stacking \([h_{t-1}, x_t]\) lets all four LSTM projections execute as one fused GEMM of width \(4 d_h\), slicing the result into \((f_t, i_t, \tilde{C}_t, o_t)\) before applying \(\sigma\) to the three gates and \(\tanh\) to the candidate.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Uninterrupted Cell-State Derivative&lt;/strong&gt;: Differentiating \(C_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t\) yields a direct additive term \(\frac{\partial C_t}{\partial C_{t-1}} = \operatorname{diag}(f_t) + \text{gate paths}\). Even when nonlinearities saturate elsewhere, the diagonal \(f_t\) highway preserves error flow without multiplying by \(W_{hh}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GRU Coupled Gating&lt;/strong&gt;: A GRU uses reset gate \(r_t\) to modulate how much past state enters the candidate \(\tilde{h}_t = \tanh(W_h [r_t \odot h_{t-1}, x_t])\) and update gate \(z_t\) to interpolate convexly: \(h_t = (1 - z_t) \odot h_{t-1} + z_t \odot \tilde{h}_t\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter Scaling Law&lt;/strong&gt;: For input dimension \(d_x\) and hidden dimension \(d_h\), an LSTM has \(4 d_h (d_h + d_x + 1)\) parameters (with one bias per gate), whereas a GRU has \(3 d_h (d_h + d_x + 1)\)—exactly \(3/4\) the size of an LSTM.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-hand-tracing-one-complete-scalar-lstm-step&quot;&gt;Worked example: Hand-Tracing One Complete Scalar LSTM Step&lt;/h3&gt;

&lt;p&gt;Suppose at step \(t\) we have previous cell state \(C_{t-1} = 2.0\), previous hidden state \(h_{t-1} = 0.5\), and input \(x_t = 1.0\). After computing the four linear pre-activations, suppose we obtain:
\(z_f = 2.0,\quad z_i = -1.0,\quad z_g = 1.5,\quad z_o = 0.0.\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate the three sigmoid gates and candidate memory&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Forget gate: \(f_t = \sigma(2.0) = \frac{1}{1 + e^{-2}} \approx 0.8808\) (keep \(88\%\) of old memory).&lt;/li&gt;
      &lt;li&gt;Input gate: \(i_t = \sigma(-1.0) = \frac{1}{1 + e^{1}} \approx 0.2689\) (admit \(27\%\) of new candidate).&lt;/li&gt;
      &lt;li&gt;Candidate memory: \(\tilde{C}_t = \tanh(1.5) \approx 0.9051\).&lt;/li&gt;
      &lt;li&gt;Output gate: \(o_t = \sigma(0.0) = 0.5000\) (expose half of the squashed cell state).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Update the cell state \(C_t\)&lt;/strong&gt;:
\(C_t = f_t C_{t-1} + i_t \tilde{C}_t = (0.8808)(2.0) + (0.2689)(0.9051) \approx 1.7616 + 0.2434 = 2.0050.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the new working hidden state \(h_t\)&lt;/strong&gt;:
\(h_t = o_t \tanh(C_t) = 0.5000 \times \tanh(2.0050) \approx 0.5000 \times 0.9644 = 0.4822.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify gradient highway&lt;/strong&gt;: The direct cell-to-cell derivative is \(\frac{\partial C_t}{\partial C_{t-1}} = f_t = 0.8808\)—preserving nearly \(90\%\) of the gradient regardless of the output gate’s value!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;long-short-term-memory-conquering-the-vanishing-gradient&quot;&gt;Long Short-Term Memory: Conquering the Vanishing Gradient&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter06/lstm_architecture.png&quot; alt=&quot;LSTM Cell Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Cấu trúc chi tiết của một LSTM cell với các cổng điều khiển. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;The Long Short-Term Memory (LSTM) network represents one of the most important architectural innovations in the history of recurrent neural networks. Introduced by Hochreiter and Schmidhuber in 1997, LSTMs were specifically designed to solve the vanishing gradient problem that plagued vanilla RNNs, enabling neural networks to learn dependencies spanning hundreds or even thousands of time steps. While the architecture might seem complex at first glance with its multiple gates and cell state, each component serves a specific, carefully designed purpose in managing the flow of information through time.&lt;/p&gt;

&lt;p&gt;Understanding why LSTMs were necessary requires appreciating the fundamental challenge they address. As we saw with vanilla RNNs, gradients during backpropagation through time must pass through repeated matrix multiplications by the recurrent weight matrix and activation function derivatives. When these operations consistently suppress signals (as tanh derivatives do when activations saturate), gradients vanish exponentially with the number of time steps. This makes learning long-range dependencies—understanding that a word at the beginning of a paragraph influences interpretation of a sentence at the end—nearly impossible for vanilla RNNs in practice.&lt;/p&gt;

&lt;p&gt;The LSTM’s solution is elegant in its core idea, though complex in execution: create explicit pathways for information to flow unchanged through time. The key innovation is the cell state, a separate pathway that runs parallel to the hidden state. The cell state can maintain information across many time steps with only minor linear interactions, avoiding the repeated nonlinear transformations that cause vanishing gradients in vanilla RNNs. Think of the cell state as a highway for information transmission through time, while the hidden state handles moment-to-moment processing.&lt;/p&gt;

&lt;p&gt;But simply having a separate cell state isn’t sufficient—we need mechanisms to control what information enters the cell state, what information is retained or forgotten, and what information is exposed to the rest of the network. This is where gates come in. LSTMs use three types of gates—forget gates, input gates, and output gates—each implemented as a sigmoid neural network layer that outputs values between 0 and 1. These gates act as learnable switches, determining how much information flows through different paths. The sigmoid is crucial here: it provides smooth gradients (unlike hard thresholds) while its output range [0,1] makes it interpretable as a probability or proportion—how much to forget, how much to add, how much to output.&lt;/p&gt;

&lt;p&gt;The genius of the LSTM architecture lies in how these gates work together to create flexible, learnable memory dynamics. The forget gate can clear outdated information from the cell state. The input gate can selectively add new information. The output gate can control what parts of the cell state are exposed to the downstream network. All of this happens through learned parameters that adapt to the specific patterns in the training data. The network learns not just what to remember but when to remember, when to forget, and when to act on its memory—meta-cognitive skills that emerge from the architecture’s inductive bias.&lt;/p&gt;

&lt;p&gt;LSTMs became enormously successful, dominating sequence modeling from the late 1990s through the mid-2010s. They enabled breakthroughs in machine translation, speech recognition, handwriting recognition, and many other sequential tasks. Even after Transformers emerged as the dominant architecture for NLP, LSTMs remain important: they use less memory than Transformers (\(O(n)\) vs \(O(n^2)\)), process sequences naturally online (unlike Transformers which typically process entire sequences), and for certain tasks with very long sequences or online processing requirements, still offer advantages. Understanding LSTMs deeply means understanding both a historically important architecture and ongoing principles about managing information flow in recurrent computations.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;The mathematical formulation of LSTMs reveals how multiple components work together to create controllable memory dynamics. At each time step \(t\), an LSTM maintains two state vectors: the hidden state \(\mathbf{h}_t\) (like vanilla RNNs) and the cell state \(\mathbf{c}_t\) (the LSTM’s innovation). Given input \(\mathbf{x}_t\) and previous states \(\mathbf{h}_{t-1}\) and \(\mathbf{c}_{t-1}\), the LSTM computes new states through a carefully orchestrated sequence of operations.&lt;/p&gt;

&lt;p&gt;First, we concatenate the previous hidden state and current input into a single vector: \([\mathbf{h}_{t-1}; \mathbf{x}_t]\). This concatenation appears in all gate computations, meaning each gate considers both what’s happening now (\(\mathbf{x}_t\)) and what the network was previously thinking about (\(\mathbf{h}_{t-1}\)). This design allows gates to make contextual decisions—whether to forget might depend on both the current input and previous context.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;forget gate&lt;/strong&gt; determines what information to discard from the cell state:&lt;/p&gt;

\[\mathbf{f}_t = \sigma(\mathbf{W}_f \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_f)\]

&lt;p&gt;The sigmoid activation ensures \(\mathbf{f}_t \in (0,1)\), which we can interpret as “proportion to keep.” When \(f_t^{(i)} \approx 1\), we keep nearly all of cell state dimension \(i\). When \(f_t^{(i)} \approx 0\), we forget nearly everything. The network learns through backpropagation when forgetting helps—for example, when starting a new sentence, we might forget subject-verb agreement information from the previous sentence.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;input gate&lt;/strong&gt; controls what new information to add to the cell state. It consists of two parts: a gate determining how much to add, and a candidate cell state determining what to add:&lt;/p&gt;

\[\mathbf{i}_t = \sigma(\mathbf{W}_i \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_i)\]

\[\tilde{\mathbf{c}}_t = \tanh(\mathbf{W}_C \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_C)\]

&lt;p&gt;The candidate \(\tilde{\mathbf{c}}_t\) uses tanh to create values in \([-1, 1]\), representing potential updates to the cell state. The input gate \(\mathbf{i}_t\) then moderates how much of this candidate to actually use. This two-component design provides flexibility: the candidate can propose updates based on the input, while the gate decides whether now is the right time to update memory.&lt;/p&gt;

&lt;p&gt;The cell state update combines forgetting old information and adding new information:&lt;/p&gt;

\[\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t\]

&lt;p&gt;This equation is the heart of the LSTM. The Hadamard (element-wise) product \(\mathbf{f}_t \odot \mathbf{c}_{t-1}\) selectively retains information from the previous cell state. The second term \(\mathbf{i}_t \odot \tilde{\mathbf{c}}_t\) adds selectively chosen new information. Notice this is a weighted sum with minimal nonlinearity—just the element-wise multiplications by the gates. Crucially, there’s no matrix multiplication by recurrent weights here, no tanh squashing the entire state. This is why gradients can flow through the cell state more easily than through vanilla RNN hidden states.&lt;/p&gt;

&lt;p&gt;The gradient flow analysis makes this explicit. When backpropagating through the cell state update:&lt;/p&gt;

\[\frac{\partial \mathbf{c}_t}{\partial \mathbf{c}_{t-1}} = \mathbf{f}_t\]

&lt;p&gt;The gradient is simply the forget gate values! If the forget gate is consistently near 1 (which the network can learn to do when long-term memory is needed), gradients flow backward through time nearly unchanged. This is a dramatic improvement over vanilla RNNs where:&lt;/p&gt;

\[\frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-1}} = \text{diag}(\tanh&apos;(\mathbf{z}_t)) \mathbf{W}_{hh}\]

&lt;p&gt;involves both the weight matrix and activation derivatives, typically causing exponential decay.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;output gate&lt;/strong&gt; determines what information from the cell state to expose to the rest of the network:&lt;/p&gt;

\[\mathbf{o}_t = \sigma(\mathbf{W}_o \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_o)\]

\[\mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t)\]

&lt;p&gt;We apply tanh to the cell state (squashing it to \([-1,1]\)) before the output gate modulates it. Why tanh here? The cell state can grow unbounded through repeated additions, so tanh normalizes it before exposure. The output gate then decides what to show—perhaps the network has information in the cell state that’s useful for future computation but not relevant to the current output.&lt;/p&gt;

&lt;p&gt;Counting parameters reveals the cost of LSTM’s sophistication. With input dimension \(d_x\), hidden dimension \(d_h\), an LSTM has:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Forget gate: \((d_h + d_x) \times d_h + d_h\) parameters (matrix + bias)&lt;/li&gt;
  &lt;li&gt;Input gate: \((d_h + d_x) \times d_h + d_h\) parameters&lt;/li&gt;
  &lt;li&gt;Candidate: \((d_h + d_x) \times d_h + d_h\) parameters&lt;/li&gt;
  &lt;li&gt;Output gate: \((d_h + d_x) \times d_h + d_h\) parameters&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Total: \(4[(d_h + d_x) \times d_h + d_h]\) parameters, about 4× more than vanilla RNN. This is the price of controllable memory—more parameters to learn, more computation per time step, but dramatically better ability to learn long-range dependencies.&lt;/p&gt;

&lt;p&gt;The Gated Recurrent Unit (GRU), introduced by Cho et al. in 2014, simplifies LSTMs while retaining most benefits. GRUs merge the cell and hidden states, use only two gates instead of three, and have about 25% fewer parameters. The GRU equations:&lt;/p&gt;

&lt;p&gt;\(\mathbf{r}_t = \sigma(\mathbf{W}_r \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t])\) (reset gate: how much past to use)&lt;/p&gt;

&lt;p&gt;\(\mathbf{z}_t = \sigma(\mathbf{W}_z \cdot [\mathbf{h}_{t-1}; \mathbf{x}_t])\) (update gate: how much past to keep)&lt;/p&gt;

&lt;p&gt;\(\tilde{\mathbf{h}}_t = \tanh(\mathbf{W} \cdot [\mathbf{r}_t \odot \mathbf{h}_{t-1}; \mathbf{x}_t])\) (candidate hidden state)&lt;/p&gt;

&lt;p&gt;\(\mathbf{h}_t = (1 - \mathbf{z}_t) \odot \mathbf{h}_{t-1} + \mathbf{z}_t \odot \tilde{\mathbf{h}}_t\) (interpolate between old and new)&lt;/p&gt;

&lt;p&gt;The update gate \(\mathbf{z}_t\) acts like a combined forget-and-input gate, deciding how much to interpolate between the previous state and the candidate. When \(z_t^{(i)} \approx 0\), dimension \(i\) keeps its old value (like forget gate ≈ 1, input gate ≈ 0 in LSTM). When \(z_t^{(i)} \approx 1\), it uses the new candidate (like forget gate ≈ 0, input gate ≈ 1). This coupling reduces parameters while maintaining the ability to control information flow.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;To build genuine intuition for how LSTMs manage long-range dependencies, let’s trace through a concrete linguistic example: processing the sentence “The cat, which we found in the garden, was hungry” to predict whether the verb should be singular or plural (“was” vs “were”).&lt;/p&gt;

&lt;p&gt;This example is challenging for vanilla RNNs because the subject “cat” (singular) appears early, followed by a relative clause “which we found in the garden” that could mislead the model with the plural “we,” and only then comes the verb that must agree with “cat.” A vanilla RNN must maintain the “cat is singular” information through processing six intervening words, during which the hidden state undergoes six transformations that might corrupt or erase this information.&lt;/p&gt;

&lt;p&gt;Let’s trace what an LSTM might learn to do. When processing “cat,” the input gate allows important information (this is the subject, it’s singular) to enter the cell state. The cell state now contains something like “subject = cat, number = singular.” As we process the relative clause, the forget gate learns to keep this subject information (\(f_t \approx 1\) for dimensions encoding subject number) while the input gate allows information about “we found in the garden” to enter other dimensions of the cell state. Crucially, the subject information persists nearly unchanged through these steps because the forget gate protects it.&lt;/p&gt;

&lt;p&gt;When we finally reach the position where we must generate the verb, the output gate learns to expose the subject number information from the cell state. The downstream layers can then use this information to choose “was” over “were.” The relative clause information might be gated off (\(o_t \approx 0\) for those dimensions) since it’s not relevant for verb conjugation.&lt;/p&gt;

&lt;p&gt;Let’s make this concrete with simplified numbers. Suppose our cell state has just two dimensions: subject-number and clause-context. After processing “cat”:&lt;/p&gt;

&lt;p&gt;\(\mathbf{c}_{\text{cat}} = \begin{bmatrix} 0.9 \\ 0.1 \end{bmatrix}\) (strongly singular, little clause context)&lt;/p&gt;

&lt;p&gt;As we process “which we found” (plural), the forget gate for subject-number stays high:&lt;/p&gt;

&lt;p&gt;\(\mathbf{f}_{\text{which}} = \begin{bmatrix} 0.95 \\ 0.1 \end{bmatrix}\) (keep subject info, forget old clause info)&lt;/p&gt;

&lt;p&gt;The input gate allows clause information:&lt;/p&gt;

&lt;p&gt;\(\mathbf{i}_{\text{which}} = \begin{bmatrix} 0.05 \\ 0.9 \end{bmatrix}\), \(\tilde{\mathbf{c}}_{\text{which}} = \begin{bmatrix} 0.2 \\ 0.7 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;After update:&lt;/p&gt;

\[\mathbf{c}_{\text{which}} = \begin{bmatrix} 0.95 \\ 0.1 \end{bmatrix} \odot \begin{bmatrix} 0.9 \\ 0.1 \end{bmatrix} + \begin{bmatrix} 0.05 \\ 0.9 \end{bmatrix} \odot \begin{bmatrix} 0.2 \\ 0.7 \end{bmatrix} = \begin{bmatrix} 0.865 \\ 0.64 \end{bmatrix}\]

&lt;p&gt;The subject-number information (0.865) has degraded only slightly (from 0.9), while clause context has updated. This selective preservation is what enables long-range dependencies.&lt;/p&gt;

&lt;p&gt;The three-gate design might seem overengineered, but each gate serves a distinct purpose that becomes clear when considering different linguistic phenomena. The forget gate handles context switches (new sentences, topic changes). The input gate manages relevance filtering (not all information deserves storage). The output gate controls exposure (information might be worth remembering but not worth acting on immediately). This three-way decomposition provides fine-grained control over memory dynamics that proves essential for complex sequential tasks.&lt;/p&gt;

&lt;p&gt;Comparing LSTMs to biological memory systems provides another angle of intuition. Human working memory doesn’t simply accumulate all experiences—we forget what’s irrelevant (forget gate), selectively encode important new information (input gate), and retrieve different memories in different contexts (output gate). While LSTMs are far simpler than biological memory, they capture this fundamental principle that effective memory requires not just storage but selective reading, writing, and forgetting.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation-1&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;Let’s build up the LSTM equations systematically, understanding each component’s role in the larger system. At time step \(t\), we have inputs \(\mathbf{x}_t \in \mathbb{R}^{d_x}\), previous hidden state \(\mathbf{h}_{t-1} \in \mathbb{R}^{d_h}\), and previous cell state \(\mathbf{c}_{t-1} \in \mathbb{R}^{d_h}\). We’ll compute new states \(\mathbf{h}_t\) and \(\mathbf{c}_t\) through the following sequence of operations.&lt;/p&gt;

&lt;p&gt;First, all gates operate on the concatenation \([\mathbf{h}_{t-1}; \mathbf{x}_t] \in \mathbb{R}^{d_h + d_x}\). Let’s define this explicitly:&lt;/p&gt;

\[\mathbf{z}_t = [\mathbf{h}_{t-1}; \mathbf{x}_t]\]

&lt;p&gt;Now the forget gate computation:&lt;/p&gt;

\[\mathbf{f}_t = \sigma(\mathbf{W}_f \mathbf{z}_t + \mathbf{b}_f)\]

&lt;p&gt;where \(\mathbf{W}_f \in \mathbb{R}^{d_h \times (d_h + d_x)}\) and \(\mathbf{b}_f \in \mathbb{R}^{d_h}\). The sigmoid ensures each component of \(\mathbf{f}_t\) lies in \((0, 1)\). We can think of \(f_t^{(i)}\) as the probability of retaining information in cell state dimension \(i\). In practice, forget gates often learn to stay near 1 for most dimensions most of the time, occasionally dropping to near 0 when the network decides to clear memory for that dimension.&lt;/p&gt;

&lt;p&gt;The input gate and candidate computation happen in parallel:&lt;/p&gt;

\[\mathbf{i}_t = \sigma(\mathbf{W}_i \mathbf{z}_t + \mathbf{b}_i)\]

\[\tilde{\mathbf{c}}_t = \tanh(\mathbf{W}_C \mathbf{z}_t + \mathbf{b}_C)\]

&lt;p&gt;The candidate \(\tilde{\mathbf{c}}_t\) uses tanh, producing values in \((-1, 1)\), representing proposed updates to the cell state. These could be positive (add information) or negative (subtract, though this is less common). The input gate \(\mathbf{i}_t\) moderates how much of the candidate to actually add. When processing important information (like a sentence’s subject), the input gate opens (\(i_t^{(i)} \approx 1\)) to store it. For filler words or irrelevant information, the gate closes (\(i_t^{(i)} \approx 0\)).&lt;/p&gt;

&lt;p&gt;The cell state update is where information actually flows through time:&lt;/p&gt;

\[\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t\]

&lt;p&gt;Let’s analyze this equation’s gradient properties carefully. When computing \(\frac{\partial \mathbf{c}_t}{\partial \mathbf{c}_{t-1}}\):&lt;/p&gt;

\[\frac{\partial \mathbf{c}_t}{\partial \mathbf{c}_{t-1}} = \mathbf{f}_t\]

&lt;p&gt;This is elementwise—the gradient for dimension \(i\) is simply \(f_t^{(i)}\). If the network keeps \(f_t^{(i)} = 0.99\) consistently across \(T\) time steps, the gradient for that dimension is \((0.99)^T\), which for \(T=100\) is about 0.37—substantial retention compared to vanilla RNN where it might be \(10^{-30}\). And the network can learn to keep \(f_t^{(i)}\) near 1 exactly when long-range memory is needed for dimension \(i\).&lt;/p&gt;

&lt;p&gt;Contrast this with vanilla RNN where:&lt;/p&gt;

\[\frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-1}} = \text{diag}(\tanh&apos;(\mathbf{z}_t)) \mathbf{W}_{hh}\]

&lt;p&gt;The derivative involves both the weight matrix (potentially poorly conditioned with eigenvalues far from 1) and \(\tanh&apos;\) which is typically much less than 1 when activations are saturated. The LSTM’s direct path through the cell state, controlled by learned gates, provides much more stable gradient flow.&lt;/p&gt;

&lt;p&gt;The output gate and hidden state computation:&lt;/p&gt;

\[\mathbf{o}_t = \sigma(\mathbf{W}_o \mathbf{z}_t + \mathbf{b}_o)\]

\[\mathbf{h}_t = \mathbf{o}_t \odot \tanh(\mathbf{c}_t)\]

&lt;p&gt;We squash the cell state with tanh before exposing it. Why? The cell state can grow unbounded through repeated additions (imagine \(c_t = c_{t-1} + 0.1\) for 1000 steps gives \(c_{1000} = 100\)), so tanh normalizes it to \([-1,1]\) before downstream layers process it. The output gate then selectively exposes parts of this normalized cell state based on what’s relevant for current processing.&lt;/p&gt;

&lt;p&gt;The complete LSTM involves four sets of weights (\(\mathbf{W}_f, \mathbf{W}_i, \mathbf{W}_C, \mathbf{W}_o\)) each of size \(d_h \times (d_h + d_x)\), plus four bias vectors, totaling \(4[d_h(d_h + d_x) + d_h]\) parameters. The computational cost per time step is \(O(d_h^2 + d_h d_x)\), about 4× that of vanilla RNN. This is the tradeoff: more computation and parameters buy better gradient flow and longer-range dependency learning.&lt;/p&gt;

&lt;p&gt;GRUs simplify this by combining forget and input gates into a single update gate \(\mathbf{z}_t\), and using a reset gate \(\mathbf{r}_t\) to control how much previous hidden state influences the candidate:&lt;/p&gt;

\[\mathbf{r}_t = \sigma(\mathbf{W}_r [\mathbf{h}_{t-1}; \mathbf{x}_t])\]

\[\mathbf{z}_t = \sigma(\mathbf{W}_z [\mathbf{h}_{t-1}; \mathbf{x}_t])\]

\[\tilde{\mathbf{h}}_t = \tanh(\mathbf{W} [\mathbf{r}_t \odot \mathbf{h}_{t-1}; \mathbf{x}_t])\]

\[\mathbf{h}_t = (1 - \mathbf{z}_t) \odot \mathbf{h}_{t-1} + \mathbf{z}_t \odot \tilde{\mathbf{h}}_t\]

&lt;p&gt;The update gate \(\mathbf{z}_t\) interpolates between keeping the old hidden state and using the new candidate. When \(z_t^{(i)} = 0\), dimension \(i\) copies the previous value (like LSTM with \(f_t^{(i)} = 1, i_t^{(i)} = 0\)). When \(z_t^{(i)} = 1\), it uses the new candidate (like \(f_t^{(i)} = 0, i_t^{(i)} = 1\)). The coupling of forget and input into a single gate reduces parameters while maintaining control over memory.&lt;/p&gt;

&lt;p&gt;The reset gate \(\mathbf{r}_t\) modulates how much previous hidden state influences the candidate computation. When \(r_t^{(i)} = 0\), the candidate ignores previous state for dimension \(i\), essentially “resetting” that dimension. This allows the network to forget when appropriate while computing new representations from input alone.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, English. Forget, input, and output gates plus the cell state are this lesson’s formulas.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker, English. The same gates in drawing order, easier to check against a hand calculation.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. The plain RNN those gates are repairing.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>06 LSTM and GRU - Advanced Recurrent Architectures</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter06/06_00_Introduction</id>
   <content type="html">&lt;p&gt;In 1991, Sepp Hochreiter’s diploma thesis proved mathematically why vanilla RNNs fail on long sequences: every time step multiplies the error signal by the recurrent weight matrix, forcing gradients to either vanish exponentially or explode violently. Six years later, Hochreiter and Jürgen Schmidhuber unveiled the &lt;strong&gt;Long Short-Term Memory (LSTM)&lt;/strong&gt; network—introducing a radical architectural idea called the &lt;strong&gt;Constant Error Carousel&lt;/strong&gt;: a dedicated cell state \(C_t\) updated by &lt;em&gt;addition&lt;/em&gt; rather than matrix multiplication, guarded by learnable sigmoid gates. Together with the streamlined &lt;strong&gt;GRU&lt;/strong&gt; (2014), gated recurrence dominated speech recognition, machine translation, and time-series forecasting for two decades.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-why-gating-solved-long-range-sequence-learning&quot;&gt;Key ideas: Why Gating Solved Long-Range Sequence Learning&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Additive Cell State Highway&lt;/strong&gt;: Updating \(C_t = f_t \odot C_{t-1} + i_t \odot \tilde{C}_t\) replaces repeated matrix multiplication with element-wise gated addition, letting gradients flow backward across hundreds of steps whenever \(f_t \approx 1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid Gates as Differentiable Soft Switches&lt;/strong&gt;: Because \(\sigma(z) \in (0, 1)\), element-wise multiplication with a sigmoid vector acts as a continuous valve—closing (\(0\)) to erase or block irrelevant dimensions, opening (\(1\)) to preserve or write critical memory slots.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decoupled Long-Term vs. Working Memory (\(C_t\) vs. \(h_t\))&lt;/strong&gt;: The cell state \(C_t\) acts as a protected long-term notebook, while the output gate \(o_t\) filters which parts of \(C_t\) are exposed as the working hidden state \(h_t = o_t \odot \tanh(C_t)\) at step \(t\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GRU Parameter Simplification&lt;/strong&gt;: Cho et al. (2014) merged the cell and hidden states and coupled forget/input control into a single update gate \(z_t\), cutting parameter count by \(25\%\) while retaining gated additive gradient flow.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-gradient-survival-across-50-steps--vanilla-rnn-vs-lstm&quot;&gt;Worked example: Gradient Survival Across 50 Steps — Vanilla RNN vs. LSTM&lt;/h3&gt;

&lt;p&gt;Compare how a gradient signal survives across \(\Delta t = 50\) time steps of neutral “distractor” tokens:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Vanilla RNN&lt;/strong&gt; (typical step Jacobian factor \(\approx 0.85\)):
\(0.85^{50} \approx 2.96 \times 10^{-4} \quad (\text{over } 99.97\% \text{ of the gradient is wiped out!}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LSTM Cell Highway&lt;/strong&gt; (forget gate learned to stay open at \(f_t = 0.99\) during distractor steps):
\(\frac{\partial C_T}{\partial C_{T-50}} \approx \prod_{k=1}^{50} f_k = 0.99^{50} \approx 0.605 \quad (\text{over } 60\% \text{ of the exact gradient arrives intact!}).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Key Takeaway&lt;/strong&gt;: Simply initializing the forget-gate bias \(b_f = +1\) or \(+2\) (so \(\sigma(b_f) \approx 0.73\text{–}0.88\) at epoch 0) immediately gives an LSTM a massive head start on long-range credit assignment.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;lstm-and-gru-conquering-the-vanishing-gradient&quot;&gt;LSTM and GRU: Conquering the Vanishing Gradient&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter06/lstm_architecture.png&quot; alt=&quot;LSTM Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc LSTM với cell state và các gates. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Long Short-Term Memory (LSTM) and Gated Recurrent Unit (GRU) networks represent one of the most important architectural innovations in the history of neural networks. They solve the &lt;strong&gt;vanishing gradient problem&lt;/strong&gt; that fundamentally limited vanilla RNNs, enabling learning of dependencies spanning hundreds or thousands of time steps.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter06/gru_architecture.png&quot; alt=&quot;GRU Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc GRU với 2 gates (reset và update). Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;the-problem-lstms-solve&quot;&gt;The Problem LSTMs Solve&lt;/h2&gt;

&lt;p&gt;Recall from Chapter 5 that vanilla RNNs suffer from vanishing gradients: when backpropagating through many time steps, gradients shrink exponentially, making it impossible to learn long-range dependencies. Information about the beginning of a sentence is essentially forgotten by the time we reach the end.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The key insight of LSTMs&lt;/strong&gt;: Create an explicit pathway for information to flow unchanged through time, bypassing the repeated nonlinear transformations that cause gradient decay.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;the-cell-state-a-highway-for-information&quot;&gt;The Cell State: A Highway for Information&lt;/h2&gt;

&lt;p&gt;LSTMs introduce a &lt;strong&gt;cell state&lt;/strong&gt; \(\mathbf{c}_t\) — a separate pathway that runs parallel to the hidden state. The cell state can carry information across many time steps with only minor linear interactions:&lt;/p&gt;

\[\mathbf{c}_t = \mathbf{f}_t \odot \mathbf{c}_{t-1} + \mathbf{i}_t \odot \tilde{\mathbf{c}}_t\]

&lt;p&gt;When the forget gate \(\mathbf{f}_t \approx 1\), information flows through unchanged. This is dramatically different from vanilla RNNs where information must pass through weight matrices and nonlinearities at every step.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;gates-learnable-information-control&quot;&gt;Gates: Learnable Information Control&lt;/h2&gt;

&lt;p&gt;LSTMs use three types of &lt;strong&gt;gates&lt;/strong&gt; — sigmoid layers that output values in [0,1] — to control information flow:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Gate&lt;/th&gt;
      &lt;th&gt;Function&lt;/th&gt;
      &lt;th&gt;Equation&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Forget&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;What to discard from cell state&lt;/td&gt;
      &lt;td&gt;\(\mathbf{f}_t = \sigma(\mathbf{W}_f[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_f)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Input&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;What new information to add&lt;/td&gt;
      &lt;td&gt;\(\mathbf{i}_t = \sigma(\mathbf{W}_i[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_i)\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Output&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;What to expose to downstream&lt;/td&gt;
      &lt;td&gt;\(\mathbf{o}_t = \sigma(\mathbf{W}_o[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_o)\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Think of gates as learnable switches: the network learns &lt;strong&gt;when to remember&lt;/strong&gt;, &lt;strong&gt;when to forget&lt;/strong&gt;, and &lt;strong&gt;when to act&lt;/strong&gt; on its memory.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;gru-a-simpler-alternative&quot;&gt;GRU: A Simpler Alternative&lt;/h2&gt;

&lt;p&gt;The Gated Recurrent Unit (2014) simplifies LSTMs while preserving their essential benefits:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Two gates&lt;/strong&gt; instead of three (reset and update)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;No separate cell state&lt;/strong&gt; — hidden state does everything&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;~25% fewer parameters&lt;/strong&gt; — faster training, easier tuning&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For many tasks, GRU performs comparably to LSTM. A good heuristic: &lt;strong&gt;start with GRU&lt;/strong&gt; (simpler), switch to LSTM only if performance plateaus.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;what-this-chapter-covers&quot;&gt;What This Chapter Covers&lt;/h2&gt;

&lt;h3 id=&quot;06-01-lstm-architecture&quot;&gt;06-01: LSTM Architecture&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Complete mathematical formulation of LSTM&lt;/li&gt;
  &lt;li&gt;Gradient flow analysis: why LSTMs solve vanishing gradients&lt;/li&gt;
  &lt;li&gt;GRU architecture and comparison with LSTM&lt;/li&gt;
  &lt;li&gt;NumPy implementation from scratch&lt;/li&gt;
  &lt;li&gt;PyTorch implementation with long-range memory task&lt;/li&gt;
  &lt;li&gt;Gate visualization and interpretation&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;historical-impact&quot;&gt;Historical Impact&lt;/h2&gt;

&lt;p&gt;LSTMs dominated sequence modeling from the late 1990s through the mid-2010s, enabling breakthroughs in:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Machine translation (Google Translate, 2016)&lt;/li&gt;
  &lt;li&gt;Speech recognition (Siri, Google Voice)&lt;/li&gt;
  &lt;li&gt;Handwriting recognition&lt;/li&gt;
  &lt;li&gt;Music generation&lt;/li&gt;
  &lt;li&gt;Time series forecasting&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Even after Transformers emerged as the dominant architecture for NLP, LSTMs remain important:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Lower memory cost&lt;/strong&gt;: \(O(n)\) vs Transformers’ \(O(n^2)\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Online processing&lt;/strong&gt;: Can process sequences naturally as they arrive&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Long sequence efficiency&lt;/strong&gt;: Better for very long sequences with limited compute&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Understanding LSTMs deeply — both their elegance and limitations — provides crucial context for appreciating why attention mechanisms and Transformers evolved.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Before studying LSTMs, ensure you understand:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Vanilla RNN architecture and limitations (Chapter 5)&lt;/li&gt;
  &lt;li&gt;Why gradients vanish during backpropagation through time&lt;/li&gt;
  &lt;li&gt;Sigmoid and tanh activation functions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After LSTM/GRU gates, see &lt;strong&gt;06-99 Modern Applications and Updates&lt;/strong&gt; for xLSTM and the production niches where gated RNNs still win. Interview table: LSTM cell vs Transformer cache — &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=YCzL96nL7j0&quot;&gt;Long Short-Term Memory (LSTM), Clearly Explained&lt;/a&gt; — StatQuest with Josh Starmer, English. The cell state is the highway this chapter adds on top of a plain RNN.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=8HyCNIVRbSU&quot;&gt;Illustrated Guide to LSTM’s and GRU’s: A step by step explanation&lt;/a&gt; — The AI Hacker, English. Gates drawn step by step, including the GRU simplification the introduction promises.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dqoEU9Ac3ek&quot;&gt;MIT 6.S191 (2024): Recurrent Neural Networks, Transformers, and Attention&lt;/a&gt; — Alexander Amini, English. The sequence lecture’s LSTM segment, in the same course as the RNN introduction.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;Conventional wisdom in 2020 declared recurrent neural networks obsolete in the shadow of the Transformer. Yet Transformers carry a stubborn physical tax: their KV-cache grows linearly with context length and prefill attention scales quadratically \(O(T^2)\). Between 2023 and 2026, a wave of linear-time recurrent architectures—most notably &lt;strong&gt;Mamba&lt;/strong&gt; (Selective State Space Models) and &lt;strong&gt;RWKV&lt;/strong&gt;—returned to the exact state-space recursion of Chapter 05, upgrading it with input-dependent gating and hardware-aware parallel scans so models can train in parallel like Transformers while generating tokens in \(O(1)\) constant memory like an RNN.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-modern-recurrent-revival-ssms-mamba-rwkv&quot;&gt;Key ideas: The Modern Recurrent Revival (SSMs, Mamba, RWKV)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Linear Time-Invariant &amp;amp; Selective State Space Models&lt;/strong&gt;: Classical continuous-time control theory (\(\dot{h}(t) = A h(t) + B x(t)\)) discretized into \(h_t = \bar{A}_t h_{t-1} + \bar{B}_t x_t\) turns recurrence into an associative operation. Making \(\bar{A}_t, \bar{B}_t\) functions of \(x_t\) (Mamba’s selectivity) lets the state selectively remember or ignore tokens.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parallel Associative Scan (Blelloch Prefix Sum)&lt;/strong&gt;: Because linear recurrence is associative, a sequence of length \(T\) can be computed in \(O(\log T)\) parallel depth on GPUs during training—breaking the sequential training bottleneck of classical nonlinear RNNs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Constant-Memory Autoregressive Inference&lt;/strong&gt;: While a Transformer must attend over an ever-growing KV-cache of \(O(T)\) past tokens, an SSM or RWKV updates a fixed-size state tensor in \(O(1)\) time and \(O(1)\) memory per generated token.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hybrid Transformer–SSM Architectures&lt;/strong&gt;: Models like Jamba and Zamba interleave Mamba layers (cheap long-range compression) with periodic Attention layers (exact needle-in-a-haystack recall), combining the strengths of both families.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-linear-recurrence-parallelizes-via-associativity&quot;&gt;Worked example: Why Linear Recurrence Parallelizes via Associativity&lt;/h3&gt;

&lt;p&gt;Consider a scalar selective SSM step \(h_t = a_t h_{t-1} + b_t\) with \(h_0 = 0\) and 4 time steps:
\((a_1, b_1) = (0.5, 2),\; (a_2, b_2) = (0.5, 4),\; (a_3, b_3) = (0.2, 1),\; (a_4, b_4) = (1.0, 3).\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Define the associative composition operator \(\oplus\)&lt;/strong&gt; on pairs \((a, b)\):
\((a_i, b_i) \oplus (a_j, b_j) = (a_j a_i,\; a_j b_i + b_j).\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parallel Stage 1 (combine pairs \((1,2)\) and \((3,4)\) simultaneously)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\((1 \to 2)\): \((0.5 \times 0.5,\; 0.5 \times 2 + 4) = (0.25, 5.0) \implies h_2 = 5.0\).&lt;/li&gt;
      &lt;li&gt;\((3 \to 4)\): \((1.0 \times 0.2,\; 1.0 \times 1 + 3) = (0.2, 4.0)\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parallel Stage 2 (combine \((1 \to 2)\) with \((3 \to 4)\) in one step)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\((1 \to 4)\): \((0.2 \times 0.25,\; 0.2 \times 5.0 + 4.0) = (0.05, 5.0) \implies h_4 = 5.0\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify sequentially&lt;/strong&gt;:
\(h_1 = 2,\; h_2 = 0.5(2)+4 = 5,\; h_3 = 0.2(5)+1 = 2,\; h_4 = 1.0(2)+3 = 5.\)
Exact match! A length-\(T\) sequence collapses from \(T\) sequential steps to \(\lceil \log_2 T \rceil\) parallel GPU rounds.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-recurrent-sequence-models-after-transformers&quot;&gt;Optional: recurrent sequence models after Transformers&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace vanilla RNN theory or the character-LM implementation. It explains where recurrence still appears — and which 2023–2025 models revived the “scan over time” idea.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A vanilla RNN is&lt;/p&gt;

\[\mathbf{h}_t = \sigma(W_h \mathbf{h}_{t-1} + W_x \mathbf{x}_t + \mathbf{b}).\]

&lt;p&gt;Transformers removed the left-to-right &lt;em&gt;training&lt;/em&gt; loop. After 2022, &lt;strong&gt;state-space and linear-recurrent&lt;/strong&gt; models brought a loop back, but as a &lt;em&gt;parallel scan&lt;/em&gt; with linear cost in sequence length.&lt;/p&gt;

&lt;h2 id=&quot;1-why-rnns-did-not-vanish&quot;&gt;1. Why RNNs did not vanish&lt;/h2&gt;

&lt;p&gt;Transformers cost \(O(T^2)\) memory/time in sequence length \(T\) (before approximations). Streaming speech, control, and very long genomics still want \(O(T)\) steps and a compact state. That is the same motivation as this chapter — with better parameterizations.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;structured-state-space-models-and-mamba&quot;&gt;Structured state space models and Mamba&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2312.00752&quot;&gt;Gu &amp;amp; Dao, 2023&lt;/a&gt; (Mamba) use a selective SSM: the discrete state update is a recurrence&lt;/p&gt;

\[\mathbf{h}_t = \overline{A}_t \mathbf{h}_{t-1} + \overline{B}_t \mathbf{x}_t, \quad \mathbf{y}_t = C_t \mathbf{h}_t,\]

&lt;p&gt;where \(\overline{A}_t\) depends on the input (the “selection” mechanism). Training uses a parallel scan, not a Python &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; loop. This is the 2023–2025 answer to “can recurrence compete with attention on language?”&lt;/p&gt;

&lt;h3 id=&quot;rwkv&quot;&gt;RWKV&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.13048&quot;&gt;Peng et al., 2023&lt;/a&gt; mix a linear attention-style time mix with a channel mix, so inference is RNN-like (constant state) while training is parallel. Used in open chat models when KV-cache memory is the bottleneck.&lt;/p&gt;

&lt;h3 id=&quot;where-classical-rnns-remain&quot;&gt;Where classical RNNs remain&lt;/h3&gt;

&lt;p&gt;On-device keyword spotting, some forecasting baselines, and teaching labs still use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.GRU&lt;/code&gt;. Production ASR moved to Conformer / Whisper (Chapters 08 and 19), not vanilla Elman RNNs.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/state-spaces/mamba&quot;&gt;state-spaces/mamba&lt;/a&gt; — official Mamba kernels.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/BlinkDL/RWKV-LM&quot;&gt;BlinkDL/RWKV-LM&lt;/a&gt; — RWKV training and inference.&lt;/li&gt;
  &lt;li&gt;PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt; — still the right API for the core homework.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2312.00752&quot;&gt;Mamba: Linear-Time Sequence Modeling with Selective State Spaces (Gu &amp;amp; Dao, 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2305.13048&quot;&gt;RWKV: Reinventing RNNs for the Transformer Era (Peng et al., 2023)&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2111.00396&quot;&gt;Efficiently Modeling Long Sequences with Structured State Spaces (Gu et al., 2022)&lt;/a&gt; — S4, the SSM precursor.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Implement the vanilla RNN and the pitfalls lesson first. This note only contrasts &lt;strong&gt;modern linear recurrences&lt;/strong&gt; with Transformers — it does not replace the unfolding / BPTT derivation.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [MAMBA and State Space Models explained&lt;/td&gt;
          &lt;td&gt;SSM explained](https://www.youtube.com/watch?v=vrF3MtGwD0Y) — AI Coffee Break with Letitia, English. State-space models are the 2023–2024 reason a recurrence did not disappear behind transformers.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. The hidden state those newer recurrences still keep.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dqoEU9Ac3ek&quot;&gt;MIT 6.S191 (2024): Recurrent Neural Networks, Transformers, and Attention&lt;/a&gt; — Alexander Amini, English. Where a 2024 course still teaches RNNs next to attention.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-01 Recurrent Neural Networks - Fundamentals</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_01_RNN_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_01_RNN_Fundamentals</id>
   <content type="html">&lt;p&gt;Before gated cells (LSTM/GRU) and Transformers entered the scene, the vanilla Recurrent Neural Network established the core mathematical language of sequential deep learning: hidden states as compressed memory, parameter sharing across time, and Backpropagation Through Time. This module pairs the rigorous mathematical theory of vanilla RNNs with hands-on NumPy and PyTorch implementations so you understand both why recurrence works and precisely where its gradient dynamics break down.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-vanilla-rnn-fundamentals-roadmap&quot;&gt;Key ideas: Vanilla RNN Fundamentals Roadmap&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Recurrent State-Space Formulation&lt;/strong&gt;: Modeling variable-length sequences via \(h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h)\) with shared temporal weights.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;BPTT &amp;amp; Gradient Pathologies&lt;/strong&gt;: Understanding how repeated Jacobian products cause vanishing or exploding gradients as sequence length grows.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;End-to-End Implementation &amp;amp; Language Modeling&lt;/strong&gt;: Coding BPTT from scratch, applying gradient clipping, and sampling autoregressive text from a character-level RNN.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-exact-sequence-length-memory-footprint-of-bptt&quot;&gt;Worked example: Exact Sequence-Length Memory Footprint of BPTT&lt;/h3&gt;

&lt;p&gt;Suppose you train a batch of \(N = 32\) sequences of length \(T = 100\) with hidden dimension \(d_h = 256\) in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt; (4 bytes per scalar).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hidden states stored for full BPTT&lt;/strong&gt;:
\(N \times T \times d_h = 32 \times 100 \times 256 = 819{,}200 \text{ floats} \implies 819{,}200 \times 4 = 3{,}276{,}800\text{ bytes} \approx 3.125\text{ MiB}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;If sequence length grows \(10\times\) to \(T = 1{,}000\)&lt;/strong&gt;:
Activation memory scales strictly linearly \(O(T)\) to \(31.25\text{ MiB}\) (for one layer), while compute per forward pass also scales linearly \(O(T)\)—unlike full self-attention, which scales quadratically \(O(T^2)\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why this still matters&lt;/strong&gt;: That \(O(T)\) memory and \(O(1)\) per-step inference cost is the exact reason modern State Space Models (Mamba, RWKV) revived recurrent dynamics in 2023–2026.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson introduces recurrent neural networks for sequential data:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;RNN Theory and Intuition&lt;/strong&gt; — concept overview, math, and worked intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;RNN Implementation&lt;/strong&gt; — full code, related concepts, papers, pitfalls, and takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Before the theory and code lessons.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 10&lt;/td&gt;
          &lt;td&gt;Recurrent Neural Networks](https://www.youtube.com/watch?v=6niqTuYFZLQ) — Stanford University School of Engineering, English. The lecture version of the same recurrence, including backprop through time.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=L8HKweZIOmg&quot;&gt;Sequence-to-Sequence (seq2seq) Encoder-Decoder Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Sequence-to-sequence is the architecture type the introduction lists and the code lesson reaches.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-01-02 RNN Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_01_02_RNN_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_01_02_RNN_Implementation</id>
   <content type="html">&lt;p&gt;Turning recurrent equations into a working sequence model requires mastering two complementary layers of craft: first, building the core forward/BPTT mechanics in NumPy and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt;; second, wiring that core into an end-to-end character-level language model with temperature sampling, gradient clipping, and hidden-state management. This section hub organizes both implementation halves so you can move cleanly from toy sequence regression to generative text modeling.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-core-implementation-pillars-for-rnns&quot;&gt;Key ideas: Core Implementation Pillars for RNNs&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Explicit State Propagation &amp;amp; Caching&lt;/strong&gt;: Managing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(h_prev -&amp;gt; h_next)&lt;/code&gt; across variable sequence lengths and detaching hidden states across truncated BPTT boundaries.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Numerical Stability Controls&lt;/strong&gt;: Applying global gradient norm clipping and orthogonal/Xavier initialization to keep the recurrent Jacobian well-conditioned at initialization and during training.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Autoregressive Training vs. Sampling Loops&lt;/strong&gt;: Contrasting parallel teacher-forced cross-entropy loss over shifted &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(input, target)&lt;/code&gt; sequences with sequential token-by-token sampling at inference time.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-counting-parameters-in-a-character-level-nnrnn&quot;&gt;Worked example: Counting Parameters in a Character-Level &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;Suppose we build a 1-layer PyTorch character RNN with vocabulary size \(V = 65\) (one-hot input \(d_x = 65\)), hidden dimension \(d_h = 128\), and linear output head \(128 \to 65\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Input-to-hidden (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_ih&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_ih&lt;/code&gt;)&lt;/strong&gt;:
\(128 \times 65 + 128 = 8{,}320 + 128 = 8{,}448.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hidden-to-hidden (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;weight_hh&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_hh&lt;/code&gt;)&lt;/strong&gt;:
\(128 \times 128 + 128 = 16{,}384 + 128 = 16{,}512.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Output projection (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Linear(128, 65)&lt;/code&gt;)&lt;/strong&gt;:
\(65 \times 128 + 65 = 8{,}320 + 65 = 8{,}385.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Total trainable parameters&lt;/strong&gt;:
\(8{,}448 + 16{,}512 + 8{,}385 = 33{,}345.\)
Note that PyTorch’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt; allocates &lt;em&gt;two&lt;/em&gt; separate bias vectors (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_ih&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias_hh&lt;/code&gt;, adding 128 extra parameters over a single-bias NumPy implementation)—a classic detail to know when comparing parameter counts!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;RNN implementation:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Core Implementation&lt;/strong&gt; — from-scratch and sequence prediction demos&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Character LM, Papers, and Pitfalls&lt;/strong&gt; — language modeling, related concepts, papers, takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 10&lt;/td&gt;
          &lt;td&gt;Recurrent Neural Networks](https://www.youtube.com/watch?v=6niqTuYFZLQ) — Stanford University School of Engineering, English. The implementation contract: an RNN cell plus a loss over the sequence.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, English. A character-level language model built in code, which is the lesson’s programming target.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Keep this beside the code for the shapes of h and x.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-01-02-02 Character LM, Papers, and Pitfalls</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_01_02_02_RNN_Language_Model_and_Pitfalls/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_01_02_02_RNN_Language_Model_and_Pitfalls</id>
   <content type="html">&lt;p&gt;In 2015, Andrej Karpathy trained a tiny character-level RNN on raw Shakespeare plays and Linux C source code, and watched it spontaneously invent indentation, balanced curly braces, and iambic pentameter—one character at a time. A character-level language model distills sequence modeling to its purest form: given the prefix &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&quot;hell&quot;&lt;/code&gt;, predict the next probability distribution over the vocabulary so that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;o&apos;&lt;/code&gt; receives the highest probability. Yet building one also exposes every classic recurrent pitfall—temperature calibration, exposure bias, hidden-state detachment across truncated chunks, and vanishing long-range context.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-character-level-language-modeling--pitfalls&quot;&gt;Key ideas: Character-Level Language Modeling &amp;amp; Pitfalls&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Autoregressive Factorization&lt;/strong&gt;: A language model decomposes the joint probability of a character sequence into causal conditionals: \(P(c_1, \dots, c_T) = \prod_{t=1}^T P(c_t \mid c_{&amp;lt;t})\), trained by minimizing cross-entropy loss (equivalently minimizing &lt;strong&gt;perplexity&lt;/strong&gt; \(\exp(\mathcal{L}_{\text{CE}})\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Teacher Forcing vs. Exposure Bias&lt;/strong&gt;: During training, the model receives the ground-truth previous character \(c_{t-1}\) at every step; during generation, it feeds back its own sampled character \(\hat{c}_{t-1}\), meaning early mistakes can compound along the rollout.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Temperature-Scaled Sampling&lt;/strong&gt;: Dividing logits \(z\) by temperature \(\tau &amp;gt; 0\) before softmax—\(p_i = \frac{\exp(z_i/\tau)}{\sum_j \exp(z_j/\tau)}\)—controls the entropy of generation: \(\tau \to 0\) approaches greedy argmax, \(\tau = 1\) preserves learned probabilities, and \(\tau &amp;gt; 1\) flattens the distribution for higher creativity (and higher error).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hidden State Detachment in TBPTT&lt;/strong&gt;: Carrying &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h = h.detach()&lt;/code&gt; across chunks preserves forward memory over long documents while severing the autograd graph so GPU memory stays constant instead of growing unboundedly.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-temperature-softmax--perplexity-on-a-3-character-vocabulary&quot;&gt;Worked example: Temperature Softmax &amp;amp; Perplexity on a 3-Character Vocabulary&lt;/h3&gt;

&lt;p&gt;Suppose our character RNN has vocabulary \(\{\text{&apos;e&apos;}, \text{&apos;l&apos;}, \text{&apos;o&apos;}\}\) and outputs raw logits \(z = [0.0, 1.0, 2.0]\) when the true next character is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;o&apos;&lt;/code&gt;.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standard probabilities (\(\tau = 1.0\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Exponentials: \(e^0 = 1.000,\; e^1 \approx 2.718,\; e^2 \approx 7.389\); sum \(Z = 11.107\).&lt;/li&gt;
      &lt;li&gt;Probabilities: \(p(\text{&apos;e&apos;}) = 0.090,\; p(\text{&apos;l&apos;}) = 0.245,\; p(\text{&apos;o&apos;}) = 0.665\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-entropy loss and perplexity for target &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;&apos;o&apos;&lt;/code&gt;&lt;/strong&gt;:
\(\mathcal{L} = -\ln(0.665) \approx 0.408\text{ nats}, \quad \text{PPL} = e^{0.408} = \frac{1}{0.665} \approx 1.50.\)
(Interpretation: the model is as uncertain as choosing uniformly among \(1.5\) equally likely characters.)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Low temperature (\(\tau = 0.5\) — sharper / more conservative)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Scaled logits: \(z / 0.5 = [0.0, 2.0, 4.0]\).&lt;/li&gt;
      &lt;li&gt;Exponentials: \(1.000,\; 7.389,\; 54.598\); sum \(= 62.987\).&lt;/li&gt;
      &lt;li&gt;Probabilities: \(p(\text{&apos;e&apos;}) = 0.016,\; p(\text{&apos;l&apos;}) = 0.117,\; p(\text{&apos;o&apos;}) = 0.867\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;High temperature (\(\tau = 2.0\) — flatter / more diverse)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Scaled logits: \(z / 2.0 = [0.0, 0.5, 1.0]\).&lt;/li&gt;
      &lt;li&gt;Exponentials: \(1.000,\; 1.649,\; 2.718\); sum \(= 5.367\).&lt;/li&gt;
      &lt;li&gt;Probabilities: \(p(\text{&apos;e&apos;}) = 0.186,\; p(\text{&apos;l&apos;}) = 0.307,\; p(\text{&apos;o&apos;}) = 0.506\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Character-level language model example
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Character-Level Language Model with PyTorch RNN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create simple text dataset
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;hello world, deep learning is amazing! transformers are powerful.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;chars&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;list&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;char_to_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chars&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;idx_to_char&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chars&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)}&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chars&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vocabulary: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;chars&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vocabulary size: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Prepare sequences: given &quot;hell&quot; predict &quot;ello&quot;
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Create training sequences from text&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Convert to indices
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;seq_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;char_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;char_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Convert to tensors and create one-hot encodings
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;to_onehot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Convert index sequences to one-hot encoded tensors&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;one_hot&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;seq_onehot&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;seq_onehot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;one_hot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_onehot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;one_hot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;to_onehot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;long&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Dataset: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; sequences of length &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (num_sequences, seq_length, vocab_size)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Target shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (num_sequences, seq_length)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Create model
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RNNSequenceModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                         &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Loss and optimizer
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CrossEntropyLoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training character-level language model...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (batch, seq_len, vocab_size)
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Reshape for cross-entropy: (batch * seq_len, vocab_size)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs_flat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;targets_flat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Compute loss
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets_flat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Backward pass and optimize
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# BPTT happens here automatically!
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Gradient clipping (essential for RNNs!)
&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Without this, gradients can explode and training diverges
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;utils&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip_grad_norm_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_norm&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate text by sampling from learned distribution
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generating text from learned RNN&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Generate text autoregressively using trained RNN.
    
    We start with a seed text, predict the next character&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s probability
    distribution, sample from it, append to sequence, and repeat.
    This is autoregressive generation—each prediction conditions on
    all previous predictions.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Convert start text to indices
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;current_seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;char_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;generated&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;start_text&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Hidden state carries information through generation
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Prepare input: last seq_length characters (or pad if shorter)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;input_seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;current_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;current_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;current_seq&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Pad if needed
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;input_seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;char_to_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_seq&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Convert to one-hot
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vocab_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Predict next character
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Get probabilities for next character (last time step)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;probs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Sample from distribution (more interesting than argmax)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;next_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;multinomial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;probs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;next_char&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;idx_to_char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;generated&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;next_char&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;current_seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;next_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;generated&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;deep &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;generated_text&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Seed: &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Generated: &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;generated_text&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;The model learned character-level patterns!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;With more data and training, RNNs can generate coherent text.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Let’s also demonstrate the vanishing gradient problem empirically:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Demonstrating Vanishing Gradients in RNNs&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;analyze_gradient_flow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sequence_lengths&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Show how gradients diminish with sequence length.
    
    We&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ll create sequences of different lengths, compute gradients, and
    measure their magnitude. This empirically demonstrates why vanilla RNNs
    struggle with long-range dependencies.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequence_lengths&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Create simple RNN
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;rnn_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;RNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Random input sequence
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;rnn_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute loss from FIRST time step output only
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Gradient must backprop through seq_len-1 steps to reach h_1
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Measure gradient magnitude at input
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;grad_magnitude&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad_magnitude&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sequence length &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Gradient magnitude = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad_magnitude&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Typically see exponential decay in gradient magnitude
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Observation: Gradients decay exponentially with sequence length!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This is the vanishing gradient problem that limits vanilla RNNs.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;results&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;gradient_analysis&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;analyze_gradient_flow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;The relationship between RNNs and feedforward networks illuminates fundamental principles about network architecture design. Feedforward networks assume inputs are independent, identically distributed samples—the order we present images during training doesn’t matter because each image is processed in isolation. RNNs, by contrast, explicitly model dependencies between sequential inputs through the hidden state. This difference isn’t just about architecture; it reflects different assumptions about data structure. When we choose an RNN over a feedforward network, we’re encoding the inductive bias that temporal or sequential order carries information relevant to the task.&lt;/p&gt;

&lt;p&gt;The connection to finite state machines and dynamical systems provides deeper theoretical insight. An RNN with discrete hidden states and hard-threshold activations is essentially a finite state machine, transitioning between states based on inputs. With continuous hidden states and smooth activations, RNNs become continuous dynamical systems described by the difference equation \(\mathbf{h}_{t+1} = f(\mathbf{W}_{hh}\mathbf{h}_t + \mathbf{W}_{xh}\mathbf{x}_t)\). The stability and expressiveness of this dynamical system depend on the spectrum of \(\mathbf{W}_{hh}\)—its eigenvalues determine whether the system is stable, chaotic, or marginally stable. This connection to dynamical systems theory helps explain phenomena like vanishing/exploding gradients and motivates architectures like LSTMs that explicitly manage information flow through gating mechanisms.&lt;/p&gt;

&lt;p&gt;The evolution from RNNs to LSTMs to Transformers tells a story about solving fundamental limitations. Vanilla RNNs struggle with long-range dependencies due to vanishing gradients. LSTMs introduce gating mechanisms that create skip connections through time, allowing gradients to flow more easily and information to persist longer. But LSTMs still process sequences sequentially, limiting parallelization. Transformers abandon recurrence entirely, using attention to create direct connections between all time steps, enabling full parallelization at the cost of quadratic complexity in sequence length. Each architecture makes different tradeoffs between expressiveness, trainability, and computational efficiency.&lt;/p&gt;

&lt;p&gt;The relationship between RNNs and convolutional networks is subtler but illuminating. Temporal convolution—applying 1D convolution over sequences—can capture some sequential patterns and is fully parallelizable. However, its receptive field grows only linearly with depth (a network with \(L\) layers of kernel size \(k\) has receptive field \(1 + L(k-1)\)), whereas RNNs theoretically have infinite receptive field (the hidden state can remember information from arbitrarily far in the past). This tradeoff between parallelizability (favoring convolution) and theoretically unlimited memory (favoring RNNs) has led to hybrid architectures combining both, like WaveNet for audio generation.&lt;/p&gt;

&lt;p&gt;Bidirectional RNNs extend the basic architecture by processing sequences in both forward and backward directions, maintaining two hidden states \(\overrightarrow{\mathbf{h}}_t\) and \(\overleftarrow{\mathbf{h}}_t\). The output at each time step combines information from both: \(\mathbf{y}_t = g(\mathbf{W}_{hy}[\overrightarrow{\mathbf{h}}_t; \overleftarrow{\mathbf{h}}_t] + \mathbf{b}_y)\). This is powerful for tasks where future context is available (like translating a complete sentence) but impossible for real-time prediction where we must make decisions before seeing the complete sequence. The bidirectional design exemplifies how architecture should match task requirements—using future context when available, processing causally when necessary.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://doi.org/10.1207/s15516709cog1402_1&quot;&gt;“Finding Structure in Time” (1990)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Author&lt;/em&gt;: Jeffrey L. Elman&lt;br /&gt;
This seminal paper introduced the Simple Recurrent Network (SRN), now called Elman network, and demonstrated that recurrent connections enable learning temporal patterns. Elman showed that RNNs could learn to predict the next word in simple sentences, discovering grammatical structure without explicit rules. The key insight was that the hidden state develops internal representations of grammatical categories (noun, verb) and sequential dependencies without being told to do so—purely from the prediction task. The paper established RNNs as viable for sequence modeling and influenced subsequent development of more sophisticated recurrent architectures. Elman’s analysis of hidden state dynamics—showing how the state space organizes itself to reflect linguistic structure—demonstrated that neural networks could discover interpretable representations, a theme that continues in modern deep learning research.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://doi.org/10.1162/089976600300015015&quot;&gt;“Learning to Forget: Continual Prediction with LSTM” (2000)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Felix A. Gers, Jürgen Schmidhuber, Fred Cummins&lt;br /&gt;
While LSTMs were introduced in 1997, this paper made a crucial modification that made them practical: the forget gate. The original LSTM could accumulate information in the cell state but had no mechanism to selectively forget irrelevant information, leading to saturation over long sequences. The forget gate, controlled by \(\mathbf{f}_t = \sigma(\mathbf{W}_f[\mathbf{h}_{t-1}; \mathbf{x}_t] + \mathbf{b}_f)\), allows the network to clear its memory when old information becomes irrelevant. This seemingly simple addition—letting the network learn when to forget—dramatically improved LSTM performance on long sequences and became standard in all subsequent LSTM implementations. The paper demonstrates how architectural details that seem minor can have profound practical impacts.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1211.5063&quot;&gt;“On the difficulty of training Recurrent Neural Networks” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Razvan Pascanu, Tomas Mikolov, Yoshua Bengio&lt;br /&gt;
This paper provided the definitive analysis of vanishing and exploding gradients in RNNs, moving beyond empirical observations to rigorous mathematical treatment. The authors showed that when backpropagating through \(t\) time steps, gradients involve products of \(t\) Jacobian matrices, and if the largest eigenvalue of these matrices is less than 1, gradients vanish exponentially; if greater than 1, they explode exponentially. Importantly, they showed this isn’t just a training trick issue but a fundamental property of recurrent dynamics. The paper proposed gradient clipping to handle explosions (clip gradient norm to maximum threshold, now standard practice) and analyzed how LSTM’s gating mechanisms create effective paths for gradient flow. This work deepened understanding of why vanilla RNNs fail on long sequences and why architectural innovations like LSTMs are necessary, not optional.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1412.3555&quot;&gt;“Empirical Evaluation of Gated Recurrent Neural Networks on Sequence Modeling” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Junyoung Chung, Caglar Gulcehre, KyungHyun Cho, Yoshua Bengio&lt;br /&gt;
This paper systematically compared LSTM and GRU (Gated Recurrent Unit) architectures on multiple sequence modeling tasks, providing empirical evidence about when each architecture excels. GRUs, introduced by Cho et al. in 2014, simplify LSTMs by using only two gates instead of three and no separate cell state, reducing parameters by about 25%. The paper showed that GRUs often match LSTM performance while training faster due to fewer parameters. Importantly, it demonstrated that architectural details matter—carefully engineered recurrent mechanisms consistently outperformed vanilla RNNs on long sequences. The paper’s experimental methodology—controlled comparisons on multiple datasets with careful hyperparameter tuning—set a standard for how to evaluate architectural innovations in deep learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1506.02078&quot;&gt;“Visualizing and Understanding Recurrent Networks” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Andrej Karpathy, Justin Johnson, Li Fei-Fei&lt;br /&gt;
This paper investigated what RNNs learn by analyzing their hidden state dynamics on character-level language modeling. By examining which hidden units activate for which input patterns, the authors discovered that RNNs spontaneously develop interpretable internal representations: certain neurons activate for quotes, others for parentheses balancing, others for code indentation. This demonstrated that RNNs don’t just memorize but learn meaningful structure. The paper also introduced techniques for visualizing attention-like patterns in RNNs before explicit attention mechanisms were common. Perhaps most influentially, it made accessible the kind of interpretability analysis that helps us understand what neural networks learn, a methodology that has become standard for analyzing all types of models, not just RNNs.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;The most common failure mode when training RNNs is gradient explosion, and recognizing its symptoms is crucial for debugging. Training loss suddenly becomes NaN, parameters become infinite, or loss oscillates wildly rather than decreasing smoothly. This happens when the product of gradients through time steps grows exponentially. The standard solution—gradient clipping—is conceptually simple but must be implemented correctly. We compute the global gradient norm across all parameters \(\|\nabla_\theta \mathcal{L}\|_2 = \sqrt{\sum_\theta (\frac{\partial \mathcal{L}}{\partial \theta})^2}\) and if it exceeds a threshold (typically 5-10), we scale all gradients by \(\frac{\text{threshold}}{\|\nabla_\theta \mathcal{L}\|_2}\). This preserves gradient direction while preventing explosive updates. It’s crucial to clip the global norm, not individual gradient values, because we want to preserve the relative magnitudes of gradients for different parameters.&lt;/p&gt;

&lt;p&gt;Vanishing gradients are more insidious because they don’t cause obvious training failures—the network trains but simply fails to learn long-range dependencies. Symptoms include the model only using recent context (in language modeling, only considering the last few words) or being unable to learn tasks requiring information from the beginning of long sequences. Detection requires careful analysis: plot gradient magnitudes as a function of backpropagation steps or test specifically on tasks requiring long-range memory. Solutions include switching to LSTM/GRU (which mitigate though don’t eliminate vanishing gradients), using smaller sequence lengths during training (truncated BPTT), or adding auxiliary losses at intermediate time steps to provide more direct gradient paths.&lt;/p&gt;

&lt;p&gt;Initialization of recurrent weights deserves special attention because it directly affects gradient flow stability. The standard small random initialization \(\mathbf{W}_{hh} \sim \mathcal{N}(0, 0.01^2)\) often leads to vanishing gradients. A better approach is orthogonal initialization: initialize \(\mathbf{W}_{hh}\) to a random orthogonal matrix (often generated via QR decomposition of a random matrix). Orthogonal matrices preserve vector norms during multiplication, helping gradients neither vanish nor explode, at least initially. This gives training a better starting point, though as weights update, they drift from orthogonality. Another approach is identity initialization plus small random noise: \(\mathbf{W}_{hh} = I + \mathcal{N}(0, 0.001^2)\), encouraging the hidden state to change slowly, which can help with gradient flow.&lt;/p&gt;

&lt;p&gt;A subtle but important issue is variable-length sequences in batched training. When training on multiple sequences of different lengths simultaneously, we must handle the fact that some sequences end before others. The solution is padding and masking: pad shorter sequences to match the longest sequence in the batch with a special padding token, then mask the loss so padded positions don’t contribute to gradients. Without masking, the RNN receives meaningless gradient signals from padding, degrading performance. PyTorch’s PackedSequence functionality handles this elegantly, avoiding computation on padded positions entirely.&lt;/p&gt;

&lt;p&gt;The choice of hidden state dimension involves important tradeoffs. Larger hidden dimensions provide more capacity to remember complex patterns and longer contexts. However, they increase parameters quadratically (\(\mathbf{W}_{hh}\) has \(d_h^2\) elements), slow computation (each time step requires \(O(d_h^2)\) operations), and can lead to overfitting on small datasets. A common starting point is matching hidden dimension to input dimension or using 128-512 depending on task complexity. For character-level modeling, 128-256 often suffices. For word-level language modeling on large vocabularies, 512-1024 is typical. Always validate on a held-out set and watch for train-test gaps indicating overfitting.&lt;/p&gt;

&lt;p&gt;Using teacher forcing during training but autoregressive generation during inference creates train-test mismatch in sequence-to-sequence models. During training with teacher forcing, the decoder receives the true previous token as input, ensuring it sees good inputs even when its predictions are poor. During inference, it must use its own predictions, which may be wrong, leading to compounding errors. This mismatch means the model never learns to recover from its own mistakes during training. Solutions include scheduled sampling (randomly using predicted tokens instead of true tokens during training with increasing probability), or using auxiliary losses that encourage robustness to input perturbations.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Recurrent Neural Networks introduced the fundamental idea of memory in neural networks through hidden states that persist across time steps, enabling modeling of sequential data where order and context matter. The mathematical elegance of parameter sharing across time—using the same weights at every step—allows RNNs to generalize across sequence lengths while learning temporal patterns. However, this same recurrence creates challenges: sequential processing prevents parallelization, making RNNs slow to train on GPUs; the product of Jacobians through time leads to vanishing or exploding gradients, limiting their ability to learn long-range dependencies; and the fixed-size hidden state creates an information bottleneck for long sequences. Despite these limitations, RNNs established principles—that networks can maintain state, that temporal structure should be explicitly modeled, that we can learn to predict future from past—that influence all subsequent sequence modeling architectures. Understanding RNNs deeply means understanding not just how they work but why they’re designed this way, where they fail, and how later innovations like LSTMs and Transformers address their limitations while building on their insights.&lt;/p&gt;

&lt;p&gt;The journey from feedforward networks to RNNs represents a crucial conceptual leap in deep learning: from processing static inputs independently to modeling dynamic processes with memory and temporal structure. This leap opens up vast new applications but introduces new challenges that have driven decades of research and continue to inspire innovation in sequence modeling architectures today.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, English. The character language model and the loss it trains.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=L8HKweZIOmg&quot;&gt;Sequence-to-Sequence (seq2seq) Encoder-Decoder Neural Networks, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Encoder-decoder sequence models are the related architecture the pitfalls section compares.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qhXZsFVxGKo&quot;&gt;Vanishing/Exploding Gradients (C2W1L10)&lt;/a&gt; — DeepLearningAI, English. Vanishing gradients through a long product are the BPTT failure this lesson warns about.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-01-02-01 RNN Core Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_01_02_01_RNN_Core_Code/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_01_02_01_RNN_Core_Code</id>
   <content type="html">&lt;p&gt;Writing an RNN from scratch in NumPy—maintaining a cache of every hidden state \(h_0, h_1, \dots, h_T\) during the forward pass and looping backward from \(t = T\) down to \(1\) to accumulate &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dW_hh&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dW_xh&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dh_next&lt;/code&gt;—is a rite of passage in deep learning. One subtle bug, such as forgetting to add &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dh_next&lt;/code&gt; to the current time step’s output gradient &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dy @ W_hy.T&lt;/code&gt; or omitting gradient norm clipping, will either freeze learning or explode parameters to infinity within ten epochs.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-engineering-details-of-recurrent-code&quot;&gt;Key ideas: Engineering Details of Recurrent Code&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Forward Caching for BPTT&lt;/strong&gt;: Unlike stateless layers, an RNN must retain every intermediate hidden state \(h_t\) and input \(x_t\) across the sequence because &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dW_hh += da_t @ h_{t-1}.T&lt;/code&gt; requires the exact historical states during the reverse sweep.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Accumulation Across Shared Weights&lt;/strong&gt;: Because \(W_{hh}\) and \(W_{xh}\) participate at every step \(t\), their gradients are &lt;strong&gt;summed&lt;/strong&gt; across all \(t = 1 \dots T\) before a single optimizer update—never overwritten step by step.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Clipping (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;clip_grad_norm_&lt;/code&gt;)&lt;/strong&gt;: Rescaling the global gradient vector \(g \leftarrow g \cdot \min\left(1, \frac{\tau}{\|g\|_2}\right)\) preserves the exact descent direction while preventing a single sharp curvature spike (“cliff”) in the recurrent loss landscape from catapulting weights out of the basin.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.RNN&lt;/code&gt; Tensor Conventions&lt;/strong&gt;: Understanding &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;batch_first=True&lt;/code&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, T, D)&lt;/code&gt; vs. default &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(T, N, D)&lt;/code&gt; and the distinction between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;output&lt;/code&gt; (all hidden states \(h_1 \dots h_T\)) and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;h_n&lt;/code&gt; (final layer states) prevents silent broadcasting bugs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-hand-verifying-global-gradient-norm-clipping&quot;&gt;Worked example: Hand-Verifying Global Gradient Norm Clipping&lt;/h3&gt;

&lt;p&gt;Suppose after one BPTT sweep over a 50-step sequence, our unclipped parameter gradient vector (flattened across &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;W_hh&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;W_xh&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;b_h&lt;/code&gt;) has 3 components \(g = [30.0, -40.0, 0.0]\), and we set the clipping threshold to \(\tau = 5.0\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the global \(L_2\) norm&lt;/strong&gt;:
\(\|g\|_2 = \sqrt{30^2 + (-40)^2 + 0^2} = \sqrt{900 + 1{,}600} = \sqrt{2{,}500} = 50.0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the clipping scale factor&lt;/strong&gt;:
\(\alpha = \min\!\left(1, \frac{\tau}{\|g\|_2}\right) = \min\!\left(1, \frac{5.0}{50.0}\right) = 0.1.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply uniform rescaling&lt;/strong&gt;:
\(g_{\text{clipped}} = 0.1 \cdot [30.0, -40.0, 0.0] = [3.0, -4.0, 0.0].\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify norm &amp;amp; direction preservation&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;New norm: \(\sqrt{3^2 + (-4)^2} = 5.0 = \tau\).&lt;/li&gt;
      &lt;li&gt;Cosine similarity between \(g\) and \(g_{\text{clipped}}\) is exactly \(1.0\) (unlike element-wise clipping &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;np.clip(g, -5, 5)&lt;/code&gt;, which would yield &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[5, -5, 0]&lt;/code&gt; and distort the gradient angle!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Let’s implement RNNs from first principles to understand every detail, then show modern PyTorch implementations:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VanillaRNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Vanilla RNN implementation from scratch using NumPy.
    
    This implementation prioritizes clarity over efficiency. We&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ll see exactly
    how hidden states evolve over time, how gradients flow backward, and where
    the vanishing gradient problem comes from. Understanding this manual
    implementation is crucial for debugging RNN training issues and for
    appreciating what modern frameworks do automatically.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Initialize RNN with careful weight initialization.
        
        For RNNs, initialization is even more critical than for feedforward networks.
        The recurrent weights Whh determine eigenvalues of the hidden state dynamics.
        If eigenvalues are too large (&amp;gt; 1), hidden states explode. Too small (&amp;lt; 1),
        they vanish. We initialize to small random values hoping to land in a
        stable regime, though this often fails for vanilla RNNs.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Input to hidden weights: map input space to hidden space
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Scale by 1/√hidden_size to maintain variance
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wxh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Hidden to hidden weights: THE critical matrix for temporal dynamics
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Some initialize to identity + noise for better gradient flow initially
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Whh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Hidden to output weights
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Biases
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Forward pass through entire sequence.
        
        inputs: list of input vectors [x_1, x_2, ..., x_T], each x_t is (input_size, 1)
        h_prev: initial hidden state (hidden_size, 1)
        
        Returns:
            outputs: list of output vectors [y_1, y_2, ..., y_T]
            hidden_states: list of hidden states [h_0, h_1, ..., h_T]
            
        We must store ALL hidden states because backpropagation through time
        needs them. This creates a memory cost linear in sequence length,
        which becomes prohibitive for very long sequences.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Process sequence one step at a time
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# This sequential loop is unavoidable in RNNs - we can&apos;t parallelize
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# across time because h_t depends on h_{t-1}
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Hidden state update: combine previous state and current input
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# The tanh bounds activations to [-1, 1], preventing explosion
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# (though it causes saturation and vanishing gradients)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Whh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wxh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_t&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Compute output from hidden state
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# For sequence classification, we&apos;d use only the final output
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# For sequence labeling, we use all outputs
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Backpropagation Through Time (BPTT).
        
        This is where RNNs get challenging. We must backpropagate gradients
        not just through layers (as in feedforward networks) but also backward
        through time. The gradient of the loss with respect to Whh involves
        contributions from all time steps, creating the long product of Jacobians
        that leads to vanishing/exploding gradients.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initialize gradient accumulators
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# These will accumulate gradients from all time steps
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wxh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Whh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros_like&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Gradient flowing back through time
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Initially zero, will accumulate as we backprop through time
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dh_next&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backpropagate through time (from T down to 1)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# This is the &quot;backward&quot; in backpropagation through time
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;reversed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Output error at this time step
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# For MSE loss: dy = y_pred - y_true
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Gradient of output layer parameters
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Backprop into hidden state
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# Two sources of gradient: from output at this time step (dy)
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# and from future time steps (dh_next)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dh_next&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Backprop through tanh nonlinearity
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# tanh&apos;(z) = 1 - tanh^2(z) = 1 - h^2
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# This derivative approaches 0 when |h| approaches 1 (saturation)
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# causing vanishing gradients
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dh&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Gradients of hidden layer parameters
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dz&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dz&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Pass gradient to previous time step
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# This is where the product of Jacobians occurs
&lt;/span&gt;            &lt;span class=&quot;c1&quot;&gt;# dh_next will be used at time step t-1
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dh_next&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Whh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dz&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Clip gradients to prevent explosion
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# This is a hack, but necessary for vanilla RNNs
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# We&apos;re treating the symptom (large gradients) not the cause
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# (fundamental instability of recurrent dynamics)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;update_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Standard gradient descent update&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Wxh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWxh&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Whh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhh&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Why&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dWhy&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bh&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dbh&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;by&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dby&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate on simple sequence prediction task
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Vanilla RNN: Predicting Next Number in Sequence&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Task: Given [1, 2, 3], predict [2, 3, 4]
# This tests if RNN can learn simple sequential pattern
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_sequence_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_sequences&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Generate training data: sequences of increasing numbers
    Input: [start, start+1, start+2, ...]
    Target: [start+1, start+2, start+3, ...]
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sequences_in&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;sequences_target&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_sequences&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;sequences_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;sequences_target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;seq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequences_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sequences_target&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create RNN
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VanillaRNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Generate data
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_targets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;generate_sequence_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_sequences&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_length&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training loop
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training RNN to predict next number...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute loss (MSE)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tgt&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_states&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;targets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Update
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;update_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_inputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;40&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Average Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test on new sequence
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Testing on new sequence: [10, 11, 12, 13, 14, 15, 16, 17]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;13&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;17&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;h_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;h_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_input&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  After seeing &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, predict next: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (true: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Note: Vanilla RNN struggles with this simple task due to vanishing gradients!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This motivates LSTM/GRU architectures we&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ll cover in the next chapter.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now let’s see a modern PyTorch implementation that handles these details automatically:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;RNNSequenceModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Modern RNN using PyTorch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s built-in RNN layer.
    
    PyTorch handles the recurrent computation efficiently, unrolling the loop
    in optimized C++ code and managing gradients automatically. This is much
    faster than our NumPy implementation and handles batching elegantly.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;RNNSequenceModel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# PyTorch&apos;s RNN module handles the recurrent computation
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# num_layers &amp;gt; 1 creates stacked RNNs (output of one feeds into next)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# batch_first=True means input shape is (batch, seq_len, input_size)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;RNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                         &lt;span class=&quot;n&quot;&gt;batch_first&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nonlinearity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Output layer to map hidden state to predictions
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: (batch, seq_len, input_size)
        hidden: optional initial hidden state (num_layers, batch, hidden_size)
        
        Returns:
            output: (batch, seq_len, output_size)
            hidden: final hidden state
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# If no initial hidden state provided, RNN initializes to zeros
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_cuda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;cuda&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# RNN returns:
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# - rnn_out: hidden states at all time steps (batch, seq_len, hidden_size)
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# - hidden: final hidden state (num_layers, batch, hidden_size)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;rnn_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;rnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Apply output layer to each time step
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Reshape to (batch * seq_len, hidden_size) for efficient computation
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rnn_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;rnn_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rnn_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rnn_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;reshape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;seq_len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=PaCmpygFfXo&quot;&gt;The spelled-out intro to language modeling: building makemore&lt;/a&gt; — Andrej Karpathy, English. A character RNN is implemented from a blank notebook, matching this lesson’s core loop.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 10&lt;/td&gt;
          &lt;td&gt;Recurrent Neural Networks](https://www.youtube.com/watch?v=6niqTuYFZLQ) — Stanford University School of Engineering, English. The equations that loop is implementing.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. A shorter picture of one step if the full coding video is too long to start with.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05-01-01 RNN Theory and Intuition</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_01_01_RNN_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_01_01_RNN_Theory</id>
   <content type="html">&lt;p&gt;At first glance, the Elman RNN equation \(h_t = \tanh(W_{hh} h_{t-1} + W_{xh} x_t + b_h)\) looks almost too simple to model human language or chaotic time series. Yet when you differentiate that equation across \(T\) time steps via Backpropagation Through Time (BPTT), a dramatic mathematical phenomenon emerges: the gradient from step \(T\) back to step \(1\) is governed by a product of \(T - 1\) Jacobian matrices. If the spectral radius (largest eigenvalue magnitude) of \(W_{hh}\) is slightly below \(1\), long-range signals decay exponentially to numerical zero; if it is slightly above \(1\), gradients detonate to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;. Understanding this exact Jacobian product is the theoretical key to all sequence modeling.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-mathematical-theory-of-vanilla-rnns&quot;&gt;Key ideas: The Mathematical Theory of Vanilla RNNs&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;State Transition &amp;amp; Output Projections&lt;/strong&gt;: At every step \(t\), pre-activation \(a_t = W_{hh} h_{t-1} + W_{xh} x_t + b_h\) passes through \(\tanh\) (keeping activations zero-centered in \((-1, 1)\)), while an output head \(\hat{y}_t = W_{hy} h_t + b_y\) maps hidden state to predictions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Backpropagation Through Time (BPTT)&lt;/strong&gt;: Because \(W_{hh}\) is reused at every step, the total loss gradient sums contributions from all time steps: \(\frac{\partial \mathcal{L}}{\partial W_{hh}} = \sum_{t=1}^T \sum_{k=1}^t \frac{\partial \mathcal{L}_t}{\partial h_t} \left(\prod_{j=k+1}^t \frac{\partial h_j}{\partial h_{j-1}}\right) \frac{\partial h_k}{\partial W_{hh}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Spectral Radius &amp;amp; Vanishing/Exploding Gradients&lt;/strong&gt;: Each step Jacobian is \(\frac{\partial h_j}{\partial h_{j-1}} = \operatorname{diag}(1 - h_j^2) W_{hh}\). Since \(0 \le 1 - \tanh^2(\cdot) \le 1\), repeated multiplication contracts gradients whenever \(\|W_{hh}\|_2 &amp;lt; 1\) and explodes them when \(\|W_{hh}\|_2 &amp;gt; 1\) (unless tamed by gradient clipping).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Truncated BPTT (TBPTT)&lt;/strong&gt;: For very long sequences, rolling back gradients only \(k_2\) steps trades exact long-range derivatives for bounded memory and faster updates.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-computing-a-2-step-rnn-forward-pass--exact-bptt-gradient&quot;&gt;Worked example: Computing a 2-Step RNN Forward Pass &amp;amp; Exact BPTT Gradient&lt;/h3&gt;

&lt;p&gt;Let \(d_h = 1, d_x = 1\) with \(w_{hh} = 0.8\), \(w_{xh} = 0.5\), \(b_h = 0\), initial state \(h_0 = 0\), input sequence \(x_1 = 1.0, x_2 = 1.0\), and loss \(\mathcal{L} = \frac{1}{2}(h_2 - 1.0)^2\) at step \(t = 2\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Forward pass&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Step 1: \(a_1 = 0.8(0) + 0.5(1.0) = 0.5 \implies h_1 = \tanh(0.5) \approx 0.4621\).&lt;/li&gt;
      &lt;li&gt;Step 2: \(a_2 = 0.8(0.4621) + 0.5(1.0) = 0.8697 \implies h_2 = \tanh(0.8697) \approx 0.7012\).&lt;/li&gt;
      &lt;li&gt;Loss: \(\mathcal{L} = \frac{1}{2}(0.7012 - 1.0)^2 \approx 0.0446\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Backward pass at step \(t = 2\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(\frac{\partial \mathcal{L}}{\partial h_2} = h_2 - 1.0 = -0.2988\).&lt;/li&gt;
      &lt;li&gt;Local \(\tanh\) derivative: \(1 - h_2^2 = 1 - 0.7012^2 \approx 0.5083\).&lt;/li&gt;
      &lt;li&gt;\(\delta_2 = \frac{\partial \mathcal{L}}{\partial a_2} = (-0.2988)(0.5083) \approx -0.1519\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Propagate gradient back to step \(t = 1\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(\frac{\partial \mathcal{L}}{\partial h_1} = \delta_2 \cdot w_{hh} = (-0.1519)(0.8) \approx -0.1215\).&lt;/li&gt;
      &lt;li&gt;Local \(\tanh\) derivative: \(1 - h_1^2 = 1 - 0.4621^2 \approx 0.7865\).&lt;/li&gt;
      &lt;li&gt;\(\delta_1 = \frac{\partial \mathcal{L}}{\partial a_1} = (-0.1215)(0.7865) \approx -0.0956\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Accumulate total gradient for shared weight \(w_{hh}\)&lt;/strong&gt;:
\(\frac{\partial \mathcal{L}}{\partial w_{hh}} = \delta_2 h_1 + \delta_1 h_0 = (-0.1519)(0.4621) + (-0.0956)(0) \approx -0.0702.\)
Observe the attenuation factor across just one step: \(|\delta_1 / \delta_2| = |w_{hh}(1 - h_1^2)| = 0.8 \times 0.7865 = 0.629\). Over 20 similar steps, \(0.629^{20} \approx 9.8 \times 10^{-5}\)—confirming why vanilla RNNs forget distant cues!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;recurrent-neural-networks-processing-sequential-data&quot;&gt;Recurrent Neural Networks: Processing Sequential Data&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter05/rnn_unrolled_architecture.png&quot; alt=&quot;RNN Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc RNN và quá trình unfolding theo thời gian. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Recurrent Neural Networks represent a fundamentally different approach to neural computation than the feedforward networks we’ve studied so far. While feedforward networks process each input independently, treating a batch of images or feature vectors as unrelated samples, RNNs are designed specifically for sequential data where the order of elements carries meaning and where context from previous elements should influence how we interpret current ones. This seemingly simple idea—adding memory to neural networks—opens up entire domains that feedforward networks cannot adequately address: natural language, where word order determines meaning; speech, where phonemes unfold over time; financial time series, where past trends inform future predictions; and video, where frames form coherent narratives.&lt;/p&gt;

&lt;p&gt;The core insight of RNNs is to maintain a hidden state that serves as the network’s memory. At each time step, the network receives a new input and the previous hidden state, processes both through the same set of weights, and produces a new hidden state and output. This recurrence—using the same parameters at every time step while the hidden state evolves—creates a network that can theoretically process sequences of any length while learning temporal patterns through the shared parameters. The elegance lies in parameter sharing across time: just as convolutional networks share weights spatially to detect features regardless of position, RNNs share weights temporally to recognize patterns regardless of when they occur in a sequence.&lt;/p&gt;

&lt;p&gt;Understanding why RNNs emerged requires appreciating the fundamental challenge of sequential data: variable length. A sentence might have five words or fifty. An audio clip might last three seconds or three minutes. How do we build neural networks that handle this variability? The naive approach—having separate parameters for each time step—fails immediately because it doesn’t generalize to sequences longer than those seen during training and requires enormous numbers of parameters. The elegant solution RNNs provide is to use the same transformation at each step, with the hidden state carrying forward information from all previous steps. This creates an architecture that’s both parameter-efficient and theoretically capable of modeling arbitrarily long sequences.&lt;/p&gt;

&lt;p&gt;However, RNNs are not without profound limitations. The sequential nature that gives them modeling power also makes them computationally slow—we cannot process time step \(t\) until we’ve processed step \(t-1\), preventing the parallelization that GPUs excel at. The need to propagate gradients backward through many time steps leads to vanishing or exploding gradients, making it difficult to learn long-range dependencies. And the fixed-size hidden state creates an information bottleneck—all information from the past must be compressed into this state, which becomes increasingly difficult as sequences grow longer. These limitations motivated the development of LSTM and GRU architectures, and ultimately, the attention mechanisms and Transformers that now dominate sequence modeling.&lt;/p&gt;

&lt;p&gt;Yet RNNs remain important to study, not just for historical reasons but because they embody fundamental principles about sequence processing. They introduce the concept of memory in neural networks. They demonstrate both the power and limitations of sequential processing. They reveal challenges in gradient propagation that inform our understanding of training deep networks more broadly. And in certain applications—particularly where sequences are naturally processed online or where computational efficiency on CPUs matters more than GPU throughput—RNNs and their sophisticated variants still have advantages over Transformers.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;The mathematical formulation of RNNs reveals both their elegance and their challenges. At each time step \(t\), an RNN maintains a hidden state \(\mathbf{h}_t\) that summarizes all information from the sequence up to that point. Given a new input \(\mathbf{x}_t\), the RNN updates its state according to:&lt;/p&gt;

\[\mathbf{h}_t = f(\mathbf{W}_{hh}\mathbf{h}_{t-1} + \mathbf{W}_{xh}\mathbf{x}_t + \mathbf{b}_h)\]

&lt;p&gt;where \(f\) is a nonlinear activation function (typically \(\tanh\) for vanilla RNNs), \(\mathbf{W}_{hh}\) governs how the previous state influences the current state (the recurrent connection), and \(\mathbf{W}_{xh}\) governs how the current input contributes. The bias \(\mathbf{b}_h\) provides a baseline activation level.&lt;/p&gt;

&lt;p&gt;This formulation deserves careful scrutiny because it encodes several crucial design decisions. First, the same weight matrices \(\mathbf{W}_{hh}\) and \(\mathbf{W}_{xh}\) are used at every time step. This parameter sharing across time is what enables RNNs to generalize to sequences of different lengths and to learn temporal patterns independent of their absolute position in the sequence. Just as convolutional filters detect edges anywhere in an image through spatial parameter sharing, recurrent weights detect temporal patterns anywhere in a sequence through temporal parameter sharing.&lt;/p&gt;

&lt;p&gt;Second, the hidden state \(\mathbf{h}_t\) plays a dual role. It serves as both the network’s memory (encoding information from all previous inputs) and as input to the next time step. This creates a feedback loop: the current state depends on the previous state, which depends on the state before that, creating a chain of dependencies that theoretically extends back to the beginning of the sequence. Mathematically, we can unroll this recursion:&lt;/p&gt;

\[\mathbf{h}_t = f(\mathbf{W}_{hh}f(\mathbf{W}_{hh}\mathbf{h}_{t-2} + \mathbf{W}_{xh}\mathbf{x}_{t-1} + \mathbf{b}_h) + \mathbf{W}_{xh}\mathbf{x}_t + \mathbf{b}_h)\]

&lt;p&gt;This shows how \(\mathbf{h}_t\) depends on inputs \(\mathbf{x}_t\) and \(\mathbf{x}_{t-1}\), and continuing the expansion, on all previous inputs back to \(\mathbf{x}_1\). The nested composition of functions is what gives RNNs their power to model complex temporal dependencies, but also what makes them challenging to train—gradients must backpropagate through this entire composition.&lt;/p&gt;

&lt;p&gt;The output at each time step is computed from the hidden state:&lt;/p&gt;

\[\mathbf{y}_t = g(\mathbf{W}_{hy}\mathbf{h}_t + \mathbf{b}_y)\]

&lt;p&gt;where \(g\) is an activation function chosen based on the task (softmax for classification, linear for regression, sigmoid for multi-label, etc.). Importantly, \(\mathbf{W}_{hy}\) is also shared across time steps. This means we’re using the same “decoder” to interpret the hidden state at every time step, forcing the hidden state to use a consistent representation scheme throughout the sequence.&lt;/p&gt;

&lt;p&gt;The dimensions of these matrices matter for understanding computational and representational tradeoffs. If the input dimension is \(d_x\), hidden dimension is \(d_h\), and output dimension is \(d_y\), then:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{W}_{xh} \in \mathbb{R}^{d_h \times d_x}\): Projects input to hidden dimension&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}_{hh} \in \mathbb{R}^{d_h \times d_h}\): Recurrent connections (most important!)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}_{hy} \in \mathbb{R}^{d_y \times d_h}\): Projects hidden to output&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The recurrent weight matrix \(\mathbf{W}_{hh}\) is particularly important because it determines how information persists over time. If \(\mathbf{W}_{hh}\) is nearly zero, the hidden state quickly forgets previous inputs. If it’s close to identity, the hidden state changes slowly. Its eigenvalues directly control gradient flow during backpropagation through time, as we’ll see.&lt;/p&gt;

&lt;p&gt;Different tasks require different architectural patterns. For sequence classification (sentiment analysis, video classification), we typically process the entire sequence and use only the final hidden state: \(\mathbf{y} = g(\mathbf{W}_{hy}\mathbf{h}_T + \mathbf{b}_y)\). The final state \(\mathbf{h}_T\) must summarize the entire sequence. For sequence labeling (part-of-speech tagging, named entity recognition), we produce outputs at every time step: \(\mathbf{y}_t = g(\mathbf{W}_{hy}\mathbf{h}_t + \mathbf{b}_y)\) for all \(t\). For sequence-to-sequence tasks (machine translation), the encoder RNN processes the input sequence into a final hidden state, which initializes a decoder RNN that generates the output sequence.&lt;/p&gt;

&lt;p&gt;Training RNNs requires Backpropagation Through Time (BPTT), which is simply backpropagation applied to the unrolled computational graph of the RNN. The loss over a sequence is typically the sum of losses at each time step:&lt;/p&gt;

\[\mathcal{L} = \sum_{t=1}^{T} \mathcal{L}_t(\mathbf{y}_t, \hat{\mathbf{y}}_t)\]

&lt;p&gt;To compute gradients of this loss with respect to \(\mathbf{W}_{hh}\), we must account for the fact that \(\mathbf{W}_{hh}\) affects the hidden state at every time step. The gradient is:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}_{hh}} = \sum_{t=1}^{T} \frac{\partial \mathcal{L}_t}{\partial \mathbf{W}_{hh}}\]

&lt;p&gt;Each term \(\frac{\partial \mathcal{L}_t}{\partial \mathbf{W}_{hh}}\) requires backpropagating through all time steps from 1 to \(t\) via the chain rule, because \(\mathbf{W}_{hh}\) influences \(\mathbf{h}_1\), which influences \(\mathbf{h}_2\), and so on up to \(\mathbf{h}_t\). This creates a computational graph that grows with sequence length, leading to both memory challenges (must store all hidden states) and the notorious vanishing/exploding gradient problem.&lt;/p&gt;

&lt;p&gt;The gradient flow analysis reveals the core challenge. The gradient of \(\mathbf{h}_t\) with respect to \(\mathbf{h}_k\) (for \(k &amp;lt; t\)) involves a product of Jacobian matrices:&lt;/p&gt;

\[\frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_k} = \prod_{i=k+1}^{t} \frac{\partial \mathbf{h}_i}{\partial \mathbf{h}_{i-1}}\]

&lt;p&gt;Each Jacobian \(\frac{\partial \mathbf{h}_i}{\partial \mathbf{h}_{i-1}} = \text{diag}(f&apos;(\mathbf{z}_i)) \mathbf{W}_{hh}\) is the product of the activation derivative (which for \(\tanh\) is bounded by 1) and the recurrent weight matrix. If the largest singular value of \(\mathbf{W}_{hh}\) is less than 1, these products shrink exponentially with the number of time steps, causing vanishing gradients. If it’s greater than 1, they explode exponentially. This is not a minor technical issue but a fundamental challenge in training RNNs to capture long-range dependencies.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;To build genuine intuition for how RNNs process sequences, let’s trace through a concrete example of processing the sentence “The cat sat on the mat” for sentiment analysis. We’ll use a simple RNN with 3-dimensional hidden state (unrealistically small for clarity) to predict positive or negative sentiment.&lt;/p&gt;

&lt;p&gt;Initially, before seeing any words, we set \(\mathbf{h}_0 = \mathbf{0}\), representing no information. The first word “The” arrives. Suppose after embedding it becomes \(\mathbf{x}_1 = [0.2, -0.1, 0.5]\). With initialized weights (let’s use small random values):&lt;/p&gt;

\[\mathbf{W}_{hh} = \begin{bmatrix} 0.5 &amp;amp; 0.1 &amp;amp; -0.2 \\ -0.1 &amp;amp; 0.6 &amp;amp; 0.3 \\ 0.2 &amp;amp; -0.3 &amp;amp; 0.4 \end{bmatrix}, \quad \mathbf{W}_{xh} = \begin{bmatrix} 0.3 &amp;amp; 0.2 &amp;amp; -0.1 \\ 0.1 &amp;amp; -0.2 &amp;amp; 0.4 \\ -0.2 &amp;amp; 0.3 &amp;amp; 0.1 \end{bmatrix}\]

&lt;p&gt;The hidden state update computes:&lt;/p&gt;

\[\mathbf{z}_1 = \mathbf{W}_{hh}\mathbf{h}_0 + \mathbf{W}_{xh}\mathbf{x}_1 + \mathbf{b}_h = \mathbf{0} + \mathbf{W}_{xh}\mathbf{x}_1 + \mathbf{b}_h\]

&lt;p&gt;Since \(\mathbf{h}_0 = \mathbf{0}\), the first hidden state depends only on the first input:&lt;/p&gt;

\[\mathbf{h}_1 = \tanh(\mathbf{z}_1) = \tanh\begin{pmatrix}\begin{bmatrix} 0.3 &amp;amp; 0.2 &amp;amp; -0.1 \\ 0.1 &amp;amp; -0.2 &amp;amp; 0.4 \\ -0.2 &amp;amp; 0.3 &amp;amp; 0.1 \end{bmatrix} \begin{bmatrix} 0.2 \\ -0.1 \\ 0.5 \end{bmatrix} + \mathbf{b}_h\end{pmatrix}\]

&lt;p&gt;Let’s say this gives \(\mathbf{h}_1 = [0.1, 0.05, -0.15]\) (after \(\tanh\)). This vector now encodes “having seen ‘The’“—not very informative, but it’s a start. Now “cat” arrives as \(\mathbf{x}_2 = [0.8, 0.3, -0.2]\). The state update now has TWO contributions:&lt;/p&gt;

\[\mathbf{z}_2 = \mathbf{W}_{hh}\mathbf{h}_1 + \mathbf{W}_{xh}\mathbf{x}_2 + \mathbf{b}_h\]

&lt;p&gt;The first term \(\mathbf{W}_{hh}\mathbf{h}_1\) carries forward information from “The”, while \(\mathbf{W}_{xh}\mathbf{x}_2\) processes “cat”. The \(\tanh\) nonlinearity combines these:&lt;/p&gt;

\[\mathbf{h}_2 = \tanh(\mathbf{z}_2)\]

&lt;p&gt;This new state encodes “having seen ‘The cat’“—it’s been influenced by both words, with the contribution of “The” mediated through \(\mathbf{h}_1\) and the recurrent weights \(\mathbf{W}_{hh}\).&lt;/p&gt;

&lt;p&gt;As we continue through “sat”, “on”, “the”, “mat”, each hidden state incorporates more context. By the time we reach the end, \(\mathbf{h}_6\) theoretically encodes the entire sentence’s meaning. We then use this to predict sentiment:&lt;/p&gt;

\[\text{sentiment} = \text{sigmoid}(\mathbf{W}_{hy}\mathbf{h}_6 + \mathbf{b}_y)\]

&lt;p&gt;The key insight is that information from “The” at the beginning must flow through \(\mathbf{h}_1 \to \mathbf{h}_2 \to \cdots \to \mathbf{h}_6\) to influence the final prediction. Each transition involves multiplication by \(\mathbf{W}_{hh}\) and passing through \(\tanh\). If \(\mathbf{W}_{hh}\) consistently suppresses signals (eigenvalues &amp;lt; 1), information decays exponentially—this is vanishing gradients. If it amplifies signals (eigenvalues &amp;gt; 1), information explodes—exploding gradients. Maintaining stable information flow over many steps is the central challenge of vanilla RNNs.&lt;/p&gt;

&lt;p&gt;Consider what happens during backpropagation. When we compute \(\frac{\partial \mathcal{L}}{\partial \mathbf{W}_{hh}}\), we must account for \(\mathbf{W}_{hh}\) appearing at every time step. The gradient involves products like:&lt;/p&gt;

\[\frac{\partial \mathbf{h}_6}{\partial \mathbf{h}_1} = \frac{\partial \mathbf{h}_6}{\partial \mathbf{h}_5} \frac{\partial \mathbf{h}_5}{\partial \mathbf{h}_4} \cdots \frac{\partial \mathbf{h}_2}{\partial \mathbf{h}_1}\]

&lt;p&gt;Each Jacobian \(\frac{\partial \mathbf{h}_{t+1}}{\partial \mathbf{h}_t} = \text{diag}(\tanh&apos;(\mathbf{z}_{t+1})) \mathbf{W}_{hh}\) involves the recurrent weight matrix and the activation derivative.&lt;/p&gt;

&lt;p&gt;For \(\tanh\), the derivative is bounded by 1 and typically much smaller (approaching 0 for saturated activations). This means each Jacobian typically has norm less than \(\|\mathbf{W}_{hh}\|\), and their product shrinks exponentially unless \(\|\mathbf{W}_{hh}\|\) is precisely calibrated. In practice, this delicate balancing rarely works for vanilla RNNs, limiting their ability to learn dependencies spanning more than about 10-20 time steps.&lt;/p&gt;

&lt;p&gt;The mathematics of different RNN architectures reveals different design philosophies. A many-to-one architecture (sequence → single output) computes \(\mathbf{h}_t\) for all \(t\) but only uses \(\mathbf{h}_T\) for the final prediction, appropriate for classification tasks. A many-to-many architecture with the same length (sequence → sequence of same length) computes outputs \(\mathbf{y}_t = g(\mathbf{W}_{hy}\mathbf{h}_t + \mathbf{b}_y)\) at every time step, useful for tasks like video frame labeling where we want to classify each frame. A many-to-many architecture with different lengths (sequence-to-sequence) requires an encoder-decoder design: the encoder RNN processes the input into a final hidden state \(\mathbf{h}_T^{enc}\), which initializes the decoder RNN: \(\mathbf{h}_0^{dec} = \mathbf{h}_T^{enc}\). The decoder then autoregressively generates output, with each output feeding into the next time step’s input until a special end-of-sequence token is generated.&lt;/p&gt;

&lt;p&gt;The computational complexity of RNNs is linear in sequence length: \(O(T \cdot d_h^2)\) where \(T\) is sequence length and \(d_h\) is hidden dimension (dominated by the \(\mathbf{W}_{hh}\mathbf{h}_{t-1}\) multiplication at each step). This seems efficient, but the sequential dependency means we cannot parallelize across time steps. Processing a sequence of length 100 requires 100 sequential matrix multiplications, even with a powerful GPU. Transformers, by contrast, have higher complexity \(O(T^2 d)\) but can process all positions in parallel, making them much faster in practice on modern hardware when \(T\) is not extremely large.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. The hidden-state update h_t = f(h_{t-1}, x_t) is this lesson’s equation.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 10&lt;/td&gt;
          &lt;td&gt;Recurrent Neural Networks](https://www.youtube.com/watch?v=6niqTuYFZLQ) — Stanford University School of Engineering, English. Unrolls that equation and shows where the gradient has to travel.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>05 Introduction to Recurrent Neural Networks</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter05/05_00_Introduction</id>
   <content type="html">&lt;p&gt;Feedforward networks and CNNs share a quiet limitation: they suffer from total amnesia. Show a standard MLP one word of a sentence at a time, and its prediction for word five has no memory of words one through four—unless you hard-code a fixed context window and duplicate weights for every position. Natural language, audio waveforms, electrocardiograms, and financial time series do not arrive as fixed-size grids; they unfold in time with arbitrary length and causal dependencies that can span dozens of steps. Recurrent Neural Networks (RNNs) solved this by introducing a feedback loop—a compact &lt;strong&gt;hidden state vector&lt;/strong&gt; \(h_t\) that travels forward through time, continuously folding each new observation \(x_t\) into a running summary of the past.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-foundations-of-recurrent-sequence-modeling&quot;&gt;Key ideas: Foundations of Recurrent Sequence Modeling&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Dynamical Systems &amp;amp; State-Space Recursion&lt;/strong&gt;: An RNN is a discrete-time nonlinear dynamical system \(h_t = f_\theta(h_{t-1}, x_t)\). The hidden state \(h_t \in \mathbb{R}^d\) acts as a compressed sufficient statistic of the entire history \((x_1, \dots, x_t)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Temporal Weight Sharing&lt;/strong&gt;: Just as CNNs share weights across spatial coordinates, RNNs share the exact same matrices \((W_{hh}, W_{xh}, W_{hy})\) across every time step \(t\). This grants generalization to arbitrary sequence lengths unseen during training.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Unrolling Through Time (Computational Graphs)&lt;/strong&gt;: Unfolding the recurrence over \(T\) steps reveals a deep feedforward DAG of depth \(T\) with tied weights—allowing standard backpropagation (now called &lt;strong&gt;BPTT&lt;/strong&gt;, Backpropagation Through Time) to compute exact parameter gradients.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sequence-to-Sequence Topologies&lt;/strong&gt;: Depending on when inputs arrive and outputs are read, the same recurrent cell supports one-to-many (image captioning), many-to-one (sentiment classification), and many-to-many (tagging, translation, language modeling) tasks.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-unrolling-a-1d-scalar-rnn-over-3-time-steps&quot;&gt;Worked example: Unrolling a 1D Scalar RNN Over 3 Time Steps&lt;/h3&gt;

&lt;p&gt;Consider a minimal scalar RNN with \(h_0 = 0\), recurrent weight \(w_{hh} = 0.5\), input weight \(w_{xh} = 1.0\), bias \(b_h = 0\), and linear activation (for transparent arithmetic), processing the input sequence \(x = [2, -1, 4]\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Step \(t = 1\) (\(x_1 = 2\))&lt;/strong&gt;:
\(h_1 = w_{hh} h_0 + w_{xh} x_1 = 0.5(0) + 1.0(2) = 2.0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step \(t = 2\) (\(x_2 = -1\))&lt;/strong&gt;:
\(h_2 = 0.5(2.0) + 1.0(-1) = 1.0 - 1.0 = 0.0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step \(t = 3\) (\(x_3 = 4\))&lt;/strong&gt;:
\(h_3 = 0.5(0.0) + 1.0(4) = 4.0.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Closed-form memory decay&lt;/strong&gt;: Expanding the recursion shows
\(h_3 = x_3 + 0.5 x_2 + 0.5^2 x_1 = 4 + 0.5(-1) + 0.25(2) = 4 - 0.5 + 0.5 = 4.0.\)
Notice how the weight \(w_{hh}^k = 0.5^k\) exponentially damps older inputs—a direct preview of the vanishing gradient problem in BPTT when \(|w_{hh}| &amp;lt; 1\) (and exploding gradients when \(|w_{hh}| &amp;gt; 1\)).&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;introduction-to-recurrent-neural-networks&quot;&gt;Introduction to Recurrent Neural Networks&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter05/rnn_unrolled_architecture.png&quot; alt=&quot;RNN Unrolled Architecture&quot; /&gt;
&lt;em&gt;Hình ảnh: Kiến trúc RNN ở dạng folded (trái) và unrolled (phải). Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Recurrent Neural Networks (RNNs) represent a fundamental paradigm shift in neural network design: the introduction of &lt;strong&gt;memory&lt;/strong&gt;. While feedforward networks and CNNs process each input independently, treating each data point as an isolated sample, RNNs maintain an internal state that evolves as they process sequential data. This seemingly simple addition — allowing information to persist through time — opens up entirely new problem domains: natural language, speech, music, video, time series forecasting, and any task where &lt;strong&gt;order matters&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The key insight that makes RNNs powerful is their ability to process inputs of &lt;strong&gt;variable length&lt;/strong&gt;. A sentence can be 3 words or 30. A video can be 10 frames or 10,000. An audio clip can be 1 second or 1 hour. Traditional neural networks require fixed-size inputs, forcing us to truncate or pad sequences to a uniform length — losing information in the process. RNNs solve this elegantly by processing sequences one element at a time, using the same computation at each step, with a hidden state that carries information forward through the sequence. This design allows RNNs to theoretically handle sequences of arbitrary length while using a fixed number of parameters.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;why-sequential-data-needs-different-architectures&quot;&gt;Why Sequential Data Needs Different Architectures&lt;/h2&gt;

&lt;p&gt;Consider these inputs where order determines meaning:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Example&lt;/th&gt;
      &lt;th&gt;Reversed Order&lt;/th&gt;
      &lt;th&gt;Meaning Change&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;“The &lt;strong&gt;dog&lt;/strong&gt; bit the man”&lt;/td&gt;
      &lt;td&gt;“The man bit the &lt;strong&gt;dog&lt;/strong&gt;”&lt;/td&gt;
      &lt;td&gt;Subject ↔ Object flipped&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;“The food was &lt;strong&gt;not&lt;/strong&gt; bad”&lt;/td&gt;
      &lt;td&gt;“The food was bad”&lt;/td&gt;
      &lt;td&gt;Entire sentiment inverted&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;“She only has eyes for him”&lt;/td&gt;
      &lt;td&gt;“She has only eyes for him”&lt;/td&gt;
      &lt;td&gt;Literal → Idiomatically different&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;This isn’t limited to language. In virtually every domain where sequential data appears, context matters:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Stock prices&lt;/strong&gt;: Yesterday’s closing price is today’s baseline. Last week’s trend informs this week’s prediction. The 2008 financial crisis wasn’t just about one day’s numbers — it emerged from patterns unfolding over months.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Speech recognition&lt;/strong&gt;: Distinguishing “recognize speech” from “wreck a nice beach” requires temporal context that spans phonemes, not individual sounds.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Video understanding&lt;/strong&gt;: A ball’s trajectory makes sense only in the context of previous frames. Without temporal context, we can’t distinguish a ball being thrown versus a ball being caught.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Protein folding&lt;/strong&gt;: A protein’s 3D structure depends on the sequential folding process, not just the amino acid sequence.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Musical composition&lt;/strong&gt;: A chord’s emotional impact depends entirely on what came before. The same chord can sound consonant or dissonant based on context.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;The core challenge&lt;/strong&gt;: Feedforward networks treat each input as independent. They have no mechanism to know that word #5 came after word #4. They process “The dog bit the man” and “The man bit the dog” identically — both contain the same words! CNNs can detect spatial patterns but fundamentally lack temporal memory. RNNs solve this by &lt;strong&gt;passing information from one time step to the next&lt;/strong&gt; through a hidden state that serves as memory.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;the-core-idea-hidden-state-as-memory&quot;&gt;The Core Idea: Hidden State as Memory&lt;/h2&gt;

&lt;p&gt;At each time step \(t\), an RNN performs a remarkably simple operation:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Receives&lt;/strong&gt; a new input \(\mathbf{x}_t\) (e.g., the next word, frame, or data point)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Combines&lt;/strong&gt; it with the previous hidden state \(\mathbf{h}_{t-1}\) — the network’s memory of everything it’s seen so far&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Produces&lt;/strong&gt; a new hidden state \(\mathbf{h}_t\) — updated memory that now incorporates the new input&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Optionally produces&lt;/strong&gt; an output \(\mathbf{y}_t\) — prediction based on what the network has seen&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The mathematical heart of the RNN is remarkably simple:&lt;/p&gt;

\[\mathbf{h}_t = \tanh(\mathbf{W}_{hh}\mathbf{h}_{t-1} + \mathbf{W}_{xh}\mathbf{x}_t + \mathbf{b}_h)\]

&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{x}_t \in \mathbb{R}^{d_x}\) is the input at time \(t\)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{h}_{t-1} \in \mathbb{R}^{d_h}\) is the previous hidden state (memory)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}_{xh} \in \mathbb{R}^{d_h \times d_x}\) transforms input to hidden dimension&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}_{hh} \in \mathbb{R}^{d_h \times d_h}\) is the recurrent (hidden-to-hidden) weight matrix&lt;/li&gt;
  &lt;li&gt;\(\tanh\) squashes activations to \([-1, 1]\), providing a nonlinearity while preventing explosion&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter05/rnn_unrolled.png&quot; alt=&quot;RNN Unrolled&quot; /&gt;
&lt;em&gt;Hình ảnh: RNN unrolled qua các time step, thể hiện hidden state được truyền từ step này sang step tiếp theo.&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;why-this-works-three-key-insights&quot;&gt;Why This Works: Three Key Insights&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Parameter sharing across time&lt;/strong&gt;: The same weights \(\mathbf{W}_{xh}\) and \(\mathbf{W}_{hh}\) are used at every time step. This is analogous to how CNNs share weights across spatial positions. When the network learns that the pattern “verb follows subject” is important, it learns this once — not separately for each position in the sentence.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. The hidden state as compressed context&lt;/strong&gt;: The hidden state \(\mathbf{h}_t\) is a fixed-size vector (e.g., 256 or 512 dimensions) that must encode everything about the sequence up to time \(t\). This compression is lossy — information must be prioritized. The network learns what information to preserve and what to discard.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Recursive composition&lt;/strong&gt;: Because \(\mathbf{h}_t\) depends on \(\mathbf{h}_{t-1}\), which depends on \(\mathbf{h}_{t-2}\), and so on, the hidden state at time \(t\) theoretically contains information from all previous inputs. This recursive composition is what gives RNNs their theoretical ability to model arbitrarily long-range dependencies — though in practice, gradient decay limits this range.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;historical-context-why-rnns-matter&quot;&gt;Historical Context: Why RNNs Matter&lt;/h2&gt;

&lt;p&gt;Understanding RNNs isn’t just about learning legacy technology. It’s about understanding the conceptual journey:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;1986&lt;/strong&gt;: Elman (1990) introduced the Simple Recurrent Network, demonstrating that recurrent connections could learn temporal patterns&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;1997&lt;/strong&gt;: Hochreiter &amp;amp; Schmidhuber introduced LSTM, addressing the vanishing gradient problem with gating mechanisms&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2014&lt;/strong&gt;: Cho et al. introduced GRU, simplifying LSTM while maintaining performance&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2015&lt;/strong&gt;: Bahdanau et al. introduced attention, allowing direct connections to any past state&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2017&lt;/strong&gt;: Vaswani et al. introduced Transformers, abandoning recurrence entirely for parallel attention&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each innovation solved problems with previous approaches while maintaining their insights. Understanding RNNs means understanding why each subsequent architecture was developed — and when to use each.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;the-road-ahead&quot;&gt;The Road Ahead&lt;/h2&gt;

&lt;p&gt;RNNs introduced crucial concepts but have fundamental limitations:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Limitation&lt;/th&gt;
      &lt;th&gt;Impact&lt;/th&gt;
      &lt;th&gt;Modern Solution&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Sequential processing&lt;/td&gt;
      &lt;td&gt;Can’t parallelize across time&lt;/td&gt;
      &lt;td&gt;Transformers (attention)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Vanishing gradients&lt;/td&gt;
      &lt;td&gt;Can’t learn long dependencies&lt;/td&gt;
      &lt;td&gt;LSTMs/GRUs (gating)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Information bottleneck&lt;/td&gt;
      &lt;td&gt;Fixed memory loses information&lt;/td&gt;
      &lt;td&gt;Attention ( direct access)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;These limitations motivated the development of:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;LSTMs and GRUs&lt;/strong&gt; (Chapter 6): Gating mechanisms that create skip connections through time&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Attention mechanisms&lt;/strong&gt; (Chapter 7): Direct connections to any past state without compression&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Transformers&lt;/strong&gt; (Chapter 8): Abandoning recurrence entirely for parallel computation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Understanding RNNs deeply — both their elegance and their limitations — is essential for appreciating why modern architectures evolved the way they did. The RNN isn’t just a predecessor; it’s the foundation upon which sequence modeling was built.&lt;/p&gt;

&lt;h2 id=&quot;types-of-rnn-architectures&quot;&gt;Types of RNN Architectures&lt;/h2&gt;

&lt;p&gt;RNNs can be configured in several ways depending on the task:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Architecture&lt;/th&gt;
      &lt;th&gt;Input&lt;/th&gt;
      &lt;th&gt;Output&lt;/th&gt;
      &lt;th&gt;Example Tasks&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Many-to-One&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Sequence&lt;/td&gt;
      &lt;td&gt;Single value&lt;/td&gt;
      &lt;td&gt;Sentiment classification, intent detection&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;One-to-Many&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Single value&lt;/td&gt;
      &lt;td&gt;Sequence&lt;/td&gt;
      &lt;td&gt;Music generation, image captioning&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Many-to-Many (Same)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Sequence&lt;/td&gt;
      &lt;td&gt;Sequence (same length)&lt;/td&gt;
      &lt;td&gt;Part-of-speech tagging, frame-level video classification&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Many-to-Many (Diff)&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Sequence&lt;/td&gt;
      &lt;td&gt;Sequence (different length)&lt;/td&gt;
      &lt;td&gt;Machine translation, summarization&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter05/rnn_types_architecture.png&quot; alt=&quot;RNN Types&quot; /&gt;
&lt;em&gt;Hình ảnh: Các kiểu kiến trúc RNN - Many-to-One, One-to-Many, Many-to-Many. Red: Input, Green: Hidden, Blue: Output. Nguồn: CS231n&lt;/em&gt;&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;the-three-fundamental-challenges&quot;&gt;The Three Fundamental Challenges&lt;/h2&gt;

&lt;p&gt;Despite their elegance, vanilla RNNs face three challenges that motivated subsequent innovations:&lt;/p&gt;

&lt;h3 id=&quot;1-sequential-processing-cant-parallelize&quot;&gt;1. Sequential Processing (Can’t Parallelize)&lt;/h3&gt;
&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter05/rnn_blackbox.png&quot; alt=&quot;RNN Black Box&quot; /&gt;
&lt;em&gt;Hình ảnh: RNN như một black box với feedback loop — hidden state được truyền ngược lại làm input cho bước tiếp theo.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Unlike feedforward networks where all samples process independently, RNNs must compute \(\mathbf{h}_t\) before \(\mathbf{h}_{t+1}\). This sequential dependency means:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;GPU parallelization provides limited benefit&lt;/li&gt;
  &lt;li&gt;Long sequences take time proportional to their length&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Modern solution&lt;/strong&gt;: Transformers use attention to process all positions simultaneously&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-vanishing-gradients-cant-remember-long-dependencies&quot;&gt;2. Vanishing Gradients (Can’t Remember Long Dependencies)&lt;/h3&gt;
&lt;p&gt;When backpropagating through time, gradients multiply through many layers. If each layer slightly shrinks the gradient (multiplication by &amp;lt; 1), the gradient vanishes exponentially:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{h}_1} = \frac{\partial \mathcal{L}}{\partial \mathbf{h}_T} \cdot \prod_{t=2}^{T} \frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-1}}\]

&lt;p&gt;For a 50-step sequence with a Jacobian eigenvalue of 0.99, the gradient is multiplied by \(0.99^{49} \approx 0.61\) — essentially zero.&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Modern solutions&lt;/strong&gt;: LSTMs and GRUs use gating mechanisms to create direct “highways” for gradient flow&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-information-bottleneck-fixed-size-memory&quot;&gt;3. Information Bottleneck (Fixed-Size Memory)&lt;/h3&gt;
&lt;p&gt;The hidden state \(\mathbf{h}_t\) must encode the entire history of the sequence in a fixed-size vector. As sequences grow longer:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Information must be progressively compressed&lt;/li&gt;
  &lt;li&gt;Details from the beginning are lost&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Modern solutions&lt;/strong&gt;: Attention mechanisms allow direct access to any previous position without compression&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These limitations aren’t failures — they’re insights that drove the evolution of sequence modeling from RNNs → LSTMs → Attention → Transformers.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Before studying RNNs, ensure you understand:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Feedforward networks&lt;/strong&gt; and backpropagation (Chapters 2-3)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matrix multiplication&lt;/strong&gt; — the foundation of all neural network computation&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chain rule&lt;/strong&gt; — how gradients compose through multiple layers&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why gradient magnitude matters&lt;/strong&gt; — large or small gradients affect training stability&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;what-this-chapter-covers&quot;&gt;What This Chapter Covers&lt;/h2&gt;

&lt;p&gt;This chapter provides a comprehensive understanding of RNNs from first principles to practical implementation:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Mathematical foundations&lt;/strong&gt; — The equations that govern recurrent computation, unrolled through time, with matrix dimensions clearly specified&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Backpropagation Through Time (BPTT)&lt;/strong&gt; — How gradients flow backward through the computational graph, and why this creates the vanishing gradient problem&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Intuitive examples&lt;/strong&gt; — Step-by-step tracing through concrete sequences to build genuine understanding of how information flows&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Implementation&lt;/strong&gt; — Complete NumPy implementation from scratch showing every operation, followed by production-quality PyTorch code&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Character-level language modeling&lt;/strong&gt; — A complete example showing how RNNs learn to generate text character by character&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Limitations and solutions&lt;/strong&gt; — Understanding what’s missing in vanilla RNNs prepares you for LSTMs, GRUs, and Transformers&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s begin with the mathematics and implementation of vanilla RNNs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After vanilla RNNs, see &lt;strong&gt;05-99 Modern Applications and Updates&lt;/strong&gt; for Mamba, RWKV, and when linear recurrences compete with Transformers. The LLM-hub contrast (RNN state vs growing KV cache, plus one SSM paragraph) is &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=AsNTP8Kwu80&quot;&gt;Recurrent Neural Networks (RNNs), Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. A hidden state as memory is the reason this chapter exists.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=dqoEU9Ac3ek&quot;&gt;MIT 6.S191 (2024): Recurrent Neural Networks, Transformers, and Attention&lt;/a&gt; — Alexander Amini, English. MIT’s 2024 sequence lecture places that memory next to attention, which is the roadmap.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 10&lt;/td&gt;
          &lt;td&gt;Recurrent Neural Networks](https://www.youtube.com/watch?v=6niqTuYFZLQ) — Stanford University School of Engineering, English. Stanford’s RNN lecture for the three failure modes the introduction names.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_99_Modern_Applications</id>
   <content type="html">&lt;p&gt;When Vision Transformers (ViT) arrived in 2020, many predicted the immediate extinction of Convolutional Neural Networks. Yet by 2022, ConvNeXt stunned the field by showing that a pure CNN—modernized with larger \(7 \times 7\) depthwise kernels, inverted bottlenecks, LayerNorm, GELU, and AdamW training recipes—could match or surpass hierarchical Vision Transformers like Swin on ImageNet, COCO, and ADE20K. Today’s frontier vision systems (from ConvNeXt V2 and SAM-style hybrids to edge robotics models) reveal a deeper truth: convolution and attention are complementary operators, not rivals.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-modernizing-cnns-in-the-transformer-era&quot;&gt;Key ideas: Modernizing CNNs in the Transformer Era&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Training Recipe vs. Architectural Inductive Bias&lt;/strong&gt;: Much of ViT’s early advantage came from modern optimization (AdamW, cosine decay, Mixup, CutMix, RandAugment, stochastic depth) rather than self-attention alone; porting those recipes back to ResNet/ConvNeXt closed the gap dramatically.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Macro &amp;amp; Micro Modernizations (ConvNeXt Blueprint)&lt;/strong&gt;: Replacing \(3 \times 3\) standard convs with \(7 \times 7\) depthwise convs expands receptive fields cheaply, while inverted bottlenecks (expand \(4\times\) then project back) mirror Transformer MLP blocks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hybrid Convolution–Attention Backbones&lt;/strong&gt;: Modern vision foundation models routinely use convolutional stems (fast, inductive-bias-rich local feature extraction at high resolution) feeding global Transformer blocks at low resolution—avoiding the \(O(N^2)\) cost of self-attention on raw pixels.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Edge Deployment &amp;amp; Hardware Determinism&lt;/strong&gt;: On mobile NPUs, autonomous vehicles, and high-resolution medical imaging, CNNs still win on latency predictability, memory bandwidth, and small-data sample efficiency.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-a-7-times-7-depthwise-conv-beats-a-3-times-3-standard-conv&quot;&gt;Worked example: Why a \(7 \times 7\) Depthwise Conv Beats a \(3 \times 3\) Standard Conv&lt;/h3&gt;

&lt;p&gt;Consider a modern ConvNeXt block operating on \(C = 96\) channels at resolution \(56 \times 56\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Classic ResNet \(3 \times 3\) standard conv (\(96 \to 96\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Parameters: \(96 \times 96 \times 3 \times 3 = 82{,}944\).&lt;/li&gt;
      &lt;li&gt;Receptive field of this single layer: \(3 \times 3\) (9 pixels).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ConvNeXt \(7 \times 7\) depthwise conv (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;groups=96&lt;/code&gt;)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Parameters: \(96 \times 1 \times 7 \times 7 = 4{,}704\).&lt;/li&gt;
      &lt;li&gt;Receptive field of this single layer: \(7 \times 7\) (49 pixels—over \(5.4\times\) larger area!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare parameter cost&lt;/strong&gt;:
\(\frac{82{,}944}{4{,}704} = 17.63\times \text{ fewer parameters}\)
for the \(7 \times 7\) depthwise spatial mixer! The saved parameter budget is then invested into the inverted pointwise MLP (\(96 \to 384 \to 96\): \(2 \times 96 \times 384 = 73{,}728\) weights), separating spatial mixing from channel mixing just like a Transformer block.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-convnets-after-convnext-and-vision-foundation-models&quot;&gt;Optional: ConvNets after ConvNeXt and vision foundation models&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; rewrite convolution math, pooling, or the LeNet–ResNet history. It updates what practitioners actually deploy for vision after 2022.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The convolution \((\mathbf{x} * \mathbf{k})_{i} = \sum_{u} x_{i+u}\,k_{u}\) is unchanged. What changed is the &lt;strong&gt;macro architecture&lt;/strong&gt; (ConvNeXt) and the &lt;strong&gt;use case&lt;/strong&gt; (frozen convolutional or hybrid backbones inside foundation models).&lt;/p&gt;

&lt;h2 id=&quot;1-convnext-a-convnet-that-borrowed-transformer-training&quot;&gt;1. ConvNeXt: a ConvNet that borrowed Transformer training&lt;/h2&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2201.03545&quot;&gt;Liu et al., 2022&lt;/a&gt; (“A ConvNet for the 2020s”) showed that a ResNet-style stack, trained with ViT recipes (AdamW, Mixup, stochastic depth, large crops), matches hierarchical Transformers on ImageNet. &lt;a href=&quot;https://arxiv.org/abs/2301.00808&quot;&gt;ConvNeXt V2&lt;/a&gt; (2023) adds global response normalization (GRN) and a fully convolutional masked autoencoder pretraining stage.&lt;/p&gt;

&lt;p&gt;The message for this chapter: &lt;strong&gt;depthwise convolution + inverted bottlenecks&lt;/strong&gt; are still the inductive bias; the 2020s gap versus ViT was mostly &lt;em&gt;training&lt;/em&gt;, not “convolution is obsolete.”&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;vision-foundation-models-with-convolutional-dna&quot;&gt;Vision foundation models with convolutional DNA&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;DINOv2&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2304.07193&quot;&gt;Oquab et al., 2023&lt;/a&gt;) — self-supervised ViT features used as a drop-in backbone for retrieval, depth, and segmentation. ConvNeXt variants appear in the same benchmark tables.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SAM&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2304.02643&quot;&gt;Kirillov et al., 2023&lt;/a&gt;) and &lt;strong&gt;SAM 2&lt;/strong&gt; (&lt;a href=&quot;https://arxiv.org/abs/2408.00714&quot;&gt;Ravi et al., 2024&lt;/a&gt;) — promptable segmentation; the image encoder is a ViT, but production pipelines still pair it with convolutional detectors and lightweight CNN necks.&lt;/li&gt;
  &lt;li&gt;Medical imaging and remote sensing still prefer U-Net-style &lt;strong&gt;convolutional decoders&lt;/strong&gt; on top of whatever encoder won last year.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;when-a-cnn-is-still-the-right-default&quot;&gt;When a CNN is still the right default&lt;/h3&gt;

&lt;p&gt;High-resolution dense prediction, strict latency on mobile NPUs, and small-data regimes often keep EfficientNetV2 / ConvNeXt-Tiny / YOLO convolutional necks. Transformers win when you can pretrain at web scale.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/pytorch-image-models&quot;&gt;timm&lt;/a&gt; — ConvNeXt, EfficientNetV2, pretrained recipes.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/ultralytics/ultralytics&quot;&gt;Ultralytics YOLO&lt;/a&gt; — convolutional detectors (YOLOv8/v11) used in industry.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/facebookresearch/dinov2&quot;&gt;facebookresearch/dinov2&lt;/a&gt; and &lt;a href=&quot;https://github.com/facebookresearch/sam2&quot;&gt;facebookresearch/sam2&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2201.03545&quot;&gt;A ConvNet for the 2020s (Liu et al., 2022)&lt;/a&gt; — ConvNeXt.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2301.00808&quot;&gt;ConvNeXt V2 (Woo et al., 2023)&lt;/a&gt; — GRN + FCMAE pretraining.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.07193&quot;&gt;DINOv2 (Oquab et al., 2023)&lt;/a&gt; — web-scale self-supervised visual features.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2304.02643&quot;&gt;Segment Anything (Kirillov et al., 2023)&lt;/a&gt; — promptable segmentation foundation model.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Keep the convolution-dimension worksheets. This lesson only answers “what replaced VGG/ResNet &lt;em&gt;in practice&lt;/em&gt; after 2022”: modern ConvNets plus vision foundation models — not a new definition of a filter.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=QqejV0LNDHA&quot;&gt;ConvNeXt: A ConvNet for the 2020s – Paper Explained (with animations)&lt;/a&gt; — AI Coffee Break with Letitia, English. ConvNeXt is the conv net that borrowed transformer training, which is this note’s claim.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, English. The modern conv-net lecture those training tricks sit on top of.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=w1UsKanMatM&quot;&gt;Residual Networks (ResNet) [Physics Informed Machine Learning]&lt;/a&gt; — Steve Brunton, English. The residual block ConvNeXt did not throw away.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-98 Interviews Practice (CNNs and early features)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_98_Interviews_Practice</id>
   <content type="html">&lt;p&gt;In machine learning technical interviews, interviewers rarely ask you to recite PyTorch API signatures—they hand you a whiteboard marker and ask you to compute an output tensor shape, compare the parameter budget of two \(3 \times 3\) layers against a \(5 \times 5\) layer, or explain the precise distinction between translation &lt;em&gt;equivariance&lt;/em&gt; and translation &lt;em&gt;invariance&lt;/em&gt;. These rapid-fire derivations test whether you genuinely understand the geometry and optimization of CNNs under pressure.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-core-interview-competency-pillars-for-cnns&quot;&gt;Key ideas: Core Interview Competency Pillars for CNNs&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Exact Tensor &amp;amp; Parameter Arithmetic&lt;/strong&gt;: Fluency with \(H_{\text{out}} = \lfloor(H + 2p - d(k-1) - 1)/s\rfloor + 1\), parameter counts \(C_{\text{out}}(C_{\text{in}} k_H k_W + 1)\), and memory footprint calculations without reaching for a REPL.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Inductive Bias Vocabulary (Equivariance vs. Invariance)&lt;/strong&gt;: Precisely distinguishing \(f(T(x)) = T(f(x))\) (convolution is equivariant to translation) from \(f(T(x)) = f(x)\) (global pooling/classification aims for invariance), and knowing how striding and zero-padding subtly break exact equivariance.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Receptive Field &amp;amp; Factorization Trade-offs&lt;/strong&gt;: Articulating why stacked small kernels reduce parameters and increase non-linear expressive power while matching the receptive field of larger kernels.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Optimization &amp;amp; Gradient Diagnostics&lt;/strong&gt;: Explaining why identity shortcuts fix the degradation problem (not merely vanishing gradients) and how BatchNorm interacts with conv bias and train/eval modes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-whiteboard-speed-drill--two-3-times-3-convs-vs-one-5-times-5-conv&quot;&gt;Worked example: Whiteboard Speed-Drill — Two \(3 \times 3\) Convs vs. One \(5 \times 5\) Conv&lt;/h3&gt;

&lt;p&gt;An interviewer asks: &lt;em&gt;“Keeping input and output channels fixed at \(C = 128\), compare one \(5 \times 5\) conv against two stacked \(3 \times 3\) convs in receptive field, parameter count, and non-linearity.”&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Receptive field&lt;/strong&gt; (stride 1, dilation 1):
    &lt;ul&gt;
      &lt;li&gt;One \(5 \times 5\) conv: \(5 \times 5\).&lt;/li&gt;
      &lt;li&gt;Two \(3 \times 3\) convs: \(r_2 = 3 + (3 - 1)(1) = 5 \implies 5 \times 5\) (identical).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter count (weights only)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;One \(5 \times 5\) conv: \(25 C^2 = 25 \times 128^2 = 409{,}600\).&lt;/li&gt;
      &lt;li&gt;Two \(3 \times 3\) convs: \(2 \times 9 C^2 = 18 C^2 = 18 \times 128^2 = 294{,}912\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Reduction&lt;/strong&gt;: \((25 - 18)/25 = 28\%\) fewer weights (\(114{,}688\) saved).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Expressivity&lt;/strong&gt;: The stacked design inserts an extra ReLU activation between the two \(3 \times 3\) layers, allowing the \(5 \times 5\) neighborhood to compute a richer, piecewise-linear composition rather than a single linear projection.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-interview-practice--cnns-and-early-features&quot;&gt;Optional: interview practice — CNNs and early features&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; rewrite convolution math, pooling, or the LeNet–ResNet notes. After those lessons, use this drill, then open &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for solved items on convolution, CNN architectures, and early feature extraction.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Book themes for this chapter (study in the PDF, not here):&lt;/strong&gt; convolution geometry, CNN architectures, and the first half of the feature-extraction topic. Transfer-learning practice continues in &lt;strong&gt;15-98&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Hub: &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;practice-prompts-original&quot;&gt;Practice prompts (original)&lt;/h2&gt;

&lt;h3 id=&quot;q1-conv-vs-dense-parameter-count&quot;&gt;Q1. Conv vs dense parameter count&lt;/h3&gt;

&lt;p&gt;A layer maps a \(32\times32\times3\) tensor to \(32\times32\times16\) features. Compare (a) a dense layer that flattens the input and (b) a \(3\times3\) convolution with 16 output channels, same padding, bias included. Which number should you quote first in an interview?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Conv: \(k_h k_w c_{\mathrm{in}} c_{\mathrm{out}} + c_{\mathrm{out}}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Dense: input size \(32\cdot32\cdot3=3072\), output \(32\cdot32\cdot16=16384\), so about \(3072\cdot16384+16384\) weights — tens of millions. Conv: \(3\cdot3\cdot3\cdot16+16=448\). Quote the conv count first, then the &lt;em&gt;reason&lt;/em&gt;: local connectivity and weight sharing. Interviews fail people who only say “CNNs have fewer parameters” without a formula.&lt;/p&gt;

&lt;h3 id=&quot;q2-output-shape-by-hand&quot;&gt;Q2. Output shape by hand&lt;/h3&gt;

&lt;p&gt;Input \(H\times W=28\times28\), kernel \(5\times5\), stride \(s=1\), padding \(p=0\), \(c_{\mathrm{out}}=8\). What is the output tensor shape? What if \(s=2\) and \(p=2\)?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; \(H&apos;=\bigl\lfloor(H+2p-k)/s\bigr\rfloor+1\) (same for \(W\)).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; First case: \(H&apos;=28-5+1=24\), shape \(24\times24\times8\). Second: \((28+4-5)/2+1=14\), shape \(14\times14\times8\). Always state layout (channels-last vs channels-first) when you answer; frameworks disagree.&lt;/p&gt;

&lt;h3 id=&quot;q3-two-3times3-vs-one-5times5&quot;&gt;Q3. Two \(3\times3\) vs one \(5\times5\)&lt;/h3&gt;

&lt;p&gt;A stack of two \(3\times3\) convolutions (no pooling, stride 1, padding to keep size) and one \(5\times5\) convolution have the same theoretical receptive field on the input. Give one parameter-count reason and one expressivity reason to prefer the stack. Assume \(c\) channels throughout.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Receptive field adds \((k-1)\) per layer when stride is 1.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; One \(5\times5\): \(25c^2\) weights. Two \(3\times3\): \(18c^2\) weights, plus an extra nonlinearity in the middle, so the composed map is no longer a single linear filter. VGG-style stacks use exactly this argument. If the interviewer asks about depthwise-separable or \(1\times1\) bottlenecks, that is a follow-up, not a requirement for this chapter.&lt;/p&gt;

&lt;h3 id=&quot;q4-equivariance-vs-invariance&quot;&gt;Q4. Equivariance vs invariance&lt;/h3&gt;

&lt;p&gt;A vertical-edge filter is applied to an image, then the image is rolled two pixels to the right and the filter is applied again. What should change in the feature map if the implementation is a true convolution? What operation would you add if the &lt;em&gt;classifier&lt;/em&gt; must not care about that shift?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Convolution commutes with translation; global pooling throws spatial position away.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; The feature map should roll by the same two pixels (translation &lt;em&gt;equivariance&lt;/em&gt;). A final global average / max pool (or a sufficiently large downsample) makes the &lt;em&gt;vector&lt;/em&gt; fed to the linear head closer to translation &lt;em&gt;invariant&lt;/em&gt;. Mixing the two words is a common interview miss.&lt;/p&gt;

&lt;h3 id=&quot;q5-what-the-identity-skip-is-for&quot;&gt;Q5. What the identity skip is for&lt;/h3&gt;

&lt;p&gt;In a residual block \(\mathbf{y} = \mathbf{x} + \mathcal{F}(\mathbf{x})\), write \(\partial\mathbf{y}/\partial\mathbf{x}\) schematically. Why does this help a 50-layer CNN more than “just add more ReLUs”?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; The \(+1\) from the skip is the story; \(\mathcal{F}\) can be small at init.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; \(\frac{\partial\mathbf{y}}{\partial\mathbf{x}} = I + \frac{\partial\mathcal{F}}{\partial\mathbf{x}}\). The identity term keeps a path whose gain does not vanish when \(\mathcal{F}\) is near zero, so gradients can travel many blocks. Extra ReLUs without skips still multiply many Jacobian factors that can shrink. This is an architecture answer, not a “ResNet always wins on accuracy” claim.&lt;/p&gt;

&lt;h2 id=&quot;attribution&quot;&gt;Attribution&lt;/h2&gt;

&lt;p&gt;Kashani, S., and Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Download the PDF from arXiv for the full solved Q&amp;amp;A. This page is original course practice, not a reprint.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. Before the convolution-arithmetic prompts.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, English. Output-shape questions are answered by the formulas in this lecture.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, English. Use this if a prompt asks what a kernel is detecting, not how big the output is.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-02 Pooling Layers and CNN Architectures</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_02_Pooling_and_Architectures/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_02_Pooling_and_Architectures</id>
   <content type="html">&lt;p&gt;A single convolutional layer extracts local textures, but recognizing a whole scene requires coordinating spatial downsampling with multi-stage feature hierarchies. This section pairs &lt;strong&gt;pooling layers&lt;/strong&gt;—which compress resolution and introduce local invariance—with the &lt;strong&gt;classic CNN architectures&lt;/strong&gt; (LeNet, AlexNet, VGG, ResNet) that assembled convolution, pooling, normalization, and residual paths into complete vision systems.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-from-single-layers-to-full-vision-backbones&quot;&gt;Key ideas: From Single Layers to Full Vision Backbones&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Spatial Pyramids &amp;amp; Channel-Resolution Trade-off&lt;/strong&gt;: Classic CNNs follow a disciplined pyramid rule: whenever pooling (or strided conv) halves \(H\) and \(W\) (cutting spatial area by \(4\times\)), the next stage doubles the channel count \(C\), keeping per-layer FLOPs roughly constant across depth.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pooling Semantics (Max, Average, Global Average)&lt;/strong&gt;: Local pooling builds shift tolerance across early stages, while Global Average Pooling at the end converts arbitrary \((C, H, W)\) grids into compact \(C\)-dimensional semantic embeddings.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Macro-Architectural Motifs&lt;/strong&gt;: Understanding how LeNet, AlexNet, VGG, and ResNet wire pooling, bottlenecks, and skip connections equips you to read—and design—any modern vision backbone.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-why-doubling-channels-when-halving-resolution-keeps-flops-constant&quot;&gt;Worked example: Why Doubling Channels When Halving Resolution Keeps FLOPs Constant&lt;/h3&gt;

&lt;p&gt;Suppose Stage 1 of a CNN operates on feature maps of shape \((C, H, W) = (64, 56, 56)\) with a \(3 \times 3\) conv (\(64 \to 64\)), and Stage 2 follows a \(2 \times 2\) stride-2 pooling layer with \((128, 28, 28)\) and a \(3 \times 3\) conv (\(128 \to 128\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Stage 1 MACs&lt;/strong&gt;:
\(\text{MACs}_1 = H_1 \cdot W_1 \cdot C_1^2 \cdot k^2 = 56 \times 56 \times 64^2 \times 9 = 3{,}136 \times 4{,}096 \times 9 = 115{,}605{,}504.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stage 2 MACs&lt;/strong&gt; (\(H_2 = H_1/2, W_2 = W_1/2, C_2 = 2 C_1\)):
\(\text{MACs}_2 = 28 \times 28 \times 128^2 \times 9 = 784 \times 16{,}384 \times 9 = 115{,}605{,}504.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact Ratio&lt;/strong&gt;:
\(\frac{\text{MACs}_2}{\text{MACs}_1} = \frac{(H/2)(W/2)(2C)^2}{H W C^2} = \frac{\frac{1}{4} \cdot 4}{1} = 1.00!\)
That exact algebraic cancellation is the hidden organizing law behind VGG, ResNet, and nearly every hierarchical vision backbone.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This section completes the CNN toolkit: &lt;strong&gt;pooling&lt;/strong&gt; for spatial downsampling, and &lt;strong&gt;classic architectures&lt;/strong&gt; that show how convolutions and pooling are composed in practice.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Pooling Layers&lt;/strong&gt; — max/average/global pooling, math, and implementations&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Classic CNN Architectures&lt;/strong&gt; — LeNet, AlexNet, VGG, ResNet, papers, and key takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Read the pooling lesson first, then the architecture survey.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=ZjM_XQa5s6s&quot;&gt;Max Pooling in Convolutional Neural Networks explained&lt;/a&gt; — deeplizard, English. Max pooling is the downsampling half of this block.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 9&lt;/td&gt;
          &lt;td&gt;CNN Architectures](https://www.youtube.com/watch?v=DAOcjicFr1Y) — Stanford University School of Engineering, English. The architecture half: LeNet through ResNet.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=w1UsKanMatM&quot;&gt;Residual Networks (ResNet) [Physics Informed Machine Learning]&lt;/a&gt; — Steve Brunton, English. ResNet’s skip connection, the last architecture the block reaches.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-02-02 Classic CNN Architectures</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_02_02_Classic_CNN_Architectures/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_02_02_Classic_CNN_Architectures</id>
   <content type="html">&lt;p&gt;Reading the history of CNN architectures from 1998 to 2015 is like watching aviation evolve from the Wright Flyer to a commercial jetliner in under two decades. Each landmark paper—LeNet-5, AlexNet, VGGNet, and ResNet—did not merely add more layers; each diagnosed a concrete mathematical bottleneck (saturating activations, bloated FC heads, oversized kernels, or optimization degradation) and invented a reusable architectural principle that still shapes Vision Transformers and ConvNeXt today.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-evolutionary-arc-of-landmark-cnns&quot;&gt;Key ideas: The Evolutionary Arc of Landmark CNNs&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;LeNet-5 (1998)&lt;/strong&gt;: Established the canonical &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv -&amp;gt; Pool -&amp;gt; Conv -&amp;gt; Pool -&amp;gt; FC&lt;/code&gt; blueprint and proved end-to-end backpropagation on raw pixels could beat hand-crafted digit features.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;AlexNet (2012)&lt;/strong&gt;: Proved GPU-accelerated deep CNNs with ReLU, Dropout, and data augmentation could scale to million-image datasets (ImageNet).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;VGGNet (2014)&lt;/strong&gt;: Replaced heterogeneous kernel sizes with clean, modular stacks of \(3 \times 3\) filters, proving depth and architectural regularity drive representation power.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ResNet (2015)&lt;/strong&gt;: Introduced identity skip connections (\(x + F(x)\)) and \(1\times 1\) bottlenecks, solving deep optimization degradation and enabling 50–152+ layer networks.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-efficiency-leap-across-four-generations&quot;&gt;Worked example: Efficiency Leap Across Four Generations&lt;/h3&gt;

&lt;p&gt;Compare how efficiently each landmark architecture turns parameters into ImageNet accuracy (approximate canonical published figures):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Parameter count comparison&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;AlexNet (8 layers)&lt;/strong&gt;: \(\approx 61.1\text{M}\) parameters (~\(96\%\) in FC layers).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;VGG-16 (16 layers)&lt;/strong&gt;: \(\approx 138.4\text{M}\) parameters (~\(89\%\) in FC layers: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;25088 x 4096&lt;/code&gt; alone is \(102.8\text{M}\)!).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;ResNet-50 (50 layers)&lt;/strong&gt;: \(\approx 25.6\text{M}\) parameters (Global Average Pooling reduces the classifier head to just &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2048 x 1000 = 2.05M&lt;/code&gt;).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter ratio&lt;/strong&gt;:
\(\frac{P_{\text{VGG-16}}}{P_{\text{ResNet-50}}} = \frac{138.4\text{M}}{25.6\text{M}} \approx 5.4\times \text{ fewer parameters for ResNet-50}\)
despite being more than \(3\times\) deeper and achieving substantially higher top-1 accuracy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Design Rule&lt;/strong&gt;: Depth + residual connections + Global Average Pooling beats shallow width + dense classification heads on both memory and generalization.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Classic CNN architectures:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;LeNet and AlexNet&lt;/strong&gt; — early pioneers of modern computer vision&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;VGG, ResNet, and Architecture Evolution&lt;/strong&gt; — depth, skip connections, papers, takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 9&lt;/td&gt;
          &lt;td&gt;CNN Architectures](https://www.youtube.com/watch?v=DAOcjicFr1Y) — Stanford University School of Engineering, English. One lecture that lines LeNet, AlexNet, VGG, and ResNet up.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 1&lt;/td&gt;
          &lt;td&gt;Introduction to Convolutional Neural Networks for Visual Recognition](https://www.youtube.com/watch?v=vT1JzLTH4G4) — Stanford University School of Engineering, English. The historical motivation: why ImageNet forced architectures to change.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=w1UsKanMatM&quot;&gt;Residual Networks (ResNet) [Physics Informed Machine Learning]&lt;/a&gt; — Steve Brunton, English. The residual step that ends the sequence.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-02-02-02 VGG, ResNet, and Architecture Evolution</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_02_02_02_VGG_ResNet_and_Evolution/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_02_02_02_VGG_ResNet_and_Evolution</id>
   <content type="html">&lt;p&gt;After AlexNet’s 2012 breakthrough, vision researchers asked an obvious question: if 8 layers beat hand-crafted features, what happens at 16, 20, or 100 layers? VGG (2014) showed that replacing bulky \(7 \times 7\) and \(11 \times 11\) filters with uniform stacks of \(3 \times 3\) convolutions dramatically improved accuracy—yet when researchers pushed plain VGG-style networks past 20 layers, something shocking happened: &lt;strong&gt;even training error got worse&lt;/strong&gt;. A 56-layer plain network could not even match a 20-layer network on the training set, despite strictly containing the 20-layer solution space. ResNet (2015) solved this “degradation problem” with one deceptively simple line of algebra—\(y = F(x) + x\)—unlocking networks hundreds of layers deep.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-depth-factorization-and-residual-gradient-flow&quot;&gt;Key ideas: Depth, Factorization, and Residual Gradient Flow&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Filter Factorization (VGG Principle)&lt;/strong&gt;: Stacking two \(3 \times 3\) convolutions achieves the exact \(5 \times 5\) receptive field of a single \(5 \times 5\) layer—and three \(3 \times 3\) layers match a \(7 \times 7\) receptive field—while cutting parameters and inserting extra ReLU non-linearities between layers.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Degradation Problem vs. Overfitting&lt;/strong&gt;: Overfitting produces low training error and high test error; degradation produces &lt;em&gt;high training error&lt;/em&gt; in deeper plain networks because SGD struggles to approximate the identity map through stacked non-linear layers.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Residual Learning &amp;amp; Identity Shortcuts&lt;/strong&gt;: Reparameterizing a block to learn the &lt;em&gt;residual&lt;/em&gt; \(F(x) = H(x) - x\) makes the identity map trivial—the optimizer simply drives weights toward zero. During backpropagation, the gradient splits into \(\frac{\partial \mathcal{L}}{\partial x_\ell} = \frac{\partial \mathcal{L}}{\partial x_L}\left(1 + \frac{\partial}{\partial x_\ell}\sum_{i=\ell}^{L-1} F(x_i)\right)\), creating an unimpeded gradient highway directly to early layers.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bottleneck Design &amp;amp; Macro-Architecture Evolution&lt;/strong&gt;: Pairing \(1 \times 1 \to 3 \times 3 \to 1 \times 1\) bottlenecks with Global Average Pooling enabled ResNet-50 (25.6M parameters) to crush VGG-16 (138M parameters) with less than one-fifth the weights.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-receptive-field--parameter-proof-three-3-times-3-vs-one-7-times-7&quot;&gt;Worked example: Receptive Field &amp;amp; Parameter Proof (Three \(3 \times 3\) vs. One \(7 \times 7\))&lt;/h3&gt;

&lt;p&gt;Assume input and output feature maps both have \(C\) channels, with stride \(s = 1\) and same-padding.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Receptive field equivalence&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;One \(7 \times 7\) conv: \(r = 7\).&lt;/li&gt;
      &lt;li&gt;Three stacked \(3 \times 3\) convs (all \(s = 1\)):
\(r_1 = 3, \quad r_2 = 3 + (3 - 1)(1) = 5, \quad r_3 = 5 + (3 - 1)(1) = 7.\)
Both see the exact same \(7 \times 7\) spatial window.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter comparison (excluding biases)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Single \(7 \times 7\) conv:
\(P_{7\times 7} = 7 \times 7 \times C^2 = 49 C^2.\)&lt;/li&gt;
      &lt;li&gt;Three \(3 \times 3\) convs:
\(P_{3\times(3\times 3)} = 3 \times (3 \times 3 \times C^2) = 27 C^2.\)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Savings&lt;/strong&gt;: \((49 - 27)/49 = 22/49 \approx 44.9\%\) fewer parameters (for \(C = 256\), that is \(1.77\text{M}\) vs. \(3.21\text{M}\) weights!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Residual gradient check (1D scalar illustration)&lt;/strong&gt;:
Suppose 10 plain layers each have local derivative \(0.5\): the gradient shrinks by \(0.5^{10} \approx 0.00098\). Now add a skip connection so each block computes \(x_{k+1} = x_k + F_k(x_k)\) with \(F_k&apos;(x_k) = -0.5\) or \(+0.2\): even if \(F_k&apos;(x_k) \approx 0\), the derivative factor is \((1 + 0)^{10} = 1.0\)—zero vanishing!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;vggnet-2014--simplicity-and-depth&quot;&gt;VGGNet (2014) — Simplicity and Depth&lt;/h3&gt;

&lt;p&gt;VGG by Simonyan and Zisserman showed that &lt;strong&gt;depth matters&lt;/strong&gt; and &lt;strong&gt;simple is better&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key insight&lt;/strong&gt;: Use only 3×3 convolutions stacked deeply.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;VGG-16 Architecture&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (224×224×3)

Block 1: Conv3-64, Conv3-64, MaxPool → 112×112×64
Block 2: Conv3-128, Conv3-128, MaxPool → 56×56×128
Block 3: Conv3-256, Conv3-256, Conv3-256, MaxPool → 28×28×256
Block 4: Conv3-512, Conv3-512, Conv3-512, MaxPool → 14×14×512
Block 5: Conv3-512, Conv3-512, Conv3-512, MaxPool → 7×7×512

Flatten → FC 4096 → FC 4096 → FC 1000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Why 3×3 is optimal&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Two 3×3 convs = one 5×5 receptive field, but:
    &lt;ul&gt;
      &lt;li&gt;Fewer parameters: 2×(3×3) = 18 vs 5×5 = 25&lt;/li&gt;
      &lt;li&gt;More non-linearity: 2 ReLUs vs 1&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;Three 3×3 convs = one 7×7 receptive field&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;~138 million parameters&lt;/strong&gt; (mostly in FC layers)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VGG16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;VGG-16 architecture&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Block 1
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Block 2
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Block 3
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Block 4
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Block 5
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;resnet-2015--the-skip-connection-revolution&quot;&gt;ResNet (2015) — The Skip Connection Revolution&lt;/h3&gt;

&lt;p&gt;ResNet by He et al. solved the &lt;strong&gt;degradation problem&lt;/strong&gt;: deeper networks had &lt;em&gt;higher&lt;/em&gt; training error than shallow ones. This was counterintuitive—more capacity should help, not hurt.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The problem&lt;/strong&gt;: In very deep networks, gradients either vanish or explode, making optimization difficult. Even with careful initialization and batch normalization, networks deeper than ~20 layers trained poorly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The solution&lt;/strong&gt;: &lt;strong&gt;Residual connections&lt;/strong&gt; (skip connections)&lt;/p&gt;

&lt;p&gt;Instead of learning \(H(x)\) directly, learn the residual \(F(x) = H(x) - x\), then:&lt;/p&gt;

\[\mathbf{y} = F(\mathbf{x}) + \mathbf{x}\]

&lt;p&gt;&lt;strong&gt;Why it works&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Identity mapping is easy&lt;/strong&gt;: If identity is optimal, just set \(F(x) = 0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient highway&lt;/strong&gt;: Gradients flow directly through skip connections&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ensemble effect&lt;/strong&gt;: ResNet behaves like an ensemble of shallower networks&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Basic Residual Block&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;         ┌────────────────────────────────────┐
         │               Identity             │
         │                                    │
    x ───┼──→ Conv 3×3 → BN → ReLU           │
         │        ↓                           │
         │   Conv 3×3 → BN                    │
         │        ↓                           │
         └───────⊕───→ ReLU → output
              (add)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Bottleneck Block&lt;/strong&gt; (for deeper networks like ResNet-50+):&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;         ┌──────────────────────────────────┐
         │             Identity             │
         │                                  │
    x ───┼──→ Conv 1×1 → BN → ReLU (reduce)│
         │        ↓                         │
         │   Conv 3×3 → BN → ReLU           │
         │        ↓                         │
         │   Conv 1×1 → BN (expand)         │
         │        ↓                         │
         └───────⊕───→ ReLU → output
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;BasicBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Basic residual block for ResNet-18/34&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                               &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# For matching dimensions
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Handle dimension mismatch
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;downsample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# The key: skip connection!
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Bottleneck&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Bottleneck block for ResNet-50/101/152&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# 1×1 reduce
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# 3×3 conv
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# 1×1 expand
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                               &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;downsample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ResNet implementation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initial conv layer
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                               &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;maxpool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Residual layers
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_make_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_make_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_make_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer4&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;_make_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Global average pooling + classifier
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avgpool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AdaptiveAvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;_make_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blocks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;or&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                         &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;downsample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expansion&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;blocks&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maxpool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;layer1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;layer2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;layer3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;layer4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;avgpool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Create standard ResNet variants
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;BasicBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Bottleneck&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet101&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Bottleneck&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;23&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== MODEL COMPARISON ==============
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;CNN Architecture Comparison&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;models&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;LeNet-5&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LeNet5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;VGG-16&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;VGG16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ResNet-18&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ResNet-50&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;resnet50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;models&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;15&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; parameters&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;architecture-evolution-summary&quot;&gt;Architecture Evolution Summary&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Model&lt;/th&gt;
      &lt;th&gt;Year&lt;/th&gt;
      &lt;th&gt;Depth&lt;/th&gt;
      &lt;th&gt;Params&lt;/th&gt;
      &lt;th&gt;Top-5 Error&lt;/th&gt;
      &lt;th&gt;Key Innovation&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;LeNet-5&lt;/td&gt;
      &lt;td&gt;1998&lt;/td&gt;
      &lt;td&gt;5&lt;/td&gt;
      &lt;td&gt;60K&lt;/td&gt;
      &lt;td&gt;-&lt;/td&gt;
      &lt;td&gt;First successful CNN&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;AlexNet&lt;/td&gt;
      &lt;td&gt;2012&lt;/td&gt;
      &lt;td&gt;8&lt;/td&gt;
      &lt;td&gt;60M&lt;/td&gt;
      &lt;td&gt;15.3%&lt;/td&gt;
      &lt;td&gt;ReLU, Dropout, GPU&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;VGG-16&lt;/td&gt;
      &lt;td&gt;2014&lt;/td&gt;
      &lt;td&gt;16&lt;/td&gt;
      &lt;td&gt;138M&lt;/td&gt;
      &lt;td&gt;7.3%&lt;/td&gt;
      &lt;td&gt;3×3 only, depth&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;GoogLeNet&lt;/td&gt;
      &lt;td&gt;2014&lt;/td&gt;
      &lt;td&gt;22&lt;/td&gt;
      &lt;td&gt;6.8M&lt;/td&gt;
      &lt;td&gt;6.7%&lt;/td&gt;
      &lt;td&gt;Inception modules&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ResNet-50&lt;/td&gt;
      &lt;td&gt;2015&lt;/td&gt;
      &lt;td&gt;50&lt;/td&gt;
      &lt;td&gt;25M&lt;/td&gt;
      &lt;td&gt;3.6%&lt;/td&gt;
      &lt;td&gt;Skip connections&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ResNet-152&lt;/td&gt;
      &lt;td&gt;2015&lt;/td&gt;
      &lt;td&gt;152&lt;/td&gt;
      &lt;td&gt;60M&lt;/td&gt;
      &lt;td&gt;3.0%&lt;/td&gt;
      &lt;td&gt;Very deep&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;DenseNet&lt;/td&gt;
      &lt;td&gt;2017&lt;/td&gt;
      &lt;td&gt;121&lt;/td&gt;
      &lt;td&gt;8M&lt;/td&gt;
      &lt;td&gt;4.2%&lt;/td&gt;
      &lt;td&gt;Dense connections&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;EfficientNet&lt;/td&gt;
      &lt;td&gt;2019&lt;/td&gt;
      &lt;td&gt;-&lt;/td&gt;
      &lt;td&gt;5.3M&lt;/td&gt;
      &lt;td&gt;2.9%&lt;/td&gt;
      &lt;td&gt;Neural architecture search&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;5-fundamental-papers&quot;&gt;5. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf&quot;&gt;“Gradient-Based Learning Applied to Document Recognition” (1998)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Yann LeCun, Léon Bottou, Yoshua Bengio, Patrick Haffner&lt;br /&gt;
Introduced LeNet-5, establishing the conv-pool-conv-pool pattern that became the blueprint for CNNs. Demonstrated end-to-end gradient-based learning on raw pixels, proving that hand-crafted features were unnecessary for image recognition.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1312.4400&quot;&gt;“Network In Network” (2014)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Min Lin, Qiang Chen, Shuicheng Yan&lt;br /&gt;
Introduced 1×1 convolutions for cross-channel pooling and Global Average Pooling (GAP) to replace fully connected layers. These innovations dramatically reduced parameters and became standard in all subsequent architectures.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.1556&quot;&gt;“Very Deep Convolutional Networks for Large-Scale Image Recognition” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Karen Simonyan, Andrew Zisserman&lt;br /&gt;
VGGNet proved that depth with small 3×3 filters outperforms shallow networks with large filters. The simple, repeating architecture became a reference design and is still widely used for transfer learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.03385&quot;&gt;“Deep Residual Learning for Image Recognition” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun&lt;br /&gt;
ResNet’s skip connections solved the degradation problem, enabling training of networks with 100+ layers. Won ImageNet 2015 with 3.57% top-5 error (surpassing human performance). The residual learning framework is now used in transformers, diffusion models, and nearly all deep architectures.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1608.06993&quot;&gt;“Densely Connected Convolutional Networks” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Gao Huang, Zhuang Liu, Laurens van der Maaten, Kilian Q. Weinberger&lt;br /&gt;
DenseNet connects each layer to every other layer, enabling feature reuse and strong gradient flow. Achieved state-of-the-art accuracy with fewer parameters by maximizing information flow through the network.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1905.11946&quot;&gt;“EfficientNet: Rethinking Model Scaling” (2019)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Mingxing Tan, Quoc V. Le&lt;br /&gt;
Used neural architecture search to find efficient baseline architectures, then proposed compound scaling (depth × width × resolution) for systematic scaling. Achieved state-of-the-art accuracy with dramatically fewer parameters and FLOPs.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-key-takeaways&quot;&gt;6. Key Takeaways&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Pooling reduces dimensions&lt;/strong&gt; while preserving important features. Max pooling works best for classification; average pooling for other tasks.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Global Average Pooling&lt;/strong&gt; replaces heavy FC layers, reducing parameters by ~40× while improving generalization.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Architecture evolution&lt;/strong&gt;: LeNet (simple) → AlexNet (scale) → VGG (depth) → ResNet (skip connections) → EfficientNet (efficiency)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;3×3 convolutions are optimal&lt;/strong&gt;: Stack multiple small filters instead of using large ones.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Skip connections are essential&lt;/strong&gt; for training deep networks. They appear in ResNet, DenseNet, U-Net, Transformers, and diffusion models.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Modern best practices&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Conv → BatchNorm → ReLU&lt;/li&gt;
      &lt;li&gt;Skip connections every 2-3 layers&lt;/li&gt;
      &lt;li&gt;Global Average Pooling instead of Flatten + FC&lt;/li&gt;
      &lt;li&gt;Strided convolution for learnable downsampling&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pre-trained models&lt;/strong&gt; (transfer learning) are the standard starting point for most vision tasks. ImageNet pre-training transfers remarkably well to other domains.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Next chapter&lt;/strong&gt;: Recurrent Neural Networks for sequential data!&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=w1UsKanMatM&quot;&gt;Residual Networks (ResNet) [Physics Informed Machine Learning]&lt;/a&gt; — Steve Brunton, English. A residual block is the VGG-style stack plus a skip, which is this lesson’s turning point.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=RYth6EbBUqM&quot;&gt;C4W2L04 Why ResNets Work&lt;/a&gt; — DeepLearningAI, English. Why that skip lets depth increase without the training collapse the lesson describes.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 9&lt;/td&gt;
          &lt;td&gt;CNN Architectures](https://www.youtube.com/watch?v=DAOcjicFr1Y) — Stanford University School of Engineering, English. The lineup from VGG to ResNet so the evolution section has a single timeline.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-02-02-01 LeNet and AlexNet</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_02_02_01_LeNet_AlexNet/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_02_02_01_LeNet_AlexNet</id>
   <content type="html">&lt;p&gt;For nearly fourteen years after Yann LeCun’s LeNet-5 began reading millions of bank checks across the United States in 1998, convolutional networks sat largely on the margins of computer vision while hand-crafted SIFT features and support vector machines dominated benchmarks. Then, in September 2012, Alex Krizhevsky, Ilya Sutskever, and Geoffrey Hinton submitted &lt;strong&gt;AlexNet&lt;/strong&gt; to ImageNet and shattered the top-5 error rate from \(26.2\%\) down to \(15.3\%\)—a gap so wide that the entire field pivoted overnight. Comparing LeNet-5 and AlexNet side by side reveals the exact architectural, mathematical, and hardware ingredients that turned a niche digit recognizer into the deep learning revolution.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-from-lenet-5-1998-to-alexnet-2012&quot;&gt;Key ideas: From LeNet-5 (1998) to AlexNet (2012)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Activation Functions &amp;amp; Optimization Speed (Sigmoid/Tanh vs. ReLU)&lt;/strong&gt;: LeNet-5 relied on saturating &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;tanh&lt;/code&gt;/sigmoid activations whose derivatives vanish for large magnitudes. AlexNet popularized non-saturating &lt;strong&gt;ReLU&lt;/strong&gt; (\(\max(0, x)\)), cutting training time on deep networks by roughly \(6\times\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scale of Data, Compute, and Parallelism&lt;/strong&gt;: LeNet-5 had ~60K parameters trained on \(32 \times 32\) grayscale MNIST digits on a CPU. AlexNet scaled to ~61M parameters trained on 1.2M \(224 \times 224\) RGB ImageNet images across two NVIDIA GTX 580 GPUs (3 GB VRAM each) using grouped convolutions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Regularization for Over-Parameterized Heads&lt;/strong&gt;: AlexNet’s massive fully connected layers (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;9216 -&amp;gt; 4096 -&amp;gt; 4096 -&amp;gt; 1000&lt;/code&gt;) contained over \(95\%\) of its parameters. Without &lt;strong&gt;Dropout&lt;/strong&gt; (\(p = 0.5\)) and aggressive image data augmentation (random crops, horizontal flips, PCA color jitter), the model would have severely memorized ImageNet.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Overlapping Max Pooling&lt;/strong&gt;: Moving from LeNet’s non-overlapping \(2 \times 2\) average pooling to AlexNet’s overlapping \(3 \times 3\) max pooling with stride \(2\) preserved sharper discriminative features and modestly reduced overfitting.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-where-do-alexnets-61-million-parameters-actually-live&quot;&gt;Worked example: Where Do AlexNet’s 61 Million Parameters Actually Live?&lt;/h3&gt;

&lt;p&gt;Let us audit the parameter concentration in AlexNet’s first convolutional layer versus its first fully connected layer (using standard \(224 \times 224 \times 3\) input padded to \(227 \times 227 \times 3\)):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Conv1 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;11x11&lt;/code&gt;, stride &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;3 -&amp;gt; 96&lt;/code&gt; filters)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Spatial output: \(\lfloor (227 - 11)/4 \rfloor + 1 = 55 \implies (96, 55, 55)\).&lt;/li&gt;
      &lt;li&gt;Parameters: \(96 \times (3 \times 11 \times 11 + 1) = 96 \times 364 = 34{,}944\) (\(\approx 0.035\text{M}\)).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;FC1 (after Conv5 + MaxPool produces &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;256 x 6 x 6 = 9,216&lt;/code&gt; features \(\to 4{,}096\) neurons)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Parameters: \(9{,}216 \times 4{,}096 + 4{,}096 = 37{,}748{,}736 + 4{,}096 = 37{,}752{,}832\) (\(\approx 37.75\text{M}\)).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare FC1 against ALL five convolutional layers combined&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;All five Conv layers combined in AlexNet total only \(\approx 2.33\text{M}\) parameters (~\(3.8\%\) of the model).&lt;/li&gt;
      &lt;li&gt;FC1 &lt;strong&gt;alone&lt;/strong&gt; accounts for \(37.75 / 61.1 \approx 61.8\%\) of the entire network’s weights!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Architectural Lesson&lt;/strong&gt;: This exact bottleneck explains why later architectures (GoogLeNet, ResNet) replaced giant flattened FC layers with &lt;strong&gt;Global Average Pooling&lt;/strong&gt;, reclaiming tens of millions of parameters while &lt;em&gt;improving&lt;/em&gt; generalization.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-classic-cnn-architectures&quot;&gt;4. Classic CNN Architectures&lt;/h2&gt;

&lt;p&gt;The evolution of CNN architectures is a fascinating journey of increasing depth, efficiency, and clever design choices. Let’s trace this evolution in detail.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv.jpg&quot; alt=&quot;CNN&quot; /&gt;
&lt;em&gt;Overview of Convolutional Neural Network (CNN) architecture. Source: AnalyticsVidhya&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv6.jpg&quot; alt=&quot;CNN&quot; /&gt;
&lt;em&gt;Overview of Convolutional Neural Network (CNN) architecture. Source: AnalyticsVidhya&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;lenet-5-1998--the-pioneer&quot;&gt;LeNet-5 (1998) — The Pioneer&lt;/h3&gt;

&lt;p&gt;LeNet-5 by Yann LeCun was the first successful CNN, designed for handwritten digit recognition.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Architecture&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (32×32×1)
    ↓
Conv1: 6 filters, 5×5, stride 1 → 28×28×6
    ↓
AvgPool: 2×2, stride 2 → 14×14×6
    ↓
Conv2: 16 filters, 5×5, stride 1 → 10×10×16
    ↓
AvgPool: 2×2, stride 2 → 5×5×16
    ↓
Flatten → 400
    ↓
FC1: 400 → 120
    ↓
FC2: 120 → 84
    ↓
Output: 84 → 10
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Key characteristics&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;~60,000 parameters&lt;/li&gt;
  &lt;li&gt;Tanh/sigmoid activations (ReLU didn’t exist yet)&lt;/li&gt;
  &lt;li&gt;Average pooling (max pooling came later)&lt;/li&gt;
  &lt;li&gt;Trained on MNIST (10 classes, 28×28 images)&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LeNet5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;LeNet-5 architecture (modernized with ReLU)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;       &lt;span class=&quot;c1&quot;&gt;# 32→28
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;                   &lt;span class=&quot;c1&quot;&gt;# 28→14
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;     &lt;span class=&quot;c1&quot;&gt;# 14→10
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;                   &lt;span class=&quot;c1&quot;&gt;# 10→5
&lt;/span&gt;        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;120&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;120&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;84&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;84&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;alexnet-2012--the-deep-learning-breakthrough&quot;&gt;AlexNet (2012) — The Deep Learning Breakthrough&lt;/h3&gt;

&lt;p&gt;AlexNet by Krizhevsky, Sutskever, and Hinton won ImageNet 2012 dramatically and launched the deep learning revolution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Architecture&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (227×227×3)
    ↓
Conv1: 96 filters, 11×11, stride 4 → 55×55×96
    ↓
MaxPool: 3×3, stride 2 → 27×27×96
    ↓
Conv2: 256 filters, 5×5, pad 2 → 27×27×256
    ↓
MaxPool: 3×3, stride 2 → 13×13×256
    ↓
Conv3: 384 filters, 3×3, pad 1 → 13×13×384
    ↓
Conv4: 384 filters, 3×3, pad 1 → 13×13×384
    ↓
Conv5: 256 filters, 3×3, pad 1 → 13×13×256
    ↓
MaxPool: 3×3, stride 2 → 6×6×256
    ↓
Flatten → 9216
    ↓
FC1: 9216 → 4096 (+ Dropout 0.5)
    ↓
FC2: 4096 → 4096 (+ Dropout 0.5)
    ↓
Output: 4096 → 1000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Revolutionary contributions&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;ReLU activation&lt;/strong&gt;: Faster training than tanh/sigmoid&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dropout&lt;/strong&gt;: Regularization to prevent overfitting&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Data augmentation&lt;/strong&gt;: Random crops, flips, color jittering&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;GPU training&lt;/strong&gt;: Split across 2 GPUs (3GB each at the time)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Local Response Normalization&lt;/strong&gt;: Lateral inhibition (later replaced by BatchNorm)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;~60 million parameters&lt;/strong&gt; — massive for its time!&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;AlexNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Simplified AlexNet&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;96&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;96&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;384&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;384&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;384&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;384&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4096&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;256&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 9&lt;/td&gt;
          &lt;td&gt;CNN Architectures](https://www.youtube.com/watch?v=DAOcjicFr1Y) — Stanford University School of Engineering, English. Stay with the LeNet and AlexNet portions: stacked conv, pool, then a classifier.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 1&lt;/td&gt;
          &lt;td&gt;Introduction to Convolutional Neural Networks for Visual Recognition](https://www.youtube.com/watch?v=vT1JzLTH4G4) — Stanford University School of Engineering, English. Why AlexNet’s scale was the break with LeNet-sized models.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. The layer types those two nets are made of, without the later residual machinery.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-02-01 Pooling Layers</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_02_01_Pooling_Layers/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_02_01_Pooling_Layers</id>
   <content type="html">&lt;p&gt;Convolutional layers are &lt;em&gt;translation equivariant&lt;/em&gt;: if an object shifts one pixel to the right, its feature activation shifts one pixel to the right as well. Yet for image classification, we ultimately want &lt;em&gt;translation invariance&lt;/em&gt;—a cat shifted by two pixels should still produce the same class probability—while progressively shrinking spatial resolution so deeper layers can afford more channels and wider receptive fields. Pooling layers deliver this spatial compression with zero learnable parameters, acting as fixed local summaries that trade exact pixel coordinates for robustness and computational speed.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-spatial-subsampling-and-invariance-mechanics&quot;&gt;Key ideas: Spatial Subsampling and Invariance Mechanics&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Local Translation Invariance via Order Statistics (Max Pooling)&lt;/strong&gt;: Taking the maximum over a \(2 \times 2\) window outputs the strongest feature response regardless of which of the four sub-pixels triggered it, introducing micro-scale shift invariance while preserving sharp, high-contrast activations.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Low-Pass Smoothing &amp;amp; Signal Preservation (Average Pooling)&lt;/strong&gt;: Averaging over a window acts as a box low-pass filter, retaining background energy and smooth gradients everywhere in the patch—ideal when overall presence matters more than peak intensity.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Global Average Pooling (GAP) as Structural Regularization&lt;/strong&gt;: Replacing massive dense classification heads (like VGG’s 100M-parameter FC layers) with a spatial mean per channel \((C, H, W) \to (C,)\) eliminates millions of overfitting-prone weights and lets CNNs accept variable input resolutions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Backward Gradient Routing&lt;/strong&gt;: Max pooling routes the entire upstream gradient exclusively to the single winning argmax index (zeroing all other entries), whereas average pooling divides the gradient equally by \(k^2\) across every pixel in the window.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-forward--backward-pass-of-2-times-2-max-vs-average-pooling&quot;&gt;Worked example: Forward &amp;amp; Backward Pass of \(2 \times 2\) Max vs. Average Pooling&lt;/h3&gt;

&lt;p&gt;Consider a \(4 \times 4\) single-channel feature map \(X\) pooled with kernel \(k = 2\), stride \(s = 2\):
\(X = \begin{bmatrix} 1 &amp;amp; 3 &amp;amp; 2 &amp;amp; 0 \\ 4 &amp;amp; 2 &amp;amp; 1 &amp;amp; 5 \\ 0 &amp;amp; 1 &amp;amp; 3 &amp;amp; 2 \\ 2 &amp;amp; 0 &amp;amp; 1 &amp;amp; 4 \end{bmatrix}.\)
Suppose the upstream loss sends gradient \(G = \frac{\partial \mathcal{L}}{\partial Y} = \begin{bmatrix} 10 &amp;amp; -4 \\ 8 &amp;amp; 12 \end{bmatrix}\) back into the \(2 \times 2\) pooled output \(Y\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Max Pooling forward pass&lt;/strong&gt; (taking the max of each non-overlapping \(2 \times 2\) quadrant):
    &lt;ul&gt;
      &lt;li&gt;Top-left &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1, 3; 4, 2]&lt;/code&gt; \(\to 4\) (at index &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(1, 0)&lt;/code&gt;).&lt;/li&gt;
      &lt;li&gt;Top-right &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[2, 0; 1, 5]&lt;/code&gt; \(\to 5\) (at index &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(1, 3)&lt;/code&gt;).&lt;/li&gt;
      &lt;li&gt;Bottom-left &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0, 1; 2, 0]&lt;/code&gt; \(\to 2\) (at index &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(3, 0)&lt;/code&gt;).&lt;/li&gt;
      &lt;li&gt;Bottom-right &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[3, 2; 1, 4]&lt;/code&gt; \(\to 4\) (at index &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(3, 3)&lt;/code&gt;).
\(Y_{\max} = \begin{bmatrix} 4 &amp;amp; 5 \\ 2 &amp;amp; 4 \end{bmatrix}.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Max Pooling backward pass&lt;/strong&gt; (gradient flows &lt;em&gt;only&lt;/em&gt; to each quadrant’s argmax):
\(\frac{\partial \mathcal{L}}{\partial X}\Big|_{\max} = \begin{bmatrix} 0 &amp;amp; 0 &amp;amp; 0 &amp;amp; 0 \\ 10 &amp;amp; 0 &amp;amp; 0 &amp;amp; -4 \\ 0 &amp;amp; 0 &amp;amp; 0 &amp;amp; 0 \\ 8 &amp;amp; 0 &amp;amp; 0 &amp;amp; 12 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Average Pooling forward &amp;amp; backward pass&lt;/strong&gt; (each quadrant averaged, gradient split by \(1/4\)):
\(Y_{\text{avg}} = \begin{bmatrix} 2.5 &amp;amp; 2.0 \\ 0.75 &amp;amp; 2.5 \end{bmatrix}, \quad \frac{\partial \mathcal{L}}{\partial X}\Big|_{\text{avg}} = \begin{bmatrix} 2.5 &amp;amp; 2.5 &amp;amp; -1 &amp;amp; -1 \\ 2.5 &amp;amp; 2.5 &amp;amp; -1 &amp;amp; -1 \\ 2 &amp;amp; 2 &amp;amp; 3 &amp;amp; 3 \\ 2 &amp;amp; 2 &amp;amp; 3 &amp;amp; 3 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Global Average Pooling (GAP)&lt;/strong&gt; on \(X\): sums all \(16\) entries (\(31\)) and divides by \(16\), returning a single scalar \(31/16 = 1.9375\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;pooling-layers-and-cnn-architectures&quot;&gt;Pooling Layers and CNN Architectures&lt;/h1&gt;

&lt;p&gt;Now that we understand convolutional layers, we need two more pieces to build complete CNNs: &lt;strong&gt;pooling layers&lt;/strong&gt; for downsampling and &lt;strong&gt;architecture design patterns&lt;/strong&gt; that combine these components effectively. This lesson covers pooling operations in depth and traces the evolution of CNN architectures from LeNet to modern designs.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;1-pooling-layers-concept-overview&quot;&gt;1. Pooling Layers: Concept Overview&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Pooling&lt;/strong&gt; (also called subsampling or downsampling) reduces the spatial dimensions of feature maps while retaining the most important information. This serves several critical purposes:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Dimension reduction&lt;/strong&gt;: Smaller feature maps mean fewer parameters and less computation in subsequent layers&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Translation invariance&lt;/strong&gt;: Small shifts in the input produce the same pooled output&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Noise suppression&lt;/strong&gt;: Averaging or taking max reduces sensitivity to small variations&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Receptive field growth&lt;/strong&gt;: Each pooled pixel represents a larger region of the original input&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Key insight&lt;/strong&gt;: Pooling acts as a form of “summarization” — we don’t need every pixel of detail to recognize a cat. We need the essential features, and pooling extracts those while discarding redundant information.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv5.jpg&quot; alt=&quot;CNN&quot; /&gt;
&lt;em&gt;Overview of Convolutional Neural Network (CNN) architecture. Source: AnalyticsVidhya&lt;/em&gt;
—&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;h3 id=&quot;max-pooling&quot;&gt;Max Pooling&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Max pooling&lt;/strong&gt; takes the maximum value in each pooling region:&lt;/p&gt;

\[\text{MaxPool}(X)_{i,j} = \max_{m,n \in R_{i,j}} X_{m,n}\]

&lt;p&gt;Where \(R_{i,j}\) is the pooling region (typically 2×2) at output position \((i,j)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Visual example with 2×2 pooling, stride 2&lt;/strong&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (4×4):              Output (2×2):

┌─────┬─────┬─────┬─────┐
│  1  │  3  │  2  │  4  │     ┌─────┬─────┐
├─────┼─────┼─────┼─────┤     │  6  │  8  │
│  5  │  6  │  7  │  8  │ →   ├─────┼─────┤
├─────┼─────┼─────┼─────┤     │  3  │  4  │
│  0  │  2  │  1  │  3  │     └─────┴─────┘
├─────┼─────┼─────┼─────┤
│  1  │  3  │  2  │  4  │
└─────┴─────┴─────┴─────┘

Region [0:2, 0:2] = [[1,3],[5,6]] → max = 6
Region [0:2, 2:4] = [[2,4],[7,8]] → max = 8
Region [2:4, 0:2] = [[0,2],[1,3]] → max = 3
Region [2:4, 2:4] = [[1,3],[2,4]] → max = 4
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Properties of max pooling&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Preserves the strongest activations (dominant features)&lt;/li&gt;
  &lt;li&gt;Provides some translation invariance&lt;/li&gt;
  &lt;li&gt;Introduces a form of non-linearity&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;No learnable parameters&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;average-pooling&quot;&gt;Average Pooling&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Average pooling&lt;/strong&gt; computes the mean of each pooling region:&lt;/p&gt;

\[\text{AvgPool}(X)_{i,j} = \frac{1}{|R_{i,j}|} \sum_{m,n \in R_{i,j}} X_{m,n}\]

&lt;p&gt;&lt;strong&gt;Visual example&lt;/strong&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (4×4):              Output (2×2):

┌─────┬─────┬─────┬─────┐
│  1  │  3  │  2  │  4  │     ┌───────┬───────┐
├─────┼─────┼─────┼─────┤     │ 3.75  │ 5.25  │
│  5  │  6  │  7  │  8  │ →   ├───────┼───────┤
├─────┼─────┼─────┼─────┤     │ 1.50  │ 2.50  │
│  0  │  2  │  1  │  3  │     └───────┴───────┘
├─────┼─────┼─────┼─────┤
│  1  │  3  │  2  │  4  │
└─────┴─────┴─────┴─────┘

Region [0:2, 0:2] = [[1,3],[5,6]] → mean = 15/4 = 3.75
Region [0:2, 2:4] = [[2,4],[7,8]] → mean = 21/4 = 5.25
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Properties of average pooling&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Considers all values (no information completely discarded)&lt;/li&gt;
  &lt;li&gt;Smoother gradients during backpropagation&lt;/li&gt;
  &lt;li&gt;Better for preserving background information&lt;/li&gt;
  &lt;li&gt;Less common in classification, more in segmentation&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;max-pooling-vs-average-pooling-when-to-use-which&quot;&gt;Max Pooling vs Average Pooling: When to Use Which?&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Aspect&lt;/th&gt;
      &lt;th&gt;Max Pooling&lt;/th&gt;
      &lt;th&gt;Average Pooling&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Preserves&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Dominant features&lt;/td&gt;
      &lt;td&gt;Overall intensity&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Gradients&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Sparse (only through max)&lt;/td&gt;
      &lt;td&gt;Dense (through all)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Use case&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Classification (find most distinctive)&lt;/td&gt;
      &lt;td&gt;Segmentation, depth estimation&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Modern usage&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Early/middle layers&lt;/td&gt;
      &lt;td&gt;Global pooling at the end&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Empirical finding&lt;/strong&gt;: Max pooling generally works better for classification because the most distinctive features (maximum activations) are most useful for discriminating between classes.&lt;/p&gt;

&lt;h3 id=&quot;global-average-pooling-gap&quot;&gt;Global Average Pooling (GAP)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Global Average Pooling&lt;/strong&gt; averages each entire feature map to a single value:&lt;/p&gt;

\[\text{GAP}(X)_c = \frac{1}{H \times W} \sum_{i=1}^{H} \sum_{j=1}^{W} X_{i,j,c}\]

&lt;p&gt;&lt;strong&gt;Visual example&lt;/strong&gt;:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (7×7×512):                    Output (512,):

┌─────────────────────────────┐
│  Feature Map 1 (7×7)        │ →  [0.42]
├─────────────────────────────┤
│  Feature Map 2 (7×7)        │ →  [0.78]
├─────────────────────────────┤
│         ...                 │      ...
├─────────────────────────────┤
│  Feature Map 512 (7×7)      │ →  [0.31]
└─────────────────────────────┘

Each 7×7 map → single number (its average)
Result: 512-dimensional vector
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Why GAP is revolutionary&lt;/strong&gt; (from Network in Network, 2014):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;No fully connected layers needed&lt;/strong&gt;: Reduces parameters dramatically&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Better generalization&lt;/strong&gt;: Acts as structural regularizer&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;More interpretable&lt;/strong&gt;: Each feature map can be directly associated with a class&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Input size flexibility&lt;/strong&gt;: Model can accept any input size (at inference time)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Before GAP&lt;/strong&gt; (AlexNet, VGG):&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Conv layers → Flatten (4096 values) → FC (4096→4096) → FC (4096→1000)
Parameters in FC layers: 4096×4096 + 4096×1000 ≈ 20 million
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;With GAP&lt;/strong&gt; (ResNet, modern CNNs):&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Conv layers → GAP (512 values) → FC (512→1000)
Parameters: 512×1000 = 512,000
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;40× fewer parameters&lt;/strong&gt; just from this change!&lt;/p&gt;

&lt;h3 id=&quot;output-dimensions-for-pooling&quot;&gt;Output Dimensions for Pooling&lt;/h3&gt;

&lt;p&gt;The same formula as convolution applies:&lt;/p&gt;

\[H_{out} = \left\lfloor \frac{H_{in} + 2p - k}{s} \right\rfloor + 1\]

&lt;p&gt;For standard 2×2 max pooling with stride 2:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[k = 2, s = 2, p = 0\]
  &lt;/li&gt;
  &lt;li&gt;
\[H_{out} = \lfloor (H_{in} - 2) / 2 \rfloor + 1 = H_{in} / 2\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Spatial dimensions are halved&lt;/strong&gt; (assuming even dimensions).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;3-code-implementation&quot;&gt;3. Code Implementation&lt;/h2&gt;

&lt;h3 id=&quot;numpy-implementation&quot;&gt;NumPy Implementation&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Max pooling operation.
    
    Args:
        input_array: Input of shape (H, W) or (H, W, C)
        pool_size: Size of pooling window
        stride: Stride of the pooling operation
    
    Returns:
        Pooled output
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Handle single channel case
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ndim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newaxis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Calculate output dimensions
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Extract pooling region and take max
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;region&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;region&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;avg_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Average pooling operation.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ndim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newaxis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;region&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;region&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;squeeze_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;global_avg_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Global average pooling: average each channel to single value.
    
    Args:
        input_array: Shape (H, W, C)
    
    Returns:
        Vector of shape (C,)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== DEMONSTRATION ==============
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pooling Operations Demonstration&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create sample input
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_data&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input (4×4):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_data&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Max pooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_pooled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Max pooling (2×2, stride 2):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_pooled&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Average pooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_pooled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;avg_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pool_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Average pooling (2×2, stride 2):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_pooled&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Global average pooling (for multi-channel)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;multi_channel&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;gap_output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;global_avg_pool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;multi_channel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Global average pooling:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Input shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;multi_channel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Output shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gap_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  First 5 values: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gap_output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;pytorch-implementation&quot;&gt;PyTorch Implementation&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# ============== BUILT-IN POOLING LAYERS ==============
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Max pooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Average pooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Global average pooling (adaptive - works with any input size)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;global_avg_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AdaptiveAvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Output size 1×1
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Global max pooling
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;global_max_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AdaptiveMaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== DEMONSTRATION ==============
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PyTorch Pooling Examples&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create sample input: batch of 2, 64 channels, 32×32
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Apply different poolings
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;avg_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;avg_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;gap_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;global_avg_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;After MaxPool2d(2,2): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# (2, 64, 16, 16)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;After AvgPool2d(2,2): &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# (2, 64, 16, 16)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;After GAP: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gap_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                 &lt;span class=&quot;c1&quot;&gt;# (2, 64, 1, 1)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;After GAP + squeeze: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gap_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;squeeze&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (2, 64)
&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# ============== POOLING WITH INDICES (for unpooling) ==============
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# MaxPool can return indices for unpooling operations
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_pool_with_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;return_indices&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pooled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;max_pool_with_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Max pooling with indices:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Pooled shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pooled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Indices shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Unpooling (useful for segmentation networks like U-Net)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;unpool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxUnpool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;unpooled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;unpool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pooled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Unpooled shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;unpooled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== COMPARISON: POOLING vs STRIDED CONV ==============
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Pooling vs Strided Convolution&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Traditional: Conv → Pool
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_then_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 32×32 → 32×32
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;                              &lt;span class=&quot;c1&quot;&gt;# 32×32 → 16×16
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Modern: Strided Conv (learnable downsampling)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;strided_conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 32×32 → 16×16
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;out_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_then_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;out_strided&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;strided_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Conv + MaxPool: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Strided Conv: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_strided&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Parameter comparison
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;conv_then_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;strided_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;strided_conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Parameters - Conv+Pool: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pool_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Strided Conv: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;strided_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(Same parameters, but strided conv learns the downsampling!)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=ZjM_XQa5s6s&quot;&gt;Max Pooling in Convolutional Neural Networks explained&lt;/a&gt; — deeplizard, English. Max pooling keeps the strongest activation in each window.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. Pooling inside a full conv-net forward pass, so the shape change is visible.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, English. The lecture’s comparison of pooling against strided convolution, which is the design choice in the notes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01 Convolutional Layers</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_Convolutional_Layers/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_Convolutional_Layers</id>
   <content type="html">&lt;p&gt;At the heart of every convolutional neural network—from LeNet reading handwritten checks in 1998 to ConvNeXt competing with Vision Transformers today—sits a single mathematical primitive: the convolutional layer. Before diving into pooling or multi-stage architectures, this module dissects that primitive from four complementary angles: exact discrete math, geometric intuition, hands-on NumPy/PyTorch code, and modern efficiency variants.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-four-lenses-on-the-convolutional-layer&quot;&gt;Key ideas: Four Lenses on the Convolutional Layer&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Algebraic &amp;amp; Dimensional Mechanics&lt;/strong&gt;: Exact cross-correlation formulas, multi-channel inner products, and the output-shape equation \(H_{\text{out}} = \lfloor (H + 2p - d(k-1) - 1)/s \rfloor + 1\) govern every tensor transition.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Visual &amp;amp; Geometric Intuition&lt;/strong&gt;: Local filters act as template matchers and finite-difference edge detectors whose stacked receptive fields build hierarchical representations from pixels to semantic parts.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Systems &amp;amp; Implementation Fluency&lt;/strong&gt;: Translating index loops in NumPy into batched &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, C, H, W)&lt;/code&gt; PyTorch blocks (with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BatchNorm2d&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias=False&lt;/code&gt;) turns theory into trainable GPU code.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Architectural Efficiency &amp;amp; Trade-offs&lt;/strong&gt;: Depthwise separable, dilated, and residual convolutions solve the compute, receptive-field, and optimization bottlenecks of plain stacked layers.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-one-shot-sanity-check-of-a-conv-layer-specification&quot;&gt;Worked example: One-Shot Sanity Check of a Conv Layer Specification&lt;/h3&gt;

&lt;p&gt;Before coding any convolutional layer, verify three numbers by hand for &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, stride=2, padding=2)&lt;/code&gt; applied to a \(64 \times 64\) RGB image:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Output spatial size&lt;/strong&gt;:
\(H_{\text{out}} = \left\lfloor \frac{64 + 2(2) - 5}{2} \right\rfloor + 1 = \left\lfloor \frac{63}{2} \right\rfloor + 1 = 31 + 1 = 32.\)
Output tensor shape for a batch of \(16\) images: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(16, 32, 32, 32)&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trainable parameter count (with bias)&lt;/strong&gt;:
\(P = 32 \times (3 \times 5 \times 5 + 1) = 32 \times 76 = 2{,}432.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Activation memory (float32, 4 bytes/element) for one batch&lt;/strong&gt;:
\(16 \times 32 \times 32 \times 32 \times 4\text{ bytes} = 2{,}097{,}152\text{ bytes} = 2.0\text{ MiB}.\)
Notice that activations already occupy over \(200\times\) more memory than the layer’s \(2{,}432 \times 4 \approx 9.5\text{ KiB}\) of weights—a foundational systems fact of deep vision.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers convolutional layers — the core building block of CNNs — organized into focused sections:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Convolution Math and Dimensions&lt;/strong&gt; — concept overview, mathematical foundation, multi-channel convolution, output size, and parameter counts&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convolution Intuition and Examples&lt;/strong&gt; — edge detection, hierarchical features, and receptive field growth&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convolution Implementation&lt;/strong&gt; — NumPy from scratch, PyTorch APIs, and a complete CNN block&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Related Concepts, Pitfalls, and Papers&lt;/strong&gt; — connections to other layers, common mistakes, practical tricks, and foundational papers&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Work through each section in order before moving on to pooling and classic architectures.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, English. Before the math, intuition, and code lessons split one operation apart.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, English. The lecture that carries the operation into a layer with channels.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. A fully worked image example of the same layer.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-04 Convolution Related Concepts, Pitfalls, and Papers</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_04_Convolution_Pitfalls_and_Papers/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_04_Convolution_Pitfalls_and_Papers</id>
   <content type="html">&lt;p&gt;Standard dense convolution launched the deep vision revolution, but deploying CNNs onto real hardware—from smartphone cameras to high-resolution medical segmentation—quickly exposed its cracks: quadratic compute growth with kernel size, checkerboard artifacts, vanishing gradients in deep stacks, and bloated parameter counts. The innovations that followed—depthwise separable convolutions (MobileNet), dilated convolutions (DeepLab), residual connections (ResNet), and careful normalization—are not disconnected tricks; they are targeted mathematical surgeries on the original convolutional operator.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-architectural-variants-and-failure-modes-of-convolution&quot;&gt;Key ideas: Architectural Variants and Failure Modes of Convolution&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Depthwise Separable Factorization&lt;/strong&gt;: Standard convolution couples spatial filtering and cross-channel mixing into one \(C_{\text{in}} C_{\text{out}} k^2\) tensor. Factoring it into a per-channel &lt;strong&gt;depthwise&lt;/strong&gt; \(k \times k\) conv followed by a &lt;strong&gt;pointwise&lt;/strong&gt; \(1 \times 1\) conv decouples space from depth, slashing MACs and weights by roughly \(8\times\)–\(9\times\) for \(3 \times 3\) kernels.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dilated (Atrous) Convolutions&lt;/strong&gt;: Inserting spacing \(d\) between kernel elements expands the receptive field exponentially (\(k_{\text{eff}} = d(k-1)+1\)) without losing spatial resolution or adding parameters—critical for dense prediction tasks like semantic segmentation—though uncoordinated dilation rates can cause “gridding” blind spots.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Residual Skip Paths &amp;amp; Gradient Highways&lt;/strong&gt;: Adding the identity mapping \(y = F(x) + x\) ensures that the Jacobian \(\partial y / \partial x = I + \partial F / \partial x\) stays well-conditioned even across 100+ layers, preventing degradation where deeper plain CNNs perform worse on training data than shallower ones.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Boundary Artifacts &amp;amp; Receptive Field Mismatch&lt;/strong&gt;: Repeated zero-padding leaks border-position information into interior activations, while aggressive early striding can alias fine textures before the network has extracted them.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-standard-vs-depthwise-separable-convolution-cost&quot;&gt;Worked example: Standard vs. Depthwise Separable Convolution Cost&lt;/h3&gt;

&lt;p&gt;Suppose a mobile vision layer transforms a \(28 \times 28\) feature map from \(C_{\text{in}} = 64\) channels to \(C_{\text{out}} = 128\) channels using \(k = 3\), stride \(s = 1\), padding \(p = 1\) (so spatial output remains \(28 \times 28 = 784\) positions).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standard 2D convolution&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Parameters (excluding bias):
\(P_{\text{std}} = C_{\text{in}} \cdot C_{\text{out}} \cdot k^2 = 64 \times 128 \times 9 = 73{,}728.\)&lt;/li&gt;
      &lt;li&gt;Multiply-accumulate operations (MACs):
\(\text{MACs}_{\text{std}} = 784 \times 73{,}728 = 57{,}802{,}752 \approx 57.8\text{M}.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Depthwise separable convolution&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Stage 1 (Depthwise \(3 \times 3\), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;groups=64&lt;/code&gt;)&lt;/strong&gt;: \(64\) independent \(3 \times 3\) filters:
\(P_{\text{dw}} = 64 \times 9 = 576, \quad \text{MACs}_{\text{dw}} = 784 \times 576 = 451{,}584.\)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Stage 2 (Pointwise \(1 \times 1\))&lt;/strong&gt;: mixes \(64 \to 128\) channels:
\(P_{\text{pw}} = 64 \times 128 \times 1 = 8{,}192, \quad \text{MACs}_{\text{pw}} = 784 \times 8{,}192 = 6{,}422{,}528.\)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Total&lt;/strong&gt;:
\(P_{\text{sep}} = 576 + 8{,}192 = 8{,}768, \quad \text{MACs}_{\text{sep}} = 6{,}874{,}112 \approx 6.87\text{M}.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact efficiency ratio&lt;/strong&gt;:
\(\frac{P_{\text{sep}}}{P_{\text{std}}} = \frac{1}{C_{\text{out}}} + \frac{1}{k^2} = \frac{1}{128} + \frac{1}{9} \approx 0.00781 + 0.11111 = 0.1189 \implies 8.41\times \text{ reduction!}\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;h3 id=&quot;cnn-vs-regular-neural-networks&quot;&gt;CNN vs Regular Neural Networks&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv7.jpg&quot; alt=&quot;CNN vs Regular Neural Network&quot; /&gt;
&lt;em&gt;Why not just use a regular neural network for images? CNNs win because they preserve spatial structure, use shared filters (far fewer parameters), recognize objects regardless of position, and are designed specifically for visual data processing. Source: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Aspect&lt;/th&gt;
      &lt;th&gt;Fully Connected&lt;/th&gt;
      &lt;th&gt;Convolutional&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Connectivity&lt;/td&gt;
      &lt;td&gt;All-to-all&lt;/td&gt;
      &lt;td&gt;Local (kernel size)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Parameter sharing&lt;/td&gt;
      &lt;td&gt;None&lt;/td&gt;
      &lt;td&gt;Same filter everywhere&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Parameters (32×32×3 → 64)&lt;/td&gt;
      &lt;td&gt;196,672&lt;/td&gt;
      &lt;td&gt;1,792&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Translation invariance&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Preserves spatial structure&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;fully-connected-layers&quot;&gt;Fully Connected Layers&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Connect every input neuron to every output neuron&lt;/li&gt;
  &lt;li&gt;No assumption about spatial structure&lt;/li&gt;
  &lt;li&gt;Used after conv layers for final classification&lt;/li&gt;
  &lt;li&gt;Parameters grow quadratically with input size&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;pooling-layers&quot;&gt;Pooling Layers&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Downsample feature maps (reduce spatial dimensions)&lt;/li&gt;
  &lt;li&gt;Add translation invariance&lt;/li&gt;
  &lt;li&gt;Reduce computation and memory&lt;/li&gt;
  &lt;li&gt;No learnable parameters&lt;/li&gt;
  &lt;li&gt;Common types: Max pooling, Average pooling&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;batch-normalization&quot;&gt;Batch Normalization&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Normalizes activations to have zero mean and unit variance&lt;/li&gt;
  &lt;li&gt;Stabilizes training by reducing internal covariate shift&lt;/li&gt;
  &lt;li&gt;Typically placed after convolution, before activation&lt;/li&gt;
  &lt;li&gt;Enables higher learning rates and faster convergence&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;residual-connections-skip-connections&quot;&gt;Residual Connections (Skip Connections)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Allow gradients to flow directly through the network&lt;/li&gt;
  &lt;li&gt;Enable training of very deep networks (100+ layers)&lt;/li&gt;
  &lt;li&gt;Output: \(\mathbf{y} = F(\mathbf{x}) + \mathbf{x}\)&lt;/li&gt;
  &lt;li&gt;Key innovation of ResNet (2015)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;depthwise-separable-convolutions&quot;&gt;Depthwise Separable Convolutions&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Factorize standard convolution into depthwise + pointwise&lt;/li&gt;
  &lt;li&gt;Dramatically fewer parameters and computations&lt;/li&gt;
  &lt;li&gt;Depthwise: One filter per input channel&lt;/li&gt;
  &lt;li&gt;Pointwise: 1×1 conv to combine channels&lt;/li&gt;
  &lt;li&gt;Used in MobileNet, EfficientNet for mobile deployment&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;dilated-atrous-convolutions&quot;&gt;Dilated (Atrous) Convolutions&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Insert gaps between kernel elements&lt;/li&gt;
  &lt;li&gt;Increase receptive field without more parameters&lt;/li&gt;
  &lt;li&gt;Used in semantic segmentation (DeepLab)&lt;/li&gt;
  &lt;li&gt;Dilation rate \(d\): kernel elements spaced \(d\) pixels apart&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf&quot;&gt;“Gradient-Based Learning Applied to Document Recognition” (1998)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Yann LeCun, Léon Bottou, Yoshua Bengio, Patrick Haffner&lt;br /&gt;
Introduced LeNet-5, the first successful CNN for digit recognition. Demonstrated that convolutional layers with shared weights can learn hierarchical features from raw pixels. Established the conv-pool-conv-pool-FC pattern that dominated for nearly two decades. This paper laid the foundation for all modern CNNs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks&quot;&gt;“ImageNet Classification with Deep Convolutional Neural Networks” (2012)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Alex Krizhevsky, Ilya Sutskever, Geoffrey E. Hinton&lt;br /&gt;
AlexNet won ImageNet 2012 by a huge margin (top-5 error: 15.3% vs 26.2% runner-up), proving that deep CNNs could scale to real-world vision tasks. Introduced ReLU activation, dropout regularization, and GPU training to deep learning. This paper triggered the deep learning revolution that transformed AI.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1409.1556&quot;&gt;“Very Deep Convolutional Networks for Large-Scale Image Recognition” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Karen Simonyan, Andrew Zisserman&lt;br /&gt;
VGGNet demonstrated that network depth is crucial for performance. Used exclusively small 3×3 filters stacked to achieve large receptive fields, showing that two 3×3 convs have the same receptive field as one 5×5 but with fewer parameters and more non-linearity. The simple, repeating architecture became a template for future designs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.03385&quot;&gt;“Deep Residual Learning for Image Recognition” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun&lt;br /&gt;
Introduced skip connections that enable training of networks with 152+ layers. Solved the degradation problem where deeper networks had higher training error than shallow ones. ResNet won ImageNet 2015 and fundamentally changed how we design deep networks. The residual learning framework is now used in transformers, diffusion models, and virtually all deep architectures.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1704.04861&quot;&gt;“MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Andrew G. Howard et al.&lt;br /&gt;
Introduced depthwise separable convolutions that reduce computation by 8-9× while maintaining accuracy. Enabled running CNNs on mobile phones and embedded devices. Pioneered the efficient network design paradigm that led to EfficientNet and mobile-first AI deployment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.00567&quot;&gt;“Rethinking the Inception Architecture for Computer Vision” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Christian Szegedy et al.&lt;br /&gt;
Inception-v3 introduced factorized convolutions (using 1×n and n×1 instead of n×n) and auxiliary classifiers. Demonstrated that careful architecture design could improve both accuracy and efficiency. Many design principles from this paper influence modern architectures.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;7-common-pitfalls-and-tricks&quot;&gt;7. Common Pitfalls and Tricks&lt;/h2&gt;

&lt;h3 id=&quot;pitfall-1-not-using-padding&quot;&gt;Pitfall 1: Not Using Padding&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Issue&lt;/strong&gt;: Output shrinks with each layer, losing boundary information&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Without padding: 32×32 → 30×30 → 28×28 → ... (shrinks rapidly!)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# No padding
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# With padding: 32×32 → 32×32 → 32×32 (maintains size)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# &quot;Same&quot; padding
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;padding = (kernel_size - 1) // 2&lt;/code&gt; for odd kernel sizes to maintain spatial dimensions.&lt;/p&gt;

&lt;h3 id=&quot;pitfall-2-forgetting-about-channel-dimension-order&quot;&gt;Pitfall 2: Forgetting About Channel Dimension Order&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Issue&lt;/strong&gt;: Different frameworks use different conventions&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# PyTorch: (N, C, H, W) - Channels first
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_pytorch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# TensorFlow/Keras: (N, H, W, C) - Channels last
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_tensorflow&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tf&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;normal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;height&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Converting between them
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_tf_to_pytorch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_tensorflow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;permute&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# If using torch
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;pitfall-3-too-large-initial-kernel-size&quot;&gt;Pitfall 3: Too Large Initial Kernel Size&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Issue&lt;/strong&gt;: Large kernels have many parameters but limited receptive field benefit&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Less effective (VGG&apos;s insight)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 7×7 = 49 params/channel
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Better: Stack smaller kernels
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Three 3×3 = 27 params/channel, same 7×7 receptive field, 3× more nonlinearity
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;trick-1-11-convolutions-for-dimensionality-control&quot;&gt;Trick 1: 1×1 Convolutions for Dimensionality Control&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Reduce channels (bottleneck)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bottleneck&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# 512 → 64 channels with minimal computation
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Increase channels
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expand&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Mix channel information without spatial operations
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;trick-2-strided-convolution-instead-of-pooling&quot;&gt;Trick 2: Strided Convolution Instead of Pooling&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Traditional: Conv → Pool
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Modern: Strided conv (learnable downsampling)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;strided_conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Same output size, but the downsampling is learned!
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;trick-3-proper-weight-initialization&quot;&gt;Trick 3: Proper Weight Initialization&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Kaiming initialization for ReLU networks
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;init_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;isinstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;kaiming_normal_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mode&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;fan_out&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nonlinearity&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;constant_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;isinstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;constant_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;constant_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;apply&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;init_weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;trick-4-calculating-receptive-field&quot;&gt;Trick 4: Calculating Receptive Field&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;receptive_field_1d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Calculate receptive field for a stack of conv layers.
    
    Each layer is (kernel_size, stride)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Start with single pixel
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;stride_product&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride_product&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;stride_product&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rf&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example: 3 conv layers (k=3, s=1) followed by pool (k=2, s=2)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Receptive field: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;receptive_field_1d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 14
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;8-key-takeaways&quot;&gt;8. Key Takeaways&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Convolution vs Cross-Correlation&lt;/strong&gt;: Deep learning uses cross-correlation but calls it convolution. The difference (kernel flipping) doesn’t matter because weights are learned.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Local Connectivity + Weight Sharing&lt;/strong&gt;: These two properties make CNNs dramatically more parameter-efficient than fully connected networks.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Hierarchical Feature Learning&lt;/strong&gt;: CNNs automatically learn edges → textures → parts → objects, mirroring biological vision.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Output Dimensions&lt;/strong&gt;: \(n_{out} = \lfloor(n_{in} + 2p - k)/s\rfloor + 1\) — memorize this formula!&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Small Filters Rule&lt;/strong&gt;: Stack 3×3 convolutions instead of using larger kernels (more nonlinearity, fewer parameters).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Receptive Field&lt;/strong&gt;: Grows with depth. Understanding receptive field is crucial for architecture design.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Modern Best Practices&lt;/strong&gt;:&lt;/p&gt;
    &lt;ul&gt;
      &lt;li&gt;Conv → BatchNorm → ReLU&lt;/li&gt;
      &lt;li&gt;Residual connections for deep networks&lt;/li&gt;
      &lt;li&gt;Global average pooling instead of flatten + FC&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Convolutional layers are the foundation of computer vision in deep learning. Mastering them is essential for any vision application — from image classification to object detection to image generation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Next&lt;/strong&gt;: Pooling layers and complete CNN architectures (LeNet, AlexNet, VGG, ResNet)!&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, English. The pitfalls that show up as soon as channels and stride interact.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, English. A 2024 statement of which of those pitfalls still matter.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=RYth6EbBUqM&quot;&gt;C4W2L04 Why ResNets Work&lt;/a&gt; — DeepLearningAI, English. Why a plain stack of convolutions degrades, the paper-level pitfall the ResNet note is about.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-03 Convolution Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_03_Convolution_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_03_Convolution_Implementation</id>
   <content type="html">&lt;p&gt;Knowing the equation of 2D convolution on a whiteboard is only half the craft; translating it into bug-free, GPU-efficient code requires bridging two very different worlds. On one side sits raw NumPy, where explicit indexing exposes every boundary condition and kernel-flipping nuance. On the other sits PyTorch’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt;, where batched 4D tensors, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias=False&lt;/code&gt; conventions, and modular Conv–BN–ReLU blocks power modern vision backbones. This hub connects both implementations so you can verify framework outputs against first-principles arithmetic.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-bridging-first-principles-code-and-framework-apis&quot;&gt;Key ideas: Bridging First-Principles Code and Framework APIs&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Verification by Differential Testing&lt;/strong&gt;: Implementing a slow, transparent NumPy reference and comparing its output against &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.functional.conv2d&lt;/code&gt; on identical random tensors guarantees that your understanding of padding, stride, and channel summation matches the C++/CUDA backend to floating-point precision (\(&amp;lt; 10^{-6}\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tensor Rank &amp;amp; Axis Semantics&lt;/strong&gt;: Raw 2D images are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(H, W)&lt;/code&gt;, single multi-channel images are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(C, H, W)&lt;/code&gt;, and PyTorch mini-batches are &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, C, H, W)&lt;/code&gt;. Mixing up channel-last &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(H, W, C)&lt;/code&gt; (NumPy/PIL) with channel-first &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(C, H, W)&lt;/code&gt; (PyTorch) is the single most common vision bug.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Modular Block Abstraction&lt;/strong&gt;: Real CNNs encapsulate &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Conv2d -&amp;gt; BatchNorm2d -&amp;gt; ReLU&lt;/code&gt; into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Module&lt;/code&gt; building blocks, allowing clean residual wiring, automated weight initialization, and easy inspection of intermediate feature maps.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-cross-checking-numpy-vs-pytorch-output-on-a-minimal-tensor&quot;&gt;Worked example: Cross-Checking NumPy vs. PyTorch Output on a Minimal Tensor&lt;/h3&gt;

&lt;p&gt;Suppose we verify that our NumPy cross-correlation matches PyTorch &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; on a minimal &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N=1, C_in=1, H=3, W=3)&lt;/code&gt; input with a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(C_out=1, C_in=1, kH=2, kW=2)&lt;/code&gt; kernel, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=1&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;padding=0&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias=0&lt;/code&gt;:&lt;/p&gt;

\[X = \begin{bmatrix} 2 &amp;amp; 0 &amp;amp; 1 \\ 1 &amp;amp; 3 &amp;amp; 2 \\ 0 &amp;amp; 2 &amp;amp; 1 \end{bmatrix}, \quad W = \begin{bmatrix} 1 &amp;amp; 0 \\ -1 &amp;amp; 2 \end{bmatrix}.\]

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the four output cells by hand (NumPy cross-correlation)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\((0, 0)\): \(1(2) + 0(0) + (-1)(1) + 2(3) = 2 - 1 + 6 = 7\).&lt;/li&gt;
      &lt;li&gt;\((0, 1)\): \(1(0) + 0(1) + (-1)(3) + 2(2) = 0 - 3 + 4 = 1\).&lt;/li&gt;
      &lt;li&gt;\((1, 0)\): \(1(1) + 0(3) + (-1)(0) + 2(2) = 1 + 0 + 4 = 5\).&lt;/li&gt;
      &lt;li&gt;\((1, 1)\): \(1(3) + 0(2) + (-1)(2) + 2(1) = 3 - 2 + 2 = 3\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Expected PyTorch tensor&lt;/strong&gt;:
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.tensor([[[[7., 1.], [5., 3.]]]])&lt;/code&gt; of shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(1, 1, 2, 2)&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diagnostic check&lt;/strong&gt;: If your NumPy code instead returns &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[[7, 1], [5, 3]]&lt;/code&gt; transposed or flipped, you immediately catch whether you accidentally implemented true convolution (flipped kernel) or swapped &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(H, W)&lt;/code&gt; indices before scaling to real datasets.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Implementing convolutional layers:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;NumPy Implementation&lt;/strong&gt; — from-scratch convolution and demos&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;PyTorch and CNN Blocks&lt;/strong&gt; — PyTorch APIs, complete CNN block, training example&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pDdP0TFzsoQ&quot;&gt;PyTorch Tutorial 14 - Convolutional Neural Network (CNN)&lt;/a&gt; — Patrick Loeber, English. Nn.Conv2d, which is the PyTorch half of this implementation block.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, English. The shapes that call must respect.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. The explicit sum a NumPy implementation is looping over.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-03-02 Convolution PyTorch and CNN Blocks</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_03_02_Convolution_PyTorch/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_03_02_Convolution_PyTorch</id>
   <content type="html">&lt;p&gt;Moving from a toy 2D NumPy array to a real PyTorch vision pipeline introduces a fourth axis—the &lt;strong&gt;mini-batch&lt;/strong&gt;—and a strict memory convention: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N, C, H, W)&lt;/code&gt;. One misplaced channel dimension or forgotten &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias=False&lt;/code&gt; before BatchNorm silently wastes GPU memory or sabotages convergence. In production CNNs, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; is rarely used alone; it lives inside reusable &lt;strong&gt;Conv–BatchNorm–ReLU&lt;/strong&gt; blocks alongside \(1 \times 1\) pointwise bottlenecks and strided downsampling layers.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-pytorch-tensor-geometry-and-cnn-block-design&quot;&gt;Key ideas: PyTorch Tensor Geometry and CNN Block Design&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;NCHW Tensor Layout &amp;amp; Weight Shape Convention&lt;/strong&gt;: PyTorch stores image batches as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(Batch, Channels, Height, Width)&lt;/code&gt; and stores &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; weights as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(C_out, C_in / groups, kH, kW)&lt;/code&gt;. Knowing these exact axis orders makes shape debugging instantaneous before running a single forward pass.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Redundancy of Conv Bias Before BatchNorm&lt;/strong&gt;: BatchNorm subtracts the per-channel batch mean \(\mu_c\) before applying its own learnable shift \(\beta_c\). Any additive bias \(b_c\) inside &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; cancels out mathematically during mean subtraction, which is why modern CNN blocks always set &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias=False&lt;/code&gt; when followed by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.BatchNorm2d&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pointwise (\(1 \times 1\)) Convolutions as Per-Pixel MLPs&lt;/strong&gt;: A \(1 \times 1\) convolution does not mix neighboring pixels at all—it applies the exact same linear transformation across the channel vector at every \((h, w)\) location, enabling cheap dimensionality reduction (bottlenecks) or channel expansion.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Strided Convolution vs. Pooling for Downsampling&lt;/strong&gt;: Setting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=2&lt;/code&gt; in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; halves spatial resolution using learnable weights rather than fixed max/average rules, giving the network full control over anti-aliasing and feature retention.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-tracing-shapes--parameters-through-a-bottleneck-block&quot;&gt;Worked example: Tracing Shapes &amp;amp; Parameters Through a Bottleneck Block&lt;/h3&gt;

&lt;p&gt;Consider an input batch \(X\) of shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(N=8, C=256, H=28, W=28)&lt;/code&gt; entering a ResNet-style bottleneck sequence (all with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bias=False&lt;/code&gt; because each is followed by &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BatchNorm2d&lt;/code&gt;):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv1&lt;/code&gt;: \(1 \times 1\) conv, \(256 \to 64\) channels, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=1, padding=0&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv2&lt;/code&gt;: \(3 \times 3\) conv, \(64 \to 64\) channels, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=2, padding=1&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv3&lt;/code&gt;: \(1 \times 1\) conv, \(64 \to 256\) channels, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=1, padding=0&lt;/code&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trace tensor shapes layer by layer&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;After &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv1&lt;/code&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(8, 64, 28, 28)&lt;/code&gt; — spatial dimensions unchanged, channels compressed by \(4\times\).&lt;/li&gt;
      &lt;li&gt;After &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv2&lt;/code&gt;: \(H_{\text{out}} = \lfloor (28 + 2 - 3)/2 \rfloor + 1 = 14\), giving &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(8, 64, 14, 14)&lt;/code&gt;.&lt;/li&gt;
      &lt;li&gt;After &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv3&lt;/code&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(8, 256, 14, 14)&lt;/code&gt; — channels restored to \(256\) at half resolution.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Count exact trainable parameters&lt;/strong&gt; (conv weights + \(2C_{\text{out}}\) BatchNorm \(\gamma, \beta\) parameters per block):
    &lt;ul&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv1 + bn1&lt;/code&gt;: \((64 \times 256 \times 1 \times 1) + 2(64) = 16{,}384 + 128 = 16{,}512\).&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv2 + bn2&lt;/code&gt;: \((64 \times 64 \times 3 \times 3) + 2(64) = 36{,}864 + 128 = 36{,}992\).&lt;/li&gt;
      &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;conv3 + bn3&lt;/code&gt;: \((256 \times 64 \times 1 \times 1) + 2(256) = 16{,}384 + 512 = 16{,}896\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Total bottleneck parameters&lt;/strong&gt;: \(16{,}512 + 36{,}992 + 16{,}896 = 70{,}400\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare with a single direct \(3 \times 3\) conv (\(256 \to 256\), &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stride=2&lt;/code&gt;)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Weights alone: \(256 \times 256 \times 9 = 589{,}824\) parameters—more than \(8.3\times\) heavier than the entire 3-layer bottleneck block!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;pytorch-implementation&quot;&gt;PyTorch Implementation&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn.functional&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;F&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvolutionExplained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    A convolutional layer with detailed explanations.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                 &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Create the convolutional layer
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Forward pass with shape tracking.
        
        Args:
            x: Input tensor of shape (batch, channels, height, width)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_in&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute output dimensions
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_in&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W_in&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Apply convolution
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Verify shapes
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;assert&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Count and explain parameters.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Weight shape: (out_channels, in_channels, kernel_size, kernel_size)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;weight_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;bias_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;not&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias_params&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Parameter breakdown:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Weights: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; filters × &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
              &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;) = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Biases: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Total: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== DEMONSTRATIONS ==============
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PyTorch Convolution Examples&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example 1: Basic convolution
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--- Example 1: RGB Image to 64 Feature Maps ---&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv_layer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvolutionExplained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# RGB input
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# 64 learned filters
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;      &lt;span class=&quot;c1&quot;&gt;# 3×3 filters
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# &quot;Same&quot; padding
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Input: batch of 8 RGB images, 32×32 pixels
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input shape:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Output shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Example 2: Downsampling with strided convolution
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--- Example 2: Strided Convolution for Downsampling ---&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv_downsample&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvolutionExplained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;           &lt;span class=&quot;c1&quot;&gt;# Stride 2 halves spatial dimensions
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;output2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_downsample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input shape:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Output shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 32×32 → 16×16
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_downsample&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Example 3: 1×1 Convolution for channel manipulation
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--- Example 3: 1×1 Convolution (Channel Reduction) ---&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;conv_1x1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvolutionExplained&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Reduce channels dramatically
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;x3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;512&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;output3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv_1x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input shape:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Output shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Same spatial, fewer channels
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv_1x1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Example 4: Visualizing learned filters
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;--- Example 4: Inspecting Filter Weights ---&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Access the learned weights
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;conv_layer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Weight tensor shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; filters of size &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
      &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;×&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# First filter visualization (would show in matplotlib)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;first_filter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Shape: (3, 3, 3) = (in_channels, H, W)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;First filter shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;first_filter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Filter values (channel 0):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;first_filter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;complete-cnn-block-with-best-practices&quot;&gt;Complete CNN Block with Best Practices&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Standard convolutional block: Conv → BatchNorm → ReLU
    
    This pattern is used in virtually all modern CNNs.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Convolution (no bias when using BatchNorm)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;in_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Batch normalization stabilizes training
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# ReLU activation
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ResidualBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Residual block with skip connection (from ResNet).
    
    Key insight: Learn residual F(x) = H(x) - x instead of H(x) directly.
    Output: y = F(x) + x
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;conv2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Conv2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bn2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BatchNorm2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inplace&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Save input for skip connection
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;conv2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;bn2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;identity&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Skip connection!
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleCNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    A simple but effective CNN for image classification.
    
    Architecture: 
    Input → ConvBlocks (with pooling) → Global Average Pool → Classifier
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_channels&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Feature extraction layers
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Block 1: 32×32×3 → 16×16×32
&lt;/span&gt;            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_channels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Block 2: 16×16×32 → 8×8×64
&lt;/span&gt;            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Block 3: 8×8×64 → 4×4×128
&lt;/span&gt;            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;nc&quot;&gt;ConvBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MaxPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Global average pooling: 4×4×128 → 128
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;global_pool&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;AdaptiveAvgPool2d&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Classifier
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;classifier&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sequential&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Dropout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Extract features
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Global pooling
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;global_pool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Flatten
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Classify
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;classifier&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== TRAINING EXAMPLE ==============
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Single training step with forward and backward pass.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Calculate accuracy
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predicted&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Create model and training components
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleCNN&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_classes&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CrossEntropyLoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Count parameters
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;trainable_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;requires_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Model Statistics:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Total parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Trainable parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;trainable_params&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Simulate one training step
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dummy_images&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Batch of 32 CIFAR-like images
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dummy_labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randint&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,))&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dummy_images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dummy_labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Training step - Loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Accuracy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pDdP0TFzsoQ&quot;&gt;PyTorch Tutorial 14 - Convolutional Neural Network (CNN)&lt;/a&gt; — Patrick Loeber, English. A Conv2d module, then a small CNN block, which is this lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, English. How those blocks are stacked in a real conv net.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, English. The argument order (N, C, H, W) the module assumes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-03-01 Convolution NumPy Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_03_01_Convolution_NumPy/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_03_01_Convolution_NumPy</id>
   <content type="html">&lt;p&gt;Calling &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Conv2d&lt;/code&gt; in PyTorch takes one line of code, which makes it dangerously easy to treat convolution as an opaque black box. Yet the moment you implement 2D convolution from scratch in raw NumPy—explicitly slicing padded arrays, aligning &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(H, W)&lt;/code&gt; coordinates, and verifying that flipping the kernel converts cross-correlation into true convolution—every mystery about index boundaries, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;im2col&lt;/code&gt; vectorization, and memory layout clicks into sharp focus. Writing the slow loop once is the fastest way to understand how fast GPU kernels actually work.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-from-nested-loops-to-vectorized-matrix-multiplication&quot;&gt;Key ideas: From Nested Loops to Vectorized Matrix Multiplication&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Zero-Padding &amp;amp; Boundary Indexing&lt;/strong&gt;: Padding an image \(I \in \mathbb{R}^{H \times W}\) by \(p\) pixels creates a buffer \(I_{\text{pad}} \in \mathbb{R}^{(H+2p) \times (W+2p)}\) so that output index \((i, j)\) maps cleanly to the slice &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;I_pad[i*s : i*s + kH, j*s : j*s + kW]&lt;/code&gt; without out-of-bounds checks inside the inner loop.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-Correlation vs. Kernel Flipping (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;kernel[::-1, ::-1]&lt;/code&gt;)&lt;/strong&gt;: Rotating a 2D array by \(180^\circ\) reverses both spatial axes. Verifying numerically that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;xcorr(I, K) == conv(I, K[::-1, ::-1])&lt;/code&gt; cements the exact algebraic relationship between signal processing and deep learning frameworks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;im2col&lt;/code&gt; Lowering Trick&lt;/strong&gt;: Naive 4-nested Python loops are orders of magnitude slower than BLAS matrix multiplication. Production engines rearrange every \(k_H \times k_W\) input patch into a column of a matrix \(X_{\text{col}}\) and flatten each filter into a row of \(W_{\text{row}}\), turning the entire convolution into a single GEMM call \(Y = W_{\text{row}} X_{\text{col}}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Numerical Verification &amp;amp; Edge Response Signs&lt;/strong&gt;: Hand-crafted test patterns (such as a step function from \(0\) to \(1\)) provide deterministic ground truth: a vertical Sobel kernel must produce a strong positive peak at a dark-to-bright transition and an equal negative peak at a bright-to-dark transition.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-hand-tracing-im2col-on-a-3-times-3-input&quot;&gt;Worked example: Hand-Tracing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;im2col&lt;/code&gt; on a \(3 \times 3\) Input&lt;/h3&gt;

&lt;p&gt;Suppose we apply a \(2 \times 2\) kernel \(K = \begin{bmatrix} 1 &amp;amp; -1 \\ 2 &amp;amp; 0 \end{bmatrix}\) with stride \(s = 1\) and padding \(p = 0\) to a \(3 \times 3\) grayscale image:
\(I = \begin{bmatrix} 3 &amp;amp; 1 &amp;amp; 2 \\ 0 &amp;amp; 4 &amp;amp; 1 \\ 2 &amp;amp; 1 &amp;amp; 5 \end{bmatrix}.\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Determine the output grid size&lt;/strong&gt;:
\(H_{\text{out}} = \frac{3 - 2}{1} + 1 = 2, \quad W_{\text{out}} = 2 \implies 4 \text{ sliding patches}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Unfold the 4 patches into columns of \(X_{\text{col}} \in \mathbb{R}^{4 \times 4}\)&lt;/strong&gt; (reading each \(2 \times 2\) patch row-major):
    &lt;ul&gt;
      &lt;li&gt;Patch \((0, 0)\): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[3, 1, 0, 4]^T&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Patch \((0, 1)\): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[1, 2, 4, 1]^T&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Patch \((1, 0)\): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0, 4, 2, 1]^T&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;Patch \((1, 1)\): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[4, 1, 1, 5]^T&lt;/code&gt;
\(X_{\text{col}} = \begin{bmatrix} 3 &amp;amp; 1 &amp;amp; 0 &amp;amp; 4 \\ 1 &amp;amp; 2 &amp;amp; 4 &amp;amp; 1 \\ 0 &amp;amp; 4 &amp;amp; 2 &amp;amp; 1 \\ 4 &amp;amp; 1 &amp;amp; 1 &amp;amp; 5 \end{bmatrix}.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Flatten the kernel into a row vector \(W_{\text{row}} \in \mathbb{R}^{1 \times 4}\)&lt;/strong&gt;:
\(W_{\text{row}} = \begin{bmatrix} 1 &amp;amp; -1 &amp;amp; 2 &amp;amp; 0 \end{bmatrix}.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the single matrix-vector product \(W_{\text{row}} X_{\text{col}}\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Entry \((0,0)\): \(1(3) + (-1)(1) + 2(0) + 0(4) = 2\)&lt;/li&gt;
      &lt;li&gt;Entry \((0,1)\): \(1(1) + (-1)(2) + 2(4) + 0(1) = 7\)&lt;/li&gt;
      &lt;li&gt;Entry \((1,0)\): \(1(0) + (-1)(4) + 2(2) + 0(1) = 0\)&lt;/li&gt;
      &lt;li&gt;Entry \((1,1)\): \(1(4) + (-1)(1) + 2(1) + 0(5) = 5\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Reshape back to \((2, 2)\)&lt;/strong&gt;:
\(Y = \begin{bmatrix} 2 &amp;amp; 7 \\ 0 &amp;amp; 5 \end{bmatrix}.\)
Every single number matches the nested-loop cross-correlation—while executing as one contiguous BLAS call.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-implementation&quot;&gt;4. Code Implementation&lt;/h2&gt;

&lt;h3 id=&quot;numpy-implementation-from-scratch&quot;&gt;NumPy Implementation from Scratch&lt;/h3&gt;

&lt;p&gt;Understanding the low-level implementation solidifies the math:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Naive 2D convolution (cross-correlation) implementation.
    
    Args:
        image: Input array of shape (H, W) for single channel
               or (H, W, C) for multi-channel
        kernel: Filter array of shape (k, k) for single channel
                or (k, k, C) for multi-channel
        stride: Step size for sliding the kernel
        padding: Zero-padding added to input borders
    
    Returns:
        output: Convolved feature map
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Handle single-channel case
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ndim&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newaxis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;kernel&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newaxis&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;C&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Add padding
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;pad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                       &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;
                       &lt;span class=&quot;n&quot;&gt;mode&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;constant&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;constant_values&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Calculate output dimensions
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Initialize output
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Perform convolution (cross-correlation)
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;H_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Extract the region
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;region&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w_start&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Element-wise multiply and sum over all dimensions
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;j&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;region&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;


&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_multi_filter&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Multi-filter 2D convolution producing multiple output channels.
    
    Args:
        image: Input of shape (H, W, C_in)
        kernels: Filters of shape (num_filters, k, k, C_in)
        
    Returns:
        output: Feature maps of shape (H_out, W_out, num_filters)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;num_filters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Apply each filter
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;f&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_filters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kernels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;stride&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;padding&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stack&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;outputs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# ============== DEMONSTRATION ==============
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Example 1: Edge Detection
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Example 1: Vertical Edge Detection&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Create an image with a clear vertical edge
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;   &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;255&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Vertical edge detector (Sobel-like)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vertical_kernel&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;  &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;vertical_kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input image:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Kernel:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;vertical_kernel&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Output (edge detected):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Notice: High values where the vertical edge is located!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;


&lt;span class=&quot;c1&quot;&gt;# Example 2: True Convolution vs Cross-Correlation
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Example 2: Convolution vs Cross-Correlation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;asymmetric_kernel&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;flipped_kernel&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;flip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;asymmetric_kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Original kernel:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;asymmetric_kernel&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Flipped kernel (for true convolution):&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;flipped_kernel&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;small_image&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;11&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;12&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Cross-correlation (what deep learning uses)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cross_corr_result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;small_image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;asymmetric_kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# True convolution (with flip)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_conv_result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;conv2d_naive&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;small_image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;flipped_kernel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Cross-correlation result:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cross_corr_result&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True convolution result:&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true_conv_result&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Notice: Different results! Deep learning uses cross-correlation.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. The nested sum over the kernel is what the NumPy loops implement.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, English. The continuous picture of that sum, so the indexing does not become the definition.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, English. Use this when the NumPy output shape disagrees with the formula.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-02 Convolution Intuition and Examples</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_02_Convolution_Intuition_and_Examples/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_02_Convolution_Intuition_and_Examples</id>
   <content type="html">&lt;p&gt;When Hubel and Wiesel projected bars of light onto a screen in front of an anesthetized cat in 1959, they stumbled on a startling biological fact: individual neurons in the primary visual cortex remained completely silent until a straight edge drifted across a tiny patch of the retina at one exact angle. Decades later, when researchers visualized the first-layer filters of AlexNet trained purely on natural image labels, the exact same oriented edge detectors and color-opponent Gabor blobs emerged spontaneously from gradient descent. Convolution works not by memorizing pixels, but by asking a hierarchy of local geometric questions—and composing small answers into global understanding.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-from-local-filters-to-semantic-hierarchies&quot;&gt;Key ideas: From Local Filters to Semantic Hierarchies&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Directional Derivatives &amp;amp; Edge Detection&lt;/strong&gt;: Finite-difference kernels like Sobel \([-1, 0, +1]\) approximate the spatial partial derivatives \(\partial I / \partial x\) and \(\partial I / \partial y\). Wherever pixel intensity jumps sharply, the inner product spikes; in flat uniform regions, positive and negative weights cancel cleanly to zero.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Receptive Field Dynamics&lt;/strong&gt;: A single \(3 \times 3\) filter sees only \(9\) pixels, which cannot tell a dog’s ear from a triangle. However, each stacked convolutional layer expands the &lt;strong&gt;theoretical receptive field&lt;/strong&gt; \(r_\ell = r_{\ell-1} + (k_\ell - 1)\prod_{i=1}^{\ell-1} s_i\), allowing deep neurons to integrate context across the entire image.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Effective vs. Theoretical Receptive Field&lt;/strong&gt;: Because there are exponentially more paths from the center of a receptive field than from its corners, Luo et al. (2016) showed that the &lt;em&gt;effective&lt;/em&gt; receptive field follows a Gaussian profile concentrated near the center—meaning depth and stride must be designed generously.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Feature Hierarchy &amp;amp; Compositionality&lt;/strong&gt;: Combining oriented edges with ReLU non-linearities creates corner and curve detectors in layer 2, texture and part detectors in layers 3–4, and class-discriminative object prototypes near the top of the network.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-receptive-field-growth-across-three-layers&quot;&gt;Worked example: Receptive Field Growth Across Three Layers&lt;/h3&gt;

&lt;p&gt;Let us compute the exact receptive field size \(r_\ell\) and effective stride (jump) \(j_\ell\) as a signal passes through a three-layer CNN stem:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Layer 1: \(3 \times 3\) conv, stride \(s_1 = 1\)&lt;/li&gt;
  &lt;li&gt;Layer 2: \(3 \times 3\) conv, stride \(s_2 = 2\)&lt;/li&gt;
  &lt;li&gt;Layer 3: \(3 \times 3\) conv, stride \(s_3 = 1\)&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Initialize at the input image (Layer 0)&lt;/strong&gt;:
\(r_0 = 1, \quad j_0 = 1.\)
(Each input pixel sees \(1 \times 1\) pixel, and adjacent pixels are \(1\) pixel apart.)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;After Layer 1 (\(k_1 = 3, s_1 = 1\))&lt;/strong&gt;:
\(r_1 = r_0 + (k_1 - 1) j_0 = 1 + (3 - 1)(1) = 3, \quad j_1 = j_0 \cdot s_1 = 1 \cdot 1 = 1.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;After Layer 2 (\(k_2 = 3, s_2 = 2\))&lt;/strong&gt;:
\(r_2 = r_1 + (k_2 - 1) j_1 = 3 + (3 - 1)(1) = 5, \quad j_2 = j_1 \cdot s_2 = 1 \cdot 2 = 2.\)
Notice that stride \(2\) in Layer 2 does &lt;strong&gt;not&lt;/strong&gt; enlarge \(r_2\) immediately—it doubles the jump \(j_2\) for every subsequent layer!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;After Layer 3 (\(k_3 = 3, s_3 = 1\))&lt;/strong&gt;:
\(r_3 = r_2 + (k_3 - 1) j_2 = 5 + (3 - 1)(2) = 9, \quad j_3 = j_2 \cdot s_3 = 2 \cdot 1 = 2.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Key Insight&lt;/strong&gt;: A single activation after Layer 3 integrates a \(9 \times 9\) input patch—nearly matching a giant \(9 \times 9\) kernel (\(81\) weights per channel) while using only \(3 \times 9 = 27\) spatial weights per channel and inserting two non-linearities along the way.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;h3 id=&quot;example-1-edge-detection-hand-crafted-filters&quot;&gt;Example 1: Edge Detection (Hand-Crafted Filters)&lt;/h3&gt;

&lt;p&gt;Before deep learning, computer vision relied on hand-crafted filters. Understanding these helps build intuition for what CNNs learn automatically.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Vertical edge detector&lt;/strong&gt; (Sobel-like):&lt;/p&gt;

\[K_{vertical} = \begin{bmatrix} 1 &amp;amp; 0 &amp;amp; -1 \\ 2 &amp;amp; 0 &amp;amp; -2 \\ 1 &amp;amp; 0 &amp;amp; -1 \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Why it works&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Left column has positive weights → measures brightness on the left&lt;/li&gt;
  &lt;li&gt;Right column has negative weights → measures brightness on the right&lt;/li&gt;
  &lt;li&gt;If left is bright and right is dark: large positive output (edge!)&lt;/li&gt;
  &lt;li&gt;If uniform: positive and negative cancel → output near zero&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Horizontal edge detector&lt;/strong&gt;:&lt;/p&gt;

\[K_{horizontal} = \begin{bmatrix} 1 &amp;amp; 2 &amp;amp; 1 \\ 0 &amp;amp; 0 &amp;amp; 0 \\ -1 &amp;amp; -2 &amp;amp; -1 \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Worked example&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input image&lt;/strong&gt; (simulating a vertical edge):
\(I = \begin{bmatrix} 
100 &amp;amp; 100 &amp;amp; 100 &amp;amp; 0 &amp;amp; 0 \\
100 &amp;amp; 100 &amp;amp; 100 &amp;amp; 0 &amp;amp; 0 \\
100 &amp;amp; 100 &amp;amp; 100 &amp;amp; 0 &amp;amp; 0 \\
100 &amp;amp; 100 &amp;amp; 100 &amp;amp; 0 &amp;amp; 0 \\
100 &amp;amp; 100 &amp;amp; 100 &amp;amp; 0 &amp;amp; 0
\end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Applying vertical edge kernel at position (1,1)&lt;/strong&gt;:&lt;/p&gt;

\[\begin{align}
S[1,1] &amp;amp;= (100 \times 1) + (100 \times 0) + (100 \times -1) \\
&amp;amp;+ (100 \times 2) + (100 \times 0) + (100 \times -2) \\
&amp;amp;+ (100 \times 1) + (100 \times 0) + (100 \times -1) \\
&amp;amp;= 100 - 100 + 200 - 200 + 100 - 100 = 0
\end{align}\]

&lt;p&gt;&lt;strong&gt;At position (1,2)&lt;/strong&gt; (on the edge):&lt;/p&gt;

\[\begin{align}
S[1,2] &amp;amp;= (100 \times 1) + (100 \times 0) + (0 \times -1) \\
&amp;amp;+ (100 \times 2) + (100 \times 0) + (0 \times -2) \\
&amp;amp;+ (100 \times 1) + (100 \times 0) + (0 \times -1) \\
&amp;amp;= 100 + 0 + 0 + 200 + 0 + 0 + 100 + 0 + 0 = 400
\end{align}\]

&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt;: High activation (400) exactly at the vertical edge location!&lt;/p&gt;

&lt;h3 id=&quot;example-2-how-cnns-build-hierarchical-representations&quot;&gt;Example 2: How CNNs Build Hierarchical Representations&lt;/h3&gt;

&lt;p&gt;One of the most beautiful aspects of CNNs is how they automatically learn hierarchical features:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Layer 1 (Early layers - Simple features)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Oriented edges at various angles&lt;/li&gt;
  &lt;li&gt;Color blobs and gradients&lt;/li&gt;
  &lt;li&gt;Basic textures&lt;/li&gt;
  &lt;li&gt;Example filters: \(\begin{bmatrix} -1 &amp;amp; 0 &amp;amp; 1 \\ -1 &amp;amp; 0 &amp;amp; 1 \\ -1 &amp;amp; 0 &amp;amp; 1 \end{bmatrix}\), \(\begin{bmatrix} 1 &amp;amp; 1 &amp;amp; 1 \\ 0 &amp;amp; 0 &amp;amp; 0 \\ -1 &amp;amp; -1 &amp;amp; -1 \end{bmatrix}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Layer 2-3 (Middle layers - Parts)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Corners (combinations of edges meeting)&lt;/li&gt;
  &lt;li&gt;Simple shapes (curves, circles, rectangles)&lt;/li&gt;
  &lt;li&gt;Textures (repeated patterns of edges)&lt;/li&gt;
  &lt;li&gt;Grid patterns, stripes, spots&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Layer 4-5 (Deeper layers - Object parts)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Eyes, noses, ears (for face recognition)&lt;/li&gt;
  &lt;li&gt;Wheels, windows, headlights (for car recognition)&lt;/li&gt;
  &lt;li&gt;Petals, leaves, stems (for flower recognition)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Final layers (High-level - Objects)&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Complete faces from different angles&lt;/li&gt;
  &lt;li&gt;Full car shapes&lt;/li&gt;
  &lt;li&gt;Entire animals&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;This hierarchy emerges automatically from training&lt;/strong&gt; — the network discovers that edges are useful for building corners, corners for building shapes, and shapes for building objects. This mirrors how neuroscientists believe the visual cortex processes information.&lt;/p&gt;

&lt;h3 id=&quot;example-3-receptive-field-growth&quot;&gt;Example 3: Receptive Field Growth&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Receptive field&lt;/strong&gt; is the region of the input image that influences a single output neuron.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Single 3×3 conv layer&lt;/strong&gt;: Each output pixel “sees” a 3×3 region of the input.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Stack of two 3×3 conv layers&lt;/strong&gt;: Each output pixel in layer 2 sees a 3×3 region of layer 1’s output. But each pixel in that 3×3 region sees a 3×3 region of the input. Combined: the layer 2 output sees a &lt;strong&gt;5×5&lt;/strong&gt; region of the original input.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Formula for receptive field with \(n\) layers of 3×3 convolutions&lt;/strong&gt;:&lt;/p&gt;

\[RF = 1 + 2n\]

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Layers&lt;/th&gt;
      &lt;th&gt;Receptive Field&lt;/th&gt;
      &lt;th&gt;Equivalent Single Kernel&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;3×3&lt;/td&gt;
      &lt;td&gt;3×3&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;5×5&lt;/td&gt;
      &lt;td&gt;5×5&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;3&lt;/td&gt;
      &lt;td&gt;7×7&lt;/td&gt;
      &lt;td&gt;7×7&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;5&lt;/td&gt;
      &lt;td&gt;11×11&lt;/td&gt;
      &lt;td&gt;11×11&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;10&lt;/td&gt;
      &lt;td&gt;21×21&lt;/td&gt;
      &lt;td&gt;21×21&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Why stack small filters instead of using one large filter?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Compare: Three 3×3 layers vs one 7×7 layer&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Metric&lt;/th&gt;
      &lt;th&gt;Three 3×3&lt;/th&gt;
      &lt;th&gt;One 7×7&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Receptive field&lt;/td&gt;
      &lt;td&gt;7×7&lt;/td&gt;
      &lt;td&gt;7×7&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Parameters per channel&lt;/td&gt;
      &lt;td&gt;3×(3×3) = 27&lt;/td&gt;
      &lt;td&gt;7×7 = 49&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Non-linearities&lt;/td&gt;
      &lt;td&gt;3 ReLUs&lt;/td&gt;
      &lt;td&gt;1 ReLU&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;Three stacked 3×3 convolutions have:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Fewer parameters&lt;/strong&gt; (27 vs 49)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;More non-linearity&lt;/strong&gt; (3 ReLUs vs 1)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;More expressive power&lt;/strong&gt; (can represent more complex functions)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This insight from VGGNet (2014) revolutionized CNN architecture design.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, English. Kernels as detectors (edges, then patterns) are the intuition section.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. Shows those detectors on actual image patches.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04-01-01 Convolution Math and Dimensions</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_01_Convolution_Math_and_Dimensions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_01_01_Convolution_Math_and_Dimensions</id>
   <content type="html">&lt;p&gt;Every deep learning practitioner eventually hits a moment of quiet panic when a PyTorch training script crashes with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RuntimeError: mat1 and mat2 shapes cannot be multiplied&lt;/code&gt;—almost always traced back to a single miscalculated padding, stride, or dilation term three convolutional layers earlier. Beneath the intuitive “sliding window” metaphor lies an exact discrete calculus of index arithmetic, tensor contractions, and cross-correlation algebra. Mastering the exact math of output dimensions, multi-channel summation, and parameter counts turns architecture design from guesswork into deterministic engineering.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-the-mathematical-machinery-of-2d-convolution&quot;&gt;Key ideas: The Mathematical Machinery of 2D Convolution&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Discrete Cross-Correlation vs. True Convolution&lt;/strong&gt;: In signal processing, convolution flips the kernel by \(180^\circ\) so the operator is commutative and associative (\((f * g) * h = f * (g * h)\)). Deep learning libraries implement &lt;strong&gt;cross-correlation&lt;/strong&gt; without flipping because learned weights absorb any orientation flip during training, avoiding unnecessary memory reversals.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Tensor Contraction Across Input Channels&lt;/strong&gt;: A 2D convolutional filter is actually a &lt;strong&gt;3D tensor&lt;/strong&gt; of shape \((C_{\text{in}}, k_H, k_W)\). At each spatial location \((i, j)\), it performs a full inner product across all \(C_{\text{in}}\) channels simultaneously, collapsing depth into a single scalar before moving to the next output channel.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Discrete Sampling Geometry (Padding, Stride, Dilation)&lt;/strong&gt;: Zero-padding \(p\) controls boundary shrinkage, stride \(s\) sets the subsampling lattice spacing, and dilation \(d\) inserts \((d-1)\) zeros between kernel taps, giving an effective kernel span of \(k_{\text{eff}} = d(k - 1) + 1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Computational Complexity (FLOPs vs. Parameters)&lt;/strong&gt;: Parameter count depends only on \((C_{\text{out}}, C_{\text{in}}, k_H, k_W)\), whereas multiply-accumulate operations (MACs) scale with the spatial output area \(H_{\text{out}} \times W_{\text{out}}\)—explaining why early high-resolution layers have few parameters but dominate compute.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-multi-channel-cross-correlation-and-output-shape&quot;&gt;Worked example: Multi-Channel Cross-Correlation and Output Shape&lt;/h3&gt;

&lt;p&gt;Consider a 2-channel \(4 \times 4\) input tensor \(X \in \mathbb{R}^{2 \times 4 \times 4}\) processed by a single filter \(K \in \mathbb{R}^{2 \times 3 \times 3}\) with padding \(p = 0\), stride \(s = 1\), dilation \(d = 1\), and bias \(b = 0.5\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the exact output spatial dimensions&lt;/strong&gt;:
\(H_{\text{out}} = \left\lfloor \frac{4 + 2(0) - 1(3 - 1) - 1}{1} \right\rfloor + 1 = \left\lfloor \frac{1}{1} \right\rfloor + 1 = 2, \quad W_{\text{out}} = 2.\)
So the output feature map \(Y\) has shape \((1, 2, 2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Focus on the top-left \(3 \times 3\) patch of each input channel&lt;/strong&gt;:
Suppose channel 0’s top-left \(3 \times 3\) patch is \(X_0[0:3, 0:3] = \begin{bmatrix} 1 &amp;amp; 2 &amp;amp; 0 \\ 0 &amp;amp; 1 &amp;amp; 3 \\ 2 &amp;amp; 1 &amp;amp; 0 \end{bmatrix}\) with kernel \(K_0 = \begin{bmatrix} 1 &amp;amp; 0 &amp;amp; -1 \\ 1 &amp;amp; 0 &amp;amp; -1 \\ 1 &amp;amp; 0 &amp;amp; -1 \end{bmatrix}\), and channel 1’s top-left patch is \(X_1[0:3, 0:3] = \begin{bmatrix} 2 &amp;amp; 0 &amp;amp; 1 \\ 1 &amp;amp; 1 &amp;amp; 1 \\ 0 &amp;amp; 2 &amp;amp; 0 \end{bmatrix}\) with kernel \(K_1 = \begin{bmatrix} 0 &amp;amp; 1 &amp;amp; 0 \\ 1 &amp;amp; 1 &amp;amp; 1 \\ 0 &amp;amp; 1 &amp;amp; 0 \end{bmatrix}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate the channel-wise Frobenius inner products&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Channel 0:
\(\langle X_0, K_0 \rangle = (1\cdot 1 + 2\cdot 0 + 0\cdot(-1)) + (0\cdot 1 + 1\cdot 0 + 3\cdot(-1)) + (2\cdot 1 + 1\cdot 0 + 0\cdot(-1)) = 1 - 3 + 2 = 0.\)&lt;/li&gt;
      &lt;li&gt;Channel 1:
\(\langle X_1, K_1 \rangle = (0\cdot 2 + 1\cdot 0 + 0\cdot 1) + (1\cdot 1 + 1\cdot 1 + 1\cdot 1) + (0\cdot 0 + 1\cdot 2 + 0\cdot 0) = 0 + 3 + 2 = 5.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sum across channels and add bias&lt;/strong&gt;:
\(Y[0, 0, 0] = 0 + 5 + 0.5 = 5.5.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter and MAC count for this layer&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Parameters: \(1 \times (2 \times 3 \times 3 + 1) = 19\).&lt;/li&gt;
      &lt;li&gt;Multiply-adds across all \(2 \times 2 = 4\) output positions: \(4 \times (2 \times 9) = 72\) MACs.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;convolutional-layers-building-blocks-of-computer-vision&quot;&gt;Convolutional Layers: Building Blocks of Computer Vision&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv1.jpg&quot; alt=&quot;CNN&quot; /&gt;
&lt;em&gt;Overview of Convolutional Neural Network (CNN) architecture. Source: AnalyticsVidhya&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Convolutional layers&lt;/strong&gt; are specialized neural network layers designed for processing grid-like data, especially images. Instead of connecting every input to every neuron (fully connected), convolutional layers use small, learnable filters that slide across the input to detect local patterns.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why CNNs matter&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Parameter efficiency&lt;/strong&gt;: Millions fewer parameters than fully connected networks&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Translation invariance&lt;/strong&gt;: Detects features regardless of their position in the image&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hierarchical learning&lt;/strong&gt;: Learns low-level → mid-level → high-level features automatically&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;State-of-the-art&lt;/strong&gt;: Best performance on virtually all vision tasks&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Key insight&lt;/strong&gt;: Images have spatial structure — nearby pixels are related. Convolutional layers exploit this structure through &lt;strong&gt;local connectivity&lt;/strong&gt; and &lt;strong&gt;parameter sharing&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Analogy&lt;/strong&gt;: Think of convolution as sliding a magnifying glass (filter) across an image to find specific patterns (edges, textures, shapes). Each filter specializes in detecting one type of pattern, and you use the same magnifying glass everywhere on the image rather than having a different one for each location.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv2.jpg&quot; alt=&quot;CNN&quot; /&gt;
&lt;em&gt;Overview of Convolutional Neural Network (CNN) architecture. Source: AnalyticsVidhya&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;the-biological-inspiration&quot;&gt;The Biological Inspiration&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv3.jpg&quot; alt=&quot;CNN Inspiration from Human Eye&quot; /&gt;
&lt;em&gt;CNNs were directly inspired by how the human brain processes visual information. Your eye detects edges first, then combines them into shapes, then matches patterns to memory. A CNN does the exact same thing. Source: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In 1959, neurophysiologists David Hubel and Torsten Wiesel discovered that neurons in the visual cortex respond to specific patterns in localized regions of the visual field (called “receptive fields”). Some neurons respond to edges at certain orientations, others to motion in particular directions. This hierarchical processing — from simple features to complex objects — directly inspired the design of convolutional neural networks.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;h3 id=&quot;understanding-convolution-vs-cross-correlation&quot;&gt;Understanding Convolution vs Cross-Correlation&lt;/h3&gt;

&lt;p&gt;This is a critical distinction that often confuses newcomers. Let’s carefully understand both operations.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://miro.medium.com/v2/resize:fit:1400/1*Zx-ZMLKab7VOCQTxdZ1OAw.gif&quot; alt=&quot;Convolution Operation&quot; /&gt;
&lt;em&gt;Illustration of 2D convolution operation on an image. Source: Medium&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv4.jpg&quot; alt=&quot;The Convolution Filter Sliding&quot; /&gt;
&lt;em&gt;A small window called a filter slides across the image, scanning every patch. At each position it asks: “Is this feature here?” Different filters detect different patterns — edges, blur, sharpness. A CNN learns hundreds of these filters automatically during training. Source: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;h4 id=&quot;true-convolution-signal-processing-definition&quot;&gt;True Convolution (Signal Processing Definition)&lt;/h4&gt;

&lt;p&gt;In signal processing and mathematics, &lt;strong&gt;true convolution&lt;/strong&gt; involves &lt;strong&gt;flipping the kernel&lt;/strong&gt; (rotating 180°) before sliding it across the input. For a 2D image \(I\) and kernel \(K\):&lt;/p&gt;

\[(I * K)[i,j] = \sum_{m=0}^{k-1}\sum_{n=0}^{k-1} I[m, n] \cdot K[i-m, j-n]\]

&lt;p&gt;For finite, discrete signals with a kernel of size \(k \times k\):&lt;/p&gt;

\[(I * K)[i,j] = \sum_{m=0}^{k-1}\sum_{n=0}^{k-1} I[i-m, j-n] \cdot K[m,n]\]

&lt;p&gt;The key property here is the &lt;strong&gt;subtraction&lt;/strong&gt; in the indices (\(i-m, j-n\)), which effectively flips the kernel.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why does convolution flip the kernel?&lt;/strong&gt; Convolution was originally designed to describe how systems respond to inputs over time. The flipping ensures that convolution is:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Commutative&lt;/strong&gt;: \(I * K = K * I\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Associative&lt;/strong&gt;: \((I * K_1) * K_2 = I * (K_1 * K_2)\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These properties are essential in signal processing for analyzing linear time-invariant systems.&lt;/p&gt;

&lt;h4 id=&quot;cross-correlation-what-deep-learning-actually-uses&quot;&gt;Cross-Correlation (What Deep Learning Actually Uses)&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Cross-correlation&lt;/strong&gt; is similar but &lt;strong&gt;without the kernel flip&lt;/strong&gt;:&lt;/p&gt;

\[S[i,j] = \sum_{m=0}^{k-1}\sum_{n=0}^{k-1} I[i+m, j+n] \cdot K[m,n]\]

&lt;p&gt;Notice the &lt;strong&gt;addition&lt;/strong&gt; in the indices (\(i+m, j+n\)) — we simply slide the kernel as-is across the image.&lt;/p&gt;

&lt;h4 id=&quot;visual-comparison-convolution-vs-cross-correlation&quot;&gt;Visual Comparison: Convolution vs Cross-Correlation&lt;/h4&gt;

&lt;p&gt;Let’s make this concrete with an example:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kernel&lt;/strong&gt; \(K\):
\(K = \begin{bmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 4 &amp;amp; 5 &amp;amp; 6 \\ 7 &amp;amp; 8 &amp;amp; 9 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Flipped kernel&lt;/strong&gt; (for true convolution):
\(K_{flipped} = \begin{bmatrix} 9 &amp;amp; 8 &amp;amp; 7 \\ 6 &amp;amp; 5 &amp;amp; 4 \\ 3 &amp;amp; 2 &amp;amp; 1 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For a symmetric kernel&lt;/strong&gt; (like many edge detectors):
\(K = \begin{bmatrix} 1 &amp;amp; 0 &amp;amp; -1 \\ 1 &amp;amp; 0 &amp;amp; -1 \\ 1 &amp;amp; 0 &amp;amp; -1 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Flipping this kernel gives:
\(K_{flipped} = \begin{bmatrix} -1 &amp;amp; 0 &amp;amp; 1 \\ -1 &amp;amp; 0 &amp;amp; 1 \\ -1 &amp;amp; 0 &amp;amp; 1 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Notice that the flipped version detects edges in the &lt;strong&gt;opposite direction&lt;/strong&gt;!&lt;/p&gt;

&lt;h4 id=&quot;why-deep-learning-uses-cross-correlation-and-calls-it-convolution&quot;&gt;Why Deep Learning Uses Cross-Correlation (and Calls it “Convolution”)&lt;/h4&gt;

&lt;p&gt;Here’s the crucial insight: &lt;strong&gt;In deep learning, we don’t care about the flip because the kernel weights are learned&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Consider this reasoning:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;If we used true convolution&lt;/strong&gt;: The network would learn weights \(W\), and apply them flipped during the forward pass&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;If we use cross-correlation&lt;/strong&gt;: The network learns weights \(W&apos;\), applied without flipping&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Since the network learns the weights from data anyway, \(W&apos;\) simply learns to be the flipped version of what \(W\) would have been. &lt;strong&gt;The network will learn the same function either way&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Benefits of using cross-correlation&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Simpler implementation&lt;/strong&gt;: No need to flip the kernel&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;More intuitive&lt;/strong&gt;: The kernel “template” directly matches the pattern it detects&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Same learning capacity&lt;/strong&gt;: The network can learn any function regardless&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Historical note&lt;/strong&gt;: The deep learning community adopted the term “convolution” even though we technically use cross-correlation. This is now standard terminology, but understanding the distinction helps when reading signal processing literature or implementing custom operations.&lt;/p&gt;

&lt;h3 id=&quot;step-by-step-convolution-example&quot;&gt;Step-by-Step Convolution Example&lt;/h3&gt;

&lt;p&gt;Let’s trace through a complete example to solidify understanding:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input image&lt;/strong&gt; \(I\) (5×5):
\(I = \begin{bmatrix} 
1 &amp;amp; 2 &amp;amp; 3 &amp;amp; 0 &amp;amp; 1 \\
0 &amp;amp; 1 &amp;amp; 2 &amp;amp; 3 &amp;amp; 1 \\
1 &amp;amp; 2 &amp;amp; 1 &amp;amp; 0 &amp;amp; 0 \\
0 &amp;amp; 1 &amp;amp; 2 &amp;amp; 3 &amp;amp; 2 \\
2 &amp;amp; 1 &amp;amp; 0 &amp;amp; 1 &amp;amp; 1
\end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Kernel&lt;/strong&gt; \(K\) (3×3):
\(K = \begin{bmatrix} 
1 &amp;amp; 0 &amp;amp; -1 \\
1 &amp;amp; 0 &amp;amp; -1 \\
1 &amp;amp; 0 &amp;amp; -1
\end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Computing output at position (0,0)&lt;/strong&gt; using cross-correlation:&lt;/p&gt;

&lt;p&gt;We extract the 3×3 region starting at (0,0):
\(\text{region} = \begin{bmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 0 &amp;amp; 1 &amp;amp; 2 \\ 1 &amp;amp; 2 &amp;amp; 1 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Element-wise multiply and sum:
\(\begin{align}
S[0,0] &amp;amp;= (1 \times 1) + (2 \times 0) + (3 \times -1) \\
&amp;amp;+ (0 \times 1) + (1 \times 0) + (2 \times -1) \\
&amp;amp;+ (1 \times 1) + (2 \times 0) + (1 \times -1) \\
&amp;amp;= 1 + 0 - 3 + 0 + 0 - 2 + 1 + 0 - 1 \\
&amp;amp;= -4
\end{align}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Computing output at position (0,1)&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Region starting at (0,1):
\(\text{region} = \begin{bmatrix} 2 &amp;amp; 3 &amp;amp; 0 \\ 1 &amp;amp; 2 &amp;amp; 3 \\ 2 &amp;amp; 1 &amp;amp; 0 \end{bmatrix}\)&lt;/p&gt;

\[\begin{align}
S[0,1] &amp;amp;= (2 \times 1) + (3 \times 0) + (0 \times -1) \\
&amp;amp;+ (1 \times 1) + (2 \times 0) + (3 \times -1) \\
&amp;amp;+ (2 \times 1) + (1 \times 0) + (0 \times -1) \\
&amp;amp;= 2 + 0 + 0 + 1 + 0 - 3 + 2 + 0 + 0 \\
&amp;amp;= 2
\end{align}\]

&lt;p&gt;Continue this process for all valid positions to get the complete output.&lt;/p&gt;

&lt;h3 id=&quot;multi-channel-convolution&quot;&gt;Multi-Channel Convolution&lt;/h3&gt;

&lt;p&gt;Real images have multiple channels (RGB has 3, intermediate CNN layers can have 64, 128, 256, or more). Here’s how convolution extends:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For an input with \(C_{in}\) channels&lt;/strong&gt; (e.g., \(H \times W \times C_{in}\)) and a &lt;strong&gt;filter of size \(k \times k \times C_{in}\)&lt;/strong&gt;:&lt;/p&gt;

\[S[i,j] = \sum_{c=0}^{C_{in}-1} \sum_{m=0}^{k-1}\sum_{n=0}^{k-1} I[i+m, j+n, c] \cdot K[m,n,c] + b\]

&lt;p&gt;Where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(C_{in}\): number of input channels (3 for RGB)&lt;/li&gt;
  &lt;li&gt;\(b\): bias term (one scalar per filter)&lt;/li&gt;
  &lt;li&gt;Each filter produces &lt;strong&gt;one&lt;/strong&gt; output channel&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;To produce \(C_{out}\) output channels&lt;/strong&gt;, we need \(C_{out}\) filters, each of size \(k \times k \times C_{in}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Visual intuition&lt;/strong&gt;: For an RGB image, each filter is actually a 3D block (e.g., 3×3×3). The filter has separate weights for each color channel, and they’re all summed together to produce one output value. This allows the filter to learn color-specific patterns (e.g., detecting blue sky vs. green grass).&lt;/p&gt;

&lt;h3 id=&quot;output-dimensions-formula&quot;&gt;Output Dimensions Formula&lt;/h3&gt;

&lt;p&gt;Understanding how input dimensions transform through convolutional layers is essential for designing architectures.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Given&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Input size: \(H_{in} \times W_{in}\)&lt;/li&gt;
  &lt;li&gt;Kernel size: \(k \times k\)&lt;/li&gt;
  &lt;li&gt;Stride: \(s\) (how many pixels to move between positions)&lt;/li&gt;
  &lt;li&gt;Padding: \(p\) (zeros added around the border)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Output size&lt;/strong&gt;:&lt;/p&gt;

\[H_{out} = \left\lfloor \frac{H_{in} + 2p - k}{s} \right\rfloor + 1\]

\[W_{out} = \left\lfloor \frac{W_{in} + 2p - k}{s} \right\rfloor + 1\]

&lt;p&gt;&lt;strong&gt;Common configurations&lt;/strong&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Config&lt;/th&gt;
      &lt;th&gt;Purpose&lt;/th&gt;
      &lt;th&gt;Formula Result&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;\(k=3, s=1, p=1\)&lt;/td&gt;
      &lt;td&gt;“Same” padding&lt;/td&gt;
      &lt;td&gt;\(n_{out} = n_{in}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(k=3, s=2, p=1\)&lt;/td&gt;
      &lt;td&gt;Downsample by 2&lt;/td&gt;
      &lt;td&gt;\(n_{out} = \lceil n_{in}/2 \rceil\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(k=1, s=1, p=0\)&lt;/td&gt;
      &lt;td&gt;1×1 convolution&lt;/td&gt;
      &lt;td&gt;\(n_{out} = n_{in}\)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;\(k=7, s=2, p=3\)&lt;/td&gt;
      &lt;td&gt;Aggressive downsample&lt;/td&gt;
      &lt;td&gt;\(n_{out} = \lceil n_{in}/2 \rceil\)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;parameter-count-analysis&quot;&gt;Parameter Count Analysis&lt;/h3&gt;

&lt;p&gt;For a convolutional layer:&lt;/p&gt;

\[\text{Parameters} = (k \times k \times C_{in}) \times C_{out} + C_{out}\]

&lt;p&gt;The first term is the weights (each filter has \(k \times k \times C_{in}\) weights, and we have \(C_{out}\) filters). The second term is the biases (one per output channel).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example calculation&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Input: \(32 \times 32 \times 3\) (CIFAR-10 RGB image)&lt;/li&gt;
  &lt;li&gt;Filter: \(3 \times 3\), 64 filters&lt;/li&gt;
  &lt;li&gt;Parameters: \((3 \times 3 \times 3) \times 64 + 64 = 27 \times 64 + 64 = 1,792\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Compare to fully connected layer&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Input: \(32 \times 32 \times 3 = 3,072\) neurons&lt;/li&gt;
  &lt;li&gt;Output: 64 neurons&lt;/li&gt;
  &lt;li&gt;Parameters: \(3,072 \times 64 + 64 = 196,672\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Reduction factor&lt;/strong&gt;: \(196,672 / 1,792 \approx 110\times\) fewer parameters!&lt;/p&gt;

&lt;p&gt;This massive reduction comes from two properties:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Local connectivity&lt;/strong&gt;: Each output only connects to a small region of input&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter sharing&lt;/strong&gt;: Same filter weights used at all spatial locations&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, English. The sum that defines a convolution.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, English. Output height and width as functions of kernel, padding, and stride are derived in this lecture.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HGwBXDKFk9I&quot;&gt;Neural Networks Part 8: Image Classification with Convolutional Neural Networks (CNNs)&lt;/a&gt; — StatQuest with Josh Starmer, English. Numbers on a tiny image so the dimension formula is checkable by hand.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>04 Introduction to Convolutional Neural Networks</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter04/04_00_Introduction</id>
   <content type="html">&lt;p&gt;Picture a single high-resolution photograph from a modern smartphone: \(224 \times 224 \times 3\) pixels, already downsampled for ImageNet, yet still a vector of \(150{,}528\) raw numbers. If you feed that flattened vector into a vanilla multilayer perceptron whose very first hidden layer has just \(1{,}000\) neurons, that single layer demands over \(150\) million weights—before the network has even learned to tell a vertical edge from random sensor noise. Worse still, shifting a cat three pixels to the left scrambles every single input index, forcing a dense network to relearn the entire visual concept of “cat” at every pixel coordinate from scratch. Convolutional Neural Networks (CNNs) broke this combinatorial wall by encoding two physical symmetries of visual space directly into the linear algebra of the layer: &lt;strong&gt;locality&lt;/strong&gt; and &lt;strong&gt;translation equivariance&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;key-ideas-why-convolutional-inductive-biases-work&quot;&gt;Key ideas: Why Convolutional Inductive Biases Work&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Linear Algebra of Structured Matrices (Toeplitz &amp;amp; Doubly Block-Circulant Operators)&lt;/strong&gt;: A 2D convolution is not an exotic non-linear trick—it is a sparse, weight-tied linear map whose matrix representation has repeated diagonals. Understanding convolution as a constrained subspace of all linear maps clarifies why CNNs slash parameter counts by orders of magnitude while remaining differentiable via standard backpropagation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Signal Processing &amp;amp; Spatial Filtering&lt;/strong&gt;: Long before deep learning, computer vision engineers designed Sobel, Laplacian, and Gabor kernels to measure intensity gradients and local frequencies. CNNs inherit this exact sliding-window operator but replace hand-engineered filter taps with learnable tensors discovered end-to-end by stochastic gradient descent.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Group Equivariance &amp;amp; Symmetry&lt;/strong&gt;: Translating an input image by \((\Delta x, \Delta y)\) translates the resulting feature map by the same shift (up to boundary effects). This equivariance means a single learned edge or eye detector automatically fires anywhere in the visual field, turning sample efficiency from impossible to routine.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hierarchical Compositionality&lt;/strong&gt;: Natural scenes are compositional—pixels form edges, edges form motifs and textures, motifs form object parts, and parts assemble into objects. Stacking small local convolutions grows the effective receptive field linearly with depth, mirroring the ventral visual stream from V1 to IT cortex.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;worked-example-dense-layer-vs-convolutional-layer-parameter-budget&quot;&gt;Worked example: Dense Layer vs. Convolutional Layer Parameter Budget&lt;/h3&gt;

&lt;p&gt;Suppose we process a \(32 \times 32 \times 3\) RGB image (like CIFAR-10) and want an output representation with \(16\) feature channels of spatial size \(32 \times 32\) (so \(32 \times 32 \times 16 = 16{,}384\) output activations).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Fully connected (dense) layer cost&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Input dimension: \(D_{\text{in}} = 32 \times 32 \times 3 = 3{,}072\).&lt;/li&gt;
      &lt;li&gt;Output dimension: \(D_{\text{out}} = 32 \times 32 \times 16 = 16{,}384\).&lt;/li&gt;
      &lt;li&gt;Total parameters (weights + biases):
\(P_{\text{dense}} = 3{,}072 \times 16{,}384 + 16{,}384 = 50{,}331{,}648 + 16{,}384 = 50{,}348{,}032.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convolutional layer cost (\(3 \times 3\) kernel, padding \(p=1\), stride \(s=1\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Each of the \(16\) filters spans \(3 \times 3 \times 3 = 27\) weights plus \(1\) scalar bias.&lt;/li&gt;
      &lt;li&gt;Total parameters:
\(P_{\text{conv}} = 16 \times (3 \times 3 \times 3 + 1) = 16 \times 28 = 448.\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compression ratio&lt;/strong&gt;:
\(\frac{P_{\text{dense}}}{P_{\text{conv}}} = \frac{50{,}348{,}032}{448} = 112{,}384\times.\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;: Both layers produce the exact same \(32 \times 32 \times 16\) output tensor shape, yet the convolutional layer achieves a \(&amp;gt;10^5\times\) parameter reduction by tying weights across spatial locations and restricting each output neuron to a \(3 \times 3\) local neighborhood.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;introduction-to-convolutional-neural-networks&quot;&gt;Introduction to Convolutional Neural Networks&lt;/h1&gt;

&lt;p&gt;Convolutional Neural Networks (CNNs) are specialized neural networks designed for processing &lt;strong&gt;grid-like data&lt;/strong&gt;, especially images. They are the foundation of modern computer vision, powering applications from image classification to autonomous driving, medical diagnosis to facial recognition.&lt;/p&gt;

&lt;p&gt;This chapter introduces the fundamental concepts of CNNs: why we need them, how they work, and the key innovations that made them successful. By the end, you’ll understand the building blocks that compose every modern vision model.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;why-cnns-the-problem-with-fully-connected-networks&quot;&gt;Why CNNs? The Problem with Fully Connected Networks&lt;/h2&gt;

&lt;p&gt;Consider a small 224×224 RGB image — the standard input size for ImageNet. This single image has:&lt;/p&gt;

\[224 \times 224 \times 3 = 150,528 \text{ pixels}\]

&lt;p&gt;If we connected this directly to a hidden layer of 1000 neurons:&lt;/p&gt;

\[150,528 \times 1000 = 150,528,000 \text{ parameters}\]

&lt;p&gt;That’s &lt;strong&gt;150 million parameters&lt;/strong&gt; for just the first layer! This approach has three fatal flaws:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Computational explosion&lt;/strong&gt;: Too many parameters to train efficiently&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;No spatial awareness&lt;/strong&gt;: The network treats pixels as independent, ignoring spatial relationships&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;No translation invariance&lt;/strong&gt;: A cat in the top-left is unrelated to a cat in the bottom-right&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;CNNs solve all three problems through two key ideas: &lt;strong&gt;local connectivity&lt;/strong&gt; and &lt;strong&gt;parameter sharing&lt;/strong&gt;.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;cnn-overview&quot;&gt;CNN Overview&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv.jpg&quot; alt=&quot;CNN Pipeline Overview&quot; /&gt;
&lt;em&gt;Overview of Convolutional Neural Networks: The deep learning model that taught machines to recognize images. CNNs process images through a series of convolutional and pooling layers, extracting increasingly complex features until a final classifier makes a prediction. Source: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;A CNN consists of:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Convolutional layers&lt;/strong&gt;: Extract local features using learnable filters&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pooling layers&lt;/strong&gt;: Downsample feature maps, adding translation invariance&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Activation functions&lt;/strong&gt;: Add non-linearity (typically ReLU)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Fully connected layers&lt;/strong&gt;: Combine features for final classification (at the end)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The key insight: instead of learning a separate weight for every input pixel, CNNs learn &lt;strong&gt;small filters&lt;/strong&gt; (typically 3×3 or 5×5) that slide across the entire image. This dramatically reduces parameters while exploiting spatial structure.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;where-cnns-fit-in-the-ai-landscape&quot;&gt;Where CNNs Fit in the AI Landscape&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv1.jpg&quot; alt=&quot;AI/ML/DL Hierarchy&quot; /&gt;
&lt;em&gt;CNNs are a specialized type of deep learning model designed specifically for visual data — images, videos, and anything pixel-based. They represent one branch of the deep learning family tree, alongside RNNs for sequences and Transformers for attention-based processing. Source: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Historical context&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;1989&lt;/strong&gt;: Yann LeCun proposes backpropagation for CNNs&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;1998&lt;/strong&gt;: LeNet-5 achieves digit recognition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2012&lt;/strong&gt;: AlexNet wins ImageNet, sparking the deep learning revolution&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2015&lt;/strong&gt;: ResNet achieves superhuman performance&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;2020+&lt;/strong&gt;: CNNs combined with Transformers (Vision Transformers, ConvNeXt)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;what-exactly-is-a-cnn&quot;&gt;What Exactly is a CNN?&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter04/conv2.jpg&quot; alt=&quot;What is a CNN&quot; /&gt;
&lt;em&gt;A CNN looks at small patches at a time, just like your eyes do. This allows it to preserve spatial structure, detect features regardless of their position, and build up complex representations from simple ones. Each convolutional filter acts like a specialized feature detector. Source: Analytics Vidhya&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Core concepts&lt;/strong&gt;:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Concept&lt;/th&gt;
      &lt;th&gt;Description&lt;/th&gt;
      &lt;th&gt;Benefit&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Local connectivity&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Each neuron connects only to a small region&lt;/td&gt;
      &lt;td&gt;Fewer parameters&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Parameter sharing&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Same filter weights used everywhere&lt;/td&gt;
      &lt;td&gt;Translation invariance&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Hierarchical features&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Low-level → mid-level → high-level&lt;/td&gt;
      &lt;td&gt;Compositional understanding&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;Pooling&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Downsampling with max/average operations&lt;/td&gt;
      &lt;td&gt;Spatial invariance&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;chapter-roadmap&quot;&gt;Chapter Roadmap&lt;/h2&gt;

&lt;p&gt;This chapter covers:&lt;/p&gt;

&lt;h3 id=&quot;04-01-convolutional-layers&quot;&gt;04-01: Convolutional Layers&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;The convolution operation and cross-correlation&lt;/li&gt;
  &lt;li&gt;Multi-channel convolution&lt;/li&gt;
  &lt;li&gt;Output dimensions and parameter counting&lt;/li&gt;
  &lt;li&gt;Edge detection and feature hierarchies&lt;/li&gt;
  &lt;li&gt;NumPy and PyTorch implementations&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;04-02-pooling-layers-and-cnn-architectures&quot;&gt;04-02: Pooling Layers and CNN Architectures&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Max pooling, average pooling, global average pooling&lt;/li&gt;
  &lt;li&gt;Classic architectures: LeNet, AlexNet, VGG, ResNet&lt;/li&gt;
  &lt;li&gt;Residual connections and why depth matters&lt;/li&gt;
  &lt;li&gt;Complete CNN implementation&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;prerequisites&quot;&gt;Prerequisites&lt;/h2&gt;

&lt;p&gt;Before diving into CNNs, ensure you understand:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Linear algebra&lt;/strong&gt;: Matrix multiplication, dot products&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Neural network basics&lt;/strong&gt;: Forward/backward propagation, gradient descent&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Activation functions&lt;/strong&gt;: ReLU, softmax&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Loss functions&lt;/strong&gt;: Cross-entropy for classification&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If any of these are unclear, review Chapter 3 (Neural Networks Fundamentals) first.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;key-questions-this-chapter-answers&quot;&gt;Key Questions This Chapter Answers&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;What is convolution?&lt;/strong&gt; And why do we actually use cross-correlation?&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;How do filters detect features?&lt;/strong&gt; From edges to textures to objects&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why are small 3×3 filters better than large ones?&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;How do skip connections enable training 150+ layer networks?&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;What’s the difference between max pooling and average pooling?&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;How do modern architectures like ResNet work?&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s begin with the fundamental operation: the convolutional layer.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After the CNN building blocks, see &lt;strong&gt;04-99 Modern Applications and Updates&lt;/strong&gt; for ConvNeXt, DINOv2, and vision foundation models that still rest on convolution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (interview practice):&lt;/strong&gt; After convolution and architectures, see &lt;strong&gt;04-98 Interviews Practice&lt;/strong&gt; for original CNN geometry / skip-connection drills; full solved Q&amp;amp;A is in &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=KuXjwB4LzSA&quot;&gt;But what is a convolution?&lt;/a&gt; — 3Blue1Brown, English. Convolution as a sliding local mix is why this chapter abandons a fully connected image net.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2xqkSUhmmXU&quot;&gt;MIT 6.S191 (2024): Convolutional Neural Networks&lt;/a&gt; — Alexander Amini, English. MIT’s 2024 CNN lecture is the chapter-length version of that idea.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 5&lt;/td&gt;
          &lt;td&gt;Convolutional Neural Networks](https://www.youtube.com/watch?v=bNb2fEVKeEo) — Stanford University School of Engineering, English. Stanford’s convolution lecture, including the shapes (padding, stride, channels) the roadmap promises.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_99_Modern_Applications</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Mathematically, backpropagation in 2026 is still the exact same chain rule from 1986—yet on modern GPUs, executing it naively can leave 80% of the hardware sitting idle waiting on memory bandwidth. Modern training turns backprop into a compiler and systems problem: kernel fusion, activation checkpointing, mixed precision, and FlashAttention.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-backpropagation-as-a-systems--compiler-problem-20222026&quot;&gt;Key ideas: Backpropagation as a Systems &amp;amp; Compiler Problem (2022–2026)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Graph Compilers (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt; &amp;amp; JAX &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt;)&lt;/strong&gt;: Fuse chains of elementwise ops (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;LayerNorm + GeLU + Dropout&lt;/code&gt;) into single GPU kernels so intermediate tensors stay in fast on-chip SRAM instead of round-tripping through slow HBM.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mixed Precision (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FP16&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BF16&lt;/code&gt;) &amp;amp; Loss Scaling&lt;/strong&gt;: Runs matrix multiplies in 16-bit Tensor Cores while keeping master weights in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FP32&lt;/code&gt;; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FP16&lt;/code&gt; requires dynamic loss scaling to prevent small gradients from underflowing to zero, whereas &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BF16&lt;/code&gt; matches &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FP32&lt;/code&gt;’s exponent range.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Activation Checkpointing (Rematerialization)&lt;/strong&gt;: Discards selected intermediate forward activations to save massive VRAM and recomputes them on the fly during the backward pass—trading ~33% extra compute for up to \(O(\sqrt{L})\) memory reduction.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;IO-Aware Fused Backward Kernels (FlashAttention)&lt;/strong&gt;: Never materializes the \(O(T^2)\) attention matrix in HBM during either forward or backward passes, computing exact softmax gradients tile-by-tile in SRAM.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-quantifying-activation-checkpointing-memory-vs-compute-trade-off&quot;&gt;Worked example: Quantifying Activation Checkpointing Memory vs. Compute Trade-Off&lt;/h3&gt;

&lt;p&gt;Consider a deep network of \(L = 64\) identical layers, where each layer’s cached activation occupies \(M = 100\text{ MB}\) in VRAM and takes \(1\text{ ms}\) for a forward pass and \(2\text{ ms}\) for a backward pass.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Standard Backpropagation (Cache All 64 Layers)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Activation VRAM: \(64 \times 100\text{ MB} = 6{,}400\text{ MB} = 6.4\text{ GB}\).&lt;/li&gt;
      &lt;li&gt;Step time: \(64 \times (1 + 2)\text{ ms} = 192\text{ ms}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sqrt-Checkpointing (Checkpoint Every \(\sqrt{64} = 8\) Layers)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;We store only \(8\) checkpoint boundaries permanently, plus at most \(8\) layers inside the active recomputation segment:
\(\text{Peak VRAM} \approx (8 + 8) \times 100\text{ MB} = 1{,}600\text{ MB} = 1.6\text{ GB} \quad (4\times\text{ memory cut!})\)&lt;/li&gt;
      &lt;li&gt;Compute overhead: every non-checkpoint layer runs one extra forward pass (\(+1\text{ ms}\)) during backprop, so total time is roughly:
\(64 \times (1 + 1 + 2)\text{ ms} = 256\text{ ms} \quad (\text{only } 33\%\text{ slower!})\)
Trading 33% compute for a \(4\times\) (and on 100B-parameter models, \(10\times+\)) memory reduction is what makes long-context training fit on real GPUs.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-backpropagation-as-a-compiler-problem&quot;&gt;Optional: backpropagation as a compiler problem&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace loss-function, gradient-descent, or backpropagation theory. It maps those algorithms onto the compilers and kernels used to train models after 2022.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Backprop is still reverse-mode autodiff of a scalar loss \(\mathcal{L}\). The 2022–2026 story is that &lt;strong&gt;the tape is compiled&lt;/strong&gt;: operators are fused, activations are rematerialized, and mixed precision is the default.&lt;/p&gt;

&lt;h2 id=&quot;1-the-same-chain-rule-a-different-scheduler&quot;&gt;1. The same chain rule, a different scheduler&lt;/h2&gt;

&lt;p&gt;If a layer computes \(\mathbf{y} = f(\mathbf{x}; \theta)\), reverse mode needs \(\frac{\partial \mathcal{L}}{\partial \mathbf{x}}\) and \(\frac{\partial \mathcal{L}}{\partial \theta}\). A compiler (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;, XLA, Triton) decides:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;which intermediates to &lt;strong&gt;keep&lt;/strong&gt; versus &lt;strong&gt;recompute&lt;/strong&gt; (activation checkpointing),&lt;/li&gt;
  &lt;li&gt;which elementwise ops to &lt;strong&gt;fuse&lt;/strong&gt; into one kernel,&lt;/li&gt;
  &lt;li&gt;whether to run in BF16/FP8 with FP32 accumulation.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;That does not change the math of Chapter 03; it changes wall-clock time and memory.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;torchcompile-and-jax-jit&quot;&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt; and JAX &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt;&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2404.14294&quot;&gt;Ansel et al., 2024&lt;/a&gt; describe PyTorch 2’s Dynamo + AOTAutograd + inductor path: Python bytecode is captured into an FX graph, then lowered. JAX does the same idea with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad&lt;/code&gt; composition. Both are production answers to “I wrote backprop by hand in NumPy; how does industry run it?”&lt;/p&gt;

&lt;h3 id=&quot;mixed-precision-and-loss-scaling&quot;&gt;Mixed precision and loss scaling&lt;/h3&gt;

&lt;p&gt;A typical update is&lt;/p&gt;

\[\theta \leftarrow \theta - \eta \cdot \mathrm{Cast}_{fp32}(\widehat{\nabla \mathcal{L}}),\]

&lt;p&gt;where \(\widehat{\nabla \mathcal{L}}\) was computed in BF16/FP16. Overflow is avoided by scaling the loss before the backward pass (native AMP in PyTorch). This is the same SGD/Adam step as the theory notes, with a numeric format policy.&lt;/p&gt;

&lt;h3 id=&quot;kernel-level-backward-for-attention&quot;&gt;Kernel-level backward for attention&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;Dao et al., 2022&lt;/a&gt; (FlashAttention) derive an &lt;strong&gt;IO-aware backward&lt;/strong&gt; that never materializes the full \(N\times N\) attention matrix. The gradients of softmax-attention are identical to the Chapter 07 formulas; the implementation is a fused backward kernel. We point to it here because it is the most famous “backprop engineering” result of the period.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://pytorch.org/&quot;&gt;PyTorch 2&lt;/a&gt; — &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.func&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.utils.checkpoint&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX&lt;/a&gt; — &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;value_and_grad&lt;/code&gt;, XLA.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/triton-lang/triton&quot;&gt;Triton&lt;/a&gt; — write the backward kernel when the compiler is not enough.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2404.14294&quot;&gt;PyTorch 2 (Ansel et al., 2024)&lt;/a&gt; — dynamic graph capture + compiled autograd.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2205.14135&quot;&gt;FlashAttention (Dao et al., 2022)&lt;/a&gt; — exact attention gradients with tiled, IO-aware backward.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1805.02867&quot;&gt;Online normalizer computation for softmax (Milakov &amp;amp; Gimelshein, 2018)&lt;/a&gt; — the streaming softmax used inside those kernels (still the numeric backbone in 2024–2026 code).&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Work the backprop worksheet and the NumPy trainer first. This lesson only answers “what industry added around the tape”: compilers, AMP, and fused backwards — not a new learning rule.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, English. The chain rule did not change; this note’s point is that the scheduler around it did.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JXQT_vxqwIs&quot;&gt;Adam Optimization Algorithm (C2W2L08)&lt;/a&gt; — DeepLearningAI, English. Adam is the default scheduler the note contrasts with plain gradient descent.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NE88eqLngkg&quot;&gt;Optimization for Deep Learning (Momentum, RMSprop, AdaGrad, Adam)&lt;/a&gt; — DeepBean, English. Momentum, RMSProp, AdaGrad, and Adam in one comparison, which is the ‘different scheduler’ claim.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-98 Interviews Practice (autodiff, Hessian, logistic)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_98_Interviews_Practice</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;In deep learning interviews, logistic regression is the favorite microscope: it is tiny enough to derive its gradient and Hessian on a whiteboard in two minutes, yet rich enough to reveal whether you truly understand log-odds, convexity, and forward-vs.-reverse automatic differentiation.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-high-yield-training--autodiff-interview-topics&quot;&gt;Key ideas: High-Yield Training &amp;amp; Autodiff Interview Topics&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Logistic Regression Gradient &amp;amp; Log-Odds&lt;/strong&gt;: Deriving \(\nabla_{\mathbf{w}} L = (\sigma(\mathbf{w}^\top\mathbf{x}) - y)\mathbf{x}\) in one clean line and interpreting each weight \(w_j\) as the change in log-odds per unit increase in \(x_j\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convexity via the Logistic Hessian&lt;/strong&gt;: Proving \(H(\mathbf{w}) = X^\top D X\) with \(D_{ii} = p_i(1-p_i) &amp;gt; 0\) is positive semidefinite everywhere, guaranteeing every local minimum of logistic regression is global.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Forward-Mode vs. Reverse-Mode Autodiff&lt;/strong&gt;: Comparing operation counts—\(O(n)\) passes for forward mode vs. \(O(m)\) passes for reverse mode on \(f: \mathbb{R}^n \to \mathbb{R}^m\)—and understanding why Hessian-vector products combine both (forward-over-reverse).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hessian as a Diagnostic Tool&lt;/strong&gt;: Using top eigenvalues (sharpness) and negative eigenvalues (saddle directions) to diagnose training instability rather than inverting a \(10^9 \times 10^9\) matrix directly.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-computing-the-exact-logistic-hessian-and-verifying-positive-semidefiniteness&quot;&gt;Worked example: Computing the Exact Logistic Hessian and Verifying Positive Semidefiniteness&lt;/h3&gt;

&lt;p&gt;Consider a 1D logistic regression model \(p_i = \sigma(w x_i)\) on two points \(x_1 = 2, x_2 = -1\) evaluated at \(w = 0\) (where \(p_1 = p_2 = \sigma(0) = 0.5\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Diagonal Curvature Weights \(D_{ii} = p_i(1 - p_i)\)&lt;/strong&gt;:
\(D_{11} = 0.5(1 - 0.5) = 0.25, \qquad D_{22} = 0.5(1 - 0.5) = 0.25\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Exact Second Derivative (1D Hessian) \(H(w) = \sum_{i=1}^2 D_{ii} x_i^2\)&lt;/strong&gt;:
\(H(0) = 0.25(2)^2 + 0.25(-1)^2 = 0.25(4) + 0.25(1) = 1.00 + 0.25 = 1.25 &amp;gt; 0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify Convexity Everywhere&lt;/strong&gt;:
For &lt;em&gt;any&lt;/em&gt; weight vector \(\mathbf{w}\) and &lt;em&gt;any&lt;/em&gt; test vector \(\mathbf{v}\), \(\mathbf{v}^\top H(\mathbf{w}) \mathbf{v} = \sum_i p_i(1-p_i)(x_i^\top \mathbf{v})^2 \geq 0\) because \(p_i(1-p_i) &amp;gt; 0\) and squares are non-negative.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Interpret Log-Odds&lt;/strong&gt;:
If a learned weight is \(w_j = 0.693 \approx \ln 2\), increasing feature \(x_j\) by \(+1\) multiplies the odds \(\frac{p}{1-p}\) by \(e^{0.693} = 2.0\times\)—an instant, crisp interview answer.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-interview-practice--autodiff-hessian-logistic&quot;&gt;Optional: interview practice — autodiff, Hessian, logistic&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace loss, gradient-descent, or backpropagation theory. After those notes, use this drill, then open &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for solved items on algorithmic differentiation, curvature, and logistic regression.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Book themes for this chapter (study in the PDF, not here):&lt;/strong&gt; algorithmic (automatic) differentiation, Hessian intuition, and logistic / log-odds classification.&lt;/p&gt;

&lt;p&gt;Hub: &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;practice-prompts-original&quot;&gt;Practice prompts (original)&lt;/h2&gt;

&lt;h3 id=&quot;q1-logistic-gradient-in-one-line&quot;&gt;Q1. Logistic gradient in one line&lt;/h3&gt;

&lt;p&gt;Binary logistic regression predicts \(\hat y=\sigma(\mathbf{w}^\top\mathbf{x})\) and uses \(\ell= -y\log\hat y-(1-y)\log(1-\hat y)\). Show&lt;/p&gt;

\[\nabla_{\mathbf{w}}\ell = (\hat y-y)\,\mathbf{x}.\]

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Use \(\sigma&apos;(z)=\sigma(z)(1-\sigma(z))\) and the chain rule from Chapter 00 / the backprop notes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Let \(z=\mathbf{w}^\top\mathbf{x}\). Then \(\partial\ell/\partial z = -\frac{y}{\hat y}\sigma&apos;(z)+\frac{1-y}{1-\hat y}\sigma&apos;(z)\). Substituting \(\sigma&apos;=\hat y(1-\hat y)\) collapses the expression to \(\hat y-y\). Multiplying by \(\partial z/\partial\mathbf{w}=\mathbf{x}\) gives the claim. This is why “sigmoid + BCE” is numerically nicer when fused: you never materialize a lone \(\sigma&apos;\) that underflows.&lt;/p&gt;

&lt;h3 id=&quot;q2-odds-log-odds-and-a-coefficient&quot;&gt;Q2. Odds, log-odds, and a coefficient&lt;/h3&gt;

&lt;p&gt;A fitted logistic model has \(z = -1 + 2\,x_{\mathrm{smoke}}\) where \(x_{\mathrm{smoke}}\in\{0,1\}\). What are the odds of \(y=1\) for a non-smoker vs a smoker? What does the \(2\) mean in log-odds?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Odds are \(\hat y/(1-\hat y)=e^{z}\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Non-smoker: \(z=-1\), odds \(e^{-1}\approx 0.37\). Smoker: \(z=1\), odds \(e^{1}\approx 2.72\). The coefficient \(2\) is the &lt;em&gt;log odds ratio&lt;/em&gt; for the binary feature: smoking multiplies the odds by \(e^{2}\approx 7.4\). Interviews like this because it checks that you do not treat a logistic weight as a linear probability effect.&lt;/p&gt;

&lt;h3 id=&quot;q3-forward-vs-reverse-mode-on-a-tiny-graph&quot;&gt;Q3. Forward vs reverse mode on a tiny graph&lt;/h3&gt;

&lt;p&gt;You need \(\partial f/\partial x\) and \(\partial f/\partial y\) for \(f=(x y)+ \sin(x)\). Count scalar multiplies / transcendental calls in (a) two forward sweeps and (b) one reverse sweep. Which would you pick if \(f\) later becomes a 50-layer net with millions of weights?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Forward seeds one input; reverse seeds the output.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Two forward sweeps: seed \(x\) then \(y\), each replaying \(xy\) and \(\sin x\). One reverse sweep stores the forward values and sends adjoints back through \(+\), \(\times\), and \(\sin\). For a scalar loss and a huge \(\mathbf{w}\), reverse mode (backprop) is the only practical choice — that is the whole point of Chapter 03. Forward mode remains useful for a few inputs and many outputs (e.g. a Jacobian of a vector-valued layer).&lt;/p&gt;

&lt;h3 id=&quot;q4-logistic-hessian-and-convexity&quot;&gt;Q4. Logistic Hessian and convexity&lt;/h3&gt;

&lt;p&gt;For one example, \(\ell(\mathbf{w})= -y\log\sigma(\mathbf{w}^\top\mathbf{x})-(1-y)\log\bigl(1-\sigma(\mathbf{w}^\top\mathbf{x})\bigr)\). Show that&lt;/p&gt;

\[\nabla^2_{\mathbf{w}}\ell = \hat y(1-\hat y)\,\mathbf{x}\mathbf{x}^\top\]

&lt;p&gt;is positive semidefinite. What does that tell you about local minima of unregularized logistic regression?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; \(\mathbf{v}^\top(\mathbf{x}\mathbf{x}^\top)\mathbf{v}=(\mathbf{v}^\top\mathbf{x})^2\ge 0\) and \(\hat y(1-\hat y)\in(0,1)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; The Hessian is a nonnegative multiple of a rank-1 PSD matrix, so \(\ell\) is convex in \(\mathbf{w}\). A sum over a dataset stays convex. Every local minimum is global. Adding \(\tfrac{\lambda}{2}\|\mathbf{w}\|_2^2\) makes the Hessian positive &lt;em&gt;definite&lt;/em&gt; when \(\lambda&amp;gt;0\). Deep nets lose this guarantee as soon as you compose nonlinear hidden layers.&lt;/p&gt;

&lt;h3 id=&quot;q5-when-the-hessian-is-a-diagnosis-not-a-solver&quot;&gt;Q5. When the Hessian is a diagnosis, not a solver&lt;/h3&gt;

&lt;p&gt;Name one training symptom that a &lt;em&gt;diagonal&lt;/em&gt; Hessian (or just per-parameter second-moment) can explain, and one reason we still do not run full Newton on a modern CNN.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Think “sharp vs flat directions” from Chapter 00 Q5, and think about \(n_{\mathrm{params}}^2\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; A large diagonal entry means that coordinate is sharp: a learning rate that is fine elsewhere overshoots here — the story behind RMSprop / Adam (Chapter 10). Full Newton needs a \(P\times P\) Hessian (or linear solves with it). For millions of parameters that is impossible to store; even Hessian–vector products are used sparingly (damping, sharpness-aware ideas), not as the default step.&lt;/p&gt;

&lt;h2 id=&quot;attribution&quot;&gt;Attribution&lt;/h2&gt;

&lt;p&gt;Kashani, S., and Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Download the PDF from arXiv for the full solved Q&amp;amp;A. This page is original course practice, not a reprint.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, English. The autodiff prompts.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Backpropagation calculus&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 4](https://www.youtube.com/watch?v=tIeHLnjs5U8) — 3Blue1Brown, English. The scalar chain rule those prompts ask you to write.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yIYKR4sgzI8&quot;&gt;StatQuest: Logistic Regression&lt;/a&gt; — StatQuest with Josh Starmer, English. Logistic regression is the third prompt family in this practice set.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-04 Practical Training Techniques</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_04_Training_Techniques/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_04_Training_Techniques</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Two teams can take the exact same neural network architecture and dataset—one gets 94% accuracy in ten minutes, while the other stares at a flat loss curve for hours. The difference almost always lives in the practical training techniques: initialization, normalization, batching, and diagnostic monitoring.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-pillars-of-stable-neural-training&quot;&gt;Key ideas: Pillars of Stable Neural Training&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Symmetry-Breaking &amp;amp; Variance-Preserving Initialization&lt;/strong&gt;: Uses Xavier/Glorot (for tanh/sigmoid) or He/Kaiming (for ReLU) scaling so activations and gradients neither vanish nor explode at step 0.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Data Preprocessing &amp;amp; Leakage-Free Splits&lt;/strong&gt;: Standardizes inputs using strictly training-set statistics (\(\mu_{\text{train}}, \sigma_{\text{train}}\)) and enforces clean train/validation/test separation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diagnostic Monitoring &amp;amp; Checkpointing&lt;/strong&gt;: Tracks training vs. validation loss curves, gradient norms, and learning rates to distinguish underfitting, overfitting, and instability in real time.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Early Stopping &amp;amp; Reproducibility&lt;/strong&gt;: Halts training when validation performance plateaus, restores the best checkpoint, and pins random seeds for fair ablation experiments.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-why-fitting-scalers-on-validation-data-causes-subtle-leakage&quot;&gt;Worked example: Why Fitting Scalers on Validation Data Causes Subtle Leakage&lt;/h3&gt;

&lt;p&gt;Suppose a 1D feature has training values \(X_{\text{train}} = \{10, 20, 30\}\) and a single held-out test point \(x_{\text{test}} = 100\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Correct Pipeline (Fit Scaler on Train Only)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(\mu_{\text{train}} = \frac{10 + 20 + 30}{3} = 20\).&lt;/li&gt;
      &lt;li&gt;\(\sigma_{\text{train}} = \sqrt{\frac{(-10)^2 + 0^2 + 10^2}{3}} = \sqrt{\frac{200}{3}} \approx 8.165\).&lt;/li&gt;
      &lt;li&gt;Standardized train: \(\{-1.225, 0.000, +1.225\}\).&lt;/li&gt;
      &lt;li&gt;Standardized test: \(\frac{100 - 20}{8.165} = +9.798\) (correctly flags the test point as far out-of-distribution!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Leaky Pipeline (Mistakenly Fit Scaler on Train + Test Combined)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(\mu_{\text{all}} = \frac{10 + 20 + 30 + 100}{4} = 40\), \(\sigma_{\text{all}} \approx 35.355\).&lt;/li&gt;
      &lt;li&gt;Now every training point shifts downward to \(\{-0.849, -0.566, -0.283\}\) because future test data leaked into training preprocessing!
Always fit preprocessing transforms strictly on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;train&lt;/code&gt; and only call &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;.transform()&lt;/code&gt; on &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;val&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;test&lt;/code&gt;.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Practical techniques for training neural networks:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Initialization, Preprocessing, Batches, and Splits&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Monitoring, Early Stopping, and the Training Loop&lt;/strong&gt; — clipping, full loop, hyperparameters&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 6&lt;/td&gt;
          &lt;td&gt;Training Neural Networks I](https://www.youtube.com/watch?v=wEoyxE0GP2M) — Stanford University School of Engineering, English. Initialization, activations, and batching are the practical half of training.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 7&lt;/td&gt;
          &lt;td&gt;Training Neural Networks II](https://www.youtube.com/watch?v=_JB0AO7QxSA) — Stanford University School of Engineering, English. The follow-on lecture covers the optimization and regularization choices the second lesson monitors.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Zi-0rlM4RDs&quot;&gt;Train, Test, &amp;amp; Validation Sets explained&lt;/a&gt; — deeplizard, English. Train, validation, and test splits are the data-handling section.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-04-02 Monitoring, Early Stopping, and the Training Loop</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_04_02_Monitoring_and_Training_Loop/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_04_02_Monitoring_and_Training_Loop</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Training a neural network without logging both training and validation curves is like flying a plane in zero visibility with the instrument panel taped over. Loss curves, generalization gaps, and early-stopping patience counters tell you exactly when a model is learning, when it starts memorizing noise, and when to pull the plug.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-diagnostics--training-loop-engineering&quot;&gt;Key ideas: Diagnostics &amp;amp; Training Loop Engineering&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bias–Variance Reading of Loss Curves&lt;/strong&gt;: Both train and val loss high \(\implies\) underfitting (increase capacity/LR or train longer); train loss dropping while val loss rises \(\implies\) overfitting (regularize, augment, or stop early).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Early Stopping as Implicit Regularization&lt;/strong&gt;: Monitors validation loss with a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;patience&lt;/code&gt; window and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min_delta&lt;/code&gt; tolerance, restoring the best checkpoint weights before memorization degrades generalization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Norm &amp;amp; Activation Telemetry&lt;/strong&gt;: Logging global gradient norm \(\|\mathbf{g}\|_2\) exposes impending explosions (spikes before &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;) or vanishing layers long before accuracy collapses.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Epoch Hygiene &amp;amp; Evaluation Modes&lt;/strong&gt;: Properly toggling &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.train()&lt;/code&gt; vs. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;model.eval()&lt;/code&gt; and wrapping validation in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.no_grad()&lt;/code&gt; prevents BatchNorm/Dropout corruption and OOM crashes.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-tracing-an-early-stopping-state-machine-across-7-epochs&quot;&gt;Worked example: Tracing an Early-Stopping State Machine Across 7 Epochs&lt;/h3&gt;

&lt;p&gt;Suppose an early-stopping controller uses &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;patience = 3&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min_delta = 0.01&lt;/code&gt;, tracking validation losses across epochs 1–7:
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;[0.85, 0.72, 0.65, 0.645, 0.66, 0.68, 0.70]&lt;/code&gt;.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Epoch 1 (val = 0.850)&lt;/strong&gt;: First checkpoint. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_loss = 0.850&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_epoch = 1&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;counter = 0&lt;/code&gt; (save weights).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Epoch 2 (val = 0.720)&lt;/strong&gt;: Improvement \(0.850 - 0.720 = 0.130 \geq 0.01\). &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_loss = 0.720&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_epoch = 2&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;counter = 0&lt;/code&gt; (save weights).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Epoch 3 (val = 0.650)&lt;/strong&gt;: Improvement \(0.720 - 0.650 = 0.070 \geq 0.01\). &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_loss = 0.650&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_epoch = 3&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;counter = 0&lt;/code&gt; (save weights).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Epoch 4 (val = 0.645)&lt;/strong&gt;: Drop is \(0.650 - 0.645 = 0.005 &amp;lt; 0.01\) (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;min_delta&lt;/code&gt; not met!). &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;counter = 1&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Epoch 5 (val = 0.660)&lt;/strong&gt;: Worse than &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_loss&lt;/code&gt;. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;counter = 2&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Epoch 6 (val = 0.680)&lt;/strong&gt;: Worse than &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;best_loss&lt;/code&gt;. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;counter = 3 == patience&lt;/code&gt; \(\implies\) &lt;strong&gt;STOP TRAINING&lt;/strong&gt;!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Post-Stop Action&lt;/strong&gt;: Do &lt;strong&gt;not&lt;/strong&gt; deploy Epoch 6’s weights (val loss \(0.680\))—reload the saved checkpoint from &lt;strong&gt;Epoch 3&lt;/strong&gt; (val loss \(0.650\))!&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;monitoring-training&quot;&gt;Monitoring Training&lt;/h2&gt;

&lt;h3 id=&quot;metrics-to-track&quot;&gt;Metrics to Track&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Training Loss&lt;/strong&gt;: Should decrease steadily&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Validation Loss&lt;/strong&gt;: Should decrease; if it increases, overfitting!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Training Accuracy&lt;/strong&gt;: Should increase&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Validation Accuracy&lt;/strong&gt;: Should increase; gap with training accuracy indicates overfitting&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;visualization&quot;&gt;Visualization&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;matplotlib.pyplot&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;plot_training_history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Plot training history&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;fig&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subplots&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;figsize&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;14&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Loss plot
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Validation Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training and Validation Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Accuracy plot
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;plot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;label&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Validation Accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_xlabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_ylabel&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;set_title&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training and Validation Accuracy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;legend&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ax2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;grid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tight_layout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;plt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;show&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;early-stopping&quot;&gt;Early Stopping&lt;/h2&gt;

&lt;p&gt;Stop training when validation loss stops improving.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;EarlyStopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_delta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        patience: number of epochs to wait before stopping
        min_delta: minimum change to qualify as improvement
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_delta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_delta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;early_stop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__call__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_loss&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;is&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;min_delta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;EarlyStopping counter: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;early_stop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;copy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;early_stop&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Usage in training loop
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;early_stopping&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;EarlyStopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Training...
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;train_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_one_epoch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(...)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;validate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(...)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;early_stopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Early stopping triggered!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;early_stopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_parameters&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;gradient-clipping&quot;&gt;Gradient Clipping&lt;/h2&gt;

&lt;p&gt;Prevent exploding gradients by clipping gradient magnitudes.&lt;/p&gt;

&lt;h3 id=&quot;clip-by-value&quot;&gt;Clip by Value&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;clip_gradients_by_value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Clip gradients to [-max_value, max_value]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;keys&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max_value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;clip-by-norm&quot;&gt;Clip by Norm&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;clip_gradients_by_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_norm&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Clip gradients by global norm&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Compute global norm
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;total_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;total_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Clip if necessary
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;clip_coef&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;total_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clip_coef&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grad&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clip_coef&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clipped_gradients&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;complete-training-loop&quot;&gt;Complete Training Loop&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;initialization&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;he&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;early_stopping_patience&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Complete training function with all best practices
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Initialize
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;initialize_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;early_stopping&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;EarlyStopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;early_stopping_patience&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# History
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Training loop
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Create mini-batches
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Process each mini-batch
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Forward propagation
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward_propagation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Compute cost
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;batch_cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;compute_cost&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_cost&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Backward propagation
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward_propagation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Gradient clipping (optional)
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;clip_gradients_by_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_norm&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;5.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Update parameters
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;update_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradients&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Average loss over all batches
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute training accuracy
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;train_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Validation
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;val_predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward_propagation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;compute_cost&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;val_pred_labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_pred_labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Print progress
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;or&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
                  &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Train Loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Train Acc: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;
                  &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Val Loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Val Acc: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Early stopping
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;early_stopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Early stopping at epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;early_stopping&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_parameters&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Plot history
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;plot_training_history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_accs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;hyperparameter-tuning&quot;&gt;Hyperparameter Tuning&lt;/h2&gt;

&lt;h3 id=&quot;key-hyperparameters&quot;&gt;Key Hyperparameters&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Learning rate&lt;/strong&gt; (most important)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Batch size&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Number of layers&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Number of neurons per layer&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Activation functions&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Initialization method&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;tuning-strategies&quot;&gt;Tuning Strategies&lt;/h3&gt;

&lt;h4 id=&quot;1-manual-search&quot;&gt;1. Manual Search&lt;/h4&gt;

&lt;p&gt;Try different values based on intuition and experience.&lt;/p&gt;

&lt;h4 id=&quot;2-grid-search&quot;&gt;2. Grid Search&lt;/h4&gt;

&lt;p&gt;Try all combinations of a predefined set of values.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;learning_rates&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;batch_sizes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;best_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;bp&quot;&gt;None&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rates&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;history&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                                     &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Last validation accuracy
&lt;/span&gt;        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;best_params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Best: LR=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, BS=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Val Acc=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;3-random-search&quot;&gt;3. Random Search&lt;/h4&gt;

&lt;p&gt;Often more efficient than grid search.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;num_trials&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;trial&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_trials&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Log-uniform between 0.0001 and 0.1
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;16&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;history&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                                 &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;][&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;best_val_acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;New best: LR=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, BS=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Val Acc=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Proper initialization&lt;/strong&gt; (He for ReLU) prevents training issues&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Data preprocessing&lt;/strong&gt; (standardization/normalization) improves convergence&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mini-batch processing&lt;/strong&gt; balances speed and stability&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Train/Val/Test split&lt;/strong&gt; enables proper evaluation&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Monitoring&lt;/strong&gt; training/validation metrics detects overfitting&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Early stopping&lt;/strong&gt; prevents overfitting and saves time&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient clipping&lt;/strong&gt; prevents exploding gradients&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hyperparameter tuning&lt;/strong&gt; is essential for optimal performance&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With these techniques, you’re equipped to train neural networks effectively. The next chapter covers Convolutional Neural Networks for computer vision tasks!&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=BOCLq2gpcGU&quot;&gt;Other Regularization Methods (C2W1L08)&lt;/a&gt; — DeepLearningAI, English. Early stopping is one of the regularization methods this lesson tells you to watch.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, English. The loop that logs loss and applies the optimizer, which is the code section.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 7&lt;/td&gt;
          &lt;td&gt;Training Neural Networks II](https://www.youtube.com/watch?v=_JB0AO7QxSA) — Stanford University School of Engineering, English. Hyperparameters and training curves are what the monitoring section is looking at.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-04-01 Initialization, Preprocessing, Batches, and Splits</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_04_01_Init_Preprocessing_and_Data/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_04_01_Init_Preprocessing_and_Data</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Initialize every weight in a neural network to zero and something eerie happens: every neuron in a hidden layer computes the exact same activation, receives the exact same gradient, and updates to the exact same weight forever—turning a 1,000-neuron layer into a single expensive neuron. Breaking symmetry at the right variance scale is step zero of deep learning.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-initialization-preprocessing-and-batching&quot;&gt;Key ideas: Initialization, Preprocessing, and Batching&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Symmetry Breaking (Why Zero Init Fails)&lt;/strong&gt;: Identical weights force all neurons in a layer to evolve identically across epochs; random initialization breaks symmetry so neurons specialize into distinct feature detectors.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xavier (Glorot) vs. He (Kaiming) Variance Scaling&lt;/strong&gt;: Xavier sets \(\text{Var}(W) = \frac{2}{n_{\text{in}} + n_{\text{out}}}\) for linear/tanh regimes; He sets \(\text{Var}(W) = \frac{2}{n_{\text{in}}}\) to compensate for ReLU zeroing out half the activation energy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Input Standardization (Zero Mean, Unit Variance)&lt;/strong&gt;: Centers and rescales features so loss contours become roughly spherical, preventing large-scale features from dominating gradient updates.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mini-Batch Shuffling &amp;amp; Stratified Splits&lt;/strong&gt;: Randomizing batch order every epoch eliminates cyclical gradient bias, while stratified splitting preserves rare-class ratios across train, validation, and test sets.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-comparing-he-vs-xavier-signal-variance-across-a-10-layer-relu-network&quot;&gt;Worked example: Comparing He vs. Xavier Signal Variance Across a 10-Layer ReLU Network&lt;/h3&gt;

&lt;p&gt;Suppose a 10-layer ReLU MLP has constant width \(n = 512\) per layer and unit-variance input \(\text{Var}(a^{[0]}) = 1.0\). For a ReLU layer with symmetric zero-mean weights, forward variance evolves as:
\(\text{Var}(a^{[l]}) = \frac{1}{2}\,n\,\text{Var}(W)\,\text{Var}(a^{[l-1]})\)
(The factor \(\frac{1}{2}\) appears because ReLU zeros out the negative half of a symmetric zero-mean pre-activation!)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Using Xavier Initialization (\(\text{Var}(W) = \frac{1}{n} = \frac{1}{512}\))&lt;/strong&gt;:
Each layer multiplies activation variance by \(\frac{1}{2} \cdot 512 \cdot \frac{1}{512} = 0.5\).
After \(L = 10\) layers:
\(\text{Var}(a^{[10]}) = (0.5)^{10} \times 1.0 = \frac{1}{1024} \approx 0.000977\)
The signal loses &lt;strong&gt;99.9%&lt;/strong&gt; of its variance before even reaching the output layer!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Using He (Kaiming) Initialization (\(\text{Var}(W) = \frac{2}{n} = \frac{2}{512}\))&lt;/strong&gt;:
Each layer multiplies activation variance by \(\frac{1}{2} \cdot 512 \cdot \frac{2}{512} = 1.0\).
After \(L = 10\) layers:
\(\text{Var}(a^{[10]}) = (1.0)^{10} \times 1.0 = 1.000\)
Variance stays locked at \(1.0\) across all 10 (or 100!) layers—the exact mathematical reason He initialization unlocked deep ReLU networks.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers practical techniques and best practices for training neural networks effectively.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;weight-initialization&quot;&gt;Weight Initialization&lt;/h2&gt;

&lt;p&gt;Proper initialization is crucial for successful training. Poor initialization can lead to vanishing/exploding gradients or slow convergence.&lt;/p&gt;

&lt;h3 id=&quot;bad-initialization-methods&quot;&gt;Bad Initialization Methods&lt;/h3&gt;

&lt;h4 id=&quot;1-all-zeros&quot;&gt;1. All Zeros&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: All neurons compute the same output and receive the same gradient → No learning!&lt;/p&gt;

&lt;h4 id=&quot;2-all-same-values&quot;&gt;2. All Same Values&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;ones&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Same as zeros - breaks symmetry.&lt;/p&gt;

&lt;h3 id=&quot;good-initialization-methods&quot;&gt;Good Initialization Methods&lt;/h3&gt;

&lt;h4 id=&quot;1-random-small-values&quot;&gt;1. Random Small Values&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Pros&lt;/strong&gt;: Breaks symmetry
&lt;strong&gt;Cons&lt;/strong&gt;: May be too small for deep networks&lt;/p&gt;

&lt;h4 id=&quot;2-xavierglorot-initialization&quot;&gt;2. Xavier/Glorot Initialization&lt;/h4&gt;

&lt;p&gt;For &lt;strong&gt;sigmoid&lt;/strong&gt; or &lt;strong&gt;tanh&lt;/strong&gt; activations:&lt;/p&gt;

\[\mathbf{W}^{[l]} \sim \mathcal{N}\left(0, \frac{1}{n^{[l-1]}}\right)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;or&lt;/p&gt;

\[\mathbf{W}^{[l]} \sim \mathcal{N}\left(0, \frac{2}{n^{[l-1]} + n^{[l]}}\right)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Rationale&lt;/strong&gt;: Maintains variance of activations across layers.&lt;/p&gt;

&lt;h4 id=&quot;3-he-initialization&quot;&gt;3. He Initialization&lt;/h4&gt;

&lt;p&gt;For &lt;strong&gt;ReLU&lt;/strong&gt; activations (most common):&lt;/p&gt;

\[\mathbf{W}^{[l]} \sim \mathcal{N}\left(0, \frac{2}{n^{[l-1]}}\right)\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_l_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Why factor of 2?&lt;/strong&gt; ReLU zeros out half the neurons on average.&lt;/p&gt;

&lt;h3 id=&quot;bias-initialization&quot;&gt;Bias Initialization&lt;/h3&gt;

&lt;p&gt;Biases can typically be initialized to zero:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;complete-initialization-function&quot;&gt;Complete Initialization Function&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;initialize_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization_method&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;he&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Initialize network parameters
    
    layer_dims: list of layer sizes [n_x, n_h1, ..., n_y]
    initialization_method: &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xavier&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;he&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization_method&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization_method&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization_method&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;xavier&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initialization_method&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;he&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;data-preprocessing&quot;&gt;Data Preprocessing&lt;/h2&gt;

&lt;h3 id=&quot;1-feature-scaling&quot;&gt;1. Feature Scaling&lt;/h3&gt;

&lt;p&gt;Normalize input features to similar ranges.&lt;/p&gt;

&lt;h4 id=&quot;standardization-z-score-normalization&quot;&gt;Standardization (Z-score Normalization)&lt;/h4&gt;

\[x_{\text{norm}} = \frac{x - \mu}{\sigma}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;standardize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Standardize features to mean=0, std=1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;std&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;X_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;std&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Add epsilon to avoid division by zero
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;std&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;min-max-normalization&quot;&gt;Min-Max Normalization&lt;/h4&gt;

\[x_{\text{norm}} = \frac{x - x_{\min}}{x_{\max} - x_{\min}}\]

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;min_max_normalize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Scale features to [0, 1]&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;x_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;X_norm&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_min&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_min&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_max&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;When to use what:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Standardization&lt;/strong&gt;: When features are normally distributed or have outliers&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Min-Max&lt;/strong&gt;: When you need features in a specific range (e.g., [0, 1])&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-data-shuffling&quot;&gt;2. Data Shuffling&lt;/h3&gt;

&lt;p&gt;Shuffle training data before each epoch to prevent learning order-dependent patterns.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;shuffle_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Shuffle training data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;permutation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;permutation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;permutation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;permutation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;batch-processing&quot;&gt;Batch Processing&lt;/h2&gt;

&lt;h3 id=&quot;creating-mini-batches&quot;&gt;Creating Mini-Batches&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;create_mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Create list of mini-batches
    
    X: (n_x, m)
    Y: (n_y, m)
    batch_size: size of each mini-batch
    
    Returns: list of (X_batch, Y_batch) tuples
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Shuffle data
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;shuffle_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Partition
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;num_complete_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_complete_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Handle remaining examples (if m is not divisible by batch_size)
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_complete_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_complete_batches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;mini_batches&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;trainvalidationtest-split&quot;&gt;Train/Validation/Test Split&lt;/h2&gt;

&lt;h3 id=&quot;why-three-sets&quot;&gt;Why Three Sets?&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Training set&lt;/strong&gt;: Learn parameters&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Validation set&lt;/strong&gt;: Tune hyperparameters, monitor overfitting&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Test set&lt;/strong&gt;: Final evaluation (use only once!)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;typical-splits&quot;&gt;Typical Splits&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Small dataset (&amp;lt; 10,000 examples):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Train: 60%, Val: 20%, Test: 20%&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Medium dataset (10,000 - 1,000,000):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Train: 80%, Val: 10%, Test: 10%&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Large dataset (&amp;gt; 1,000,000):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Train: 98%, Val: 1%, Test: 1%&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;implementation&quot;&gt;Implementation&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_val_test_split&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_ratio&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_ratio&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Split data into train, validation, and test sets
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Shuffle first
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;shuffle_data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Calculate split indices
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_ratio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;val_end&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_ratio&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Split
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;val_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;Y_test&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[:,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;val_end&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:]&lt;/span&gt;
    
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=ScWTYHQra5E&quot;&gt;L11.6 Xavier Glorot and Kaiming He Initialization&lt;/a&gt; — Sebastian Raschka, English. Xavier and He initialization are the weight-scale rules this lesson states.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 6&lt;/td&gt;
          &lt;td&gt;Training Neural Networks I](https://www.youtube.com/watch?v=wEoyxE0GP2M) — Stanford University School of Engineering, English. The lecture context for those rules, plus preprocessing and batching.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=Zi-0rlM4RDs&quot;&gt;Train, Test, &amp;amp; Validation Sets explained&lt;/a&gt; — deeplizard, English. Why the lesson splits data into train, validation, and test before any epoch runs.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-03 Backpropagation Algorithm</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_03_Backpropagation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_03_Backpropagation</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;If you had to estimate the gradient of a 1-billion-parameter network by nudging each weight one by one with finite differences, a single gradient step would require a billion forward passes. Backpropagation computes every single one of those billion exact partial derivatives in just ONE backward pass—a billion-fold algorithmic miracle.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-core-pillars-of-backpropagation&quot;&gt;Key ideas: Core Pillars of Backpropagation&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Computational Graphs (DAG Decomposition)&lt;/strong&gt;: Breaks arbitrarily complex neural architectures into atomic differentiable primitives (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;+&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;*&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;matmul&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ReLU&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;exp&lt;/code&gt;) with trivial local derivatives.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Reverse-Mode Automatic Differentiation&lt;/strong&gt;: Propagates upstream scalar-loss sensitivities \(\delta = \frac{\partial L}{\partial z}\) backward from output to input, sharing every downstream sub-path instead of recomputing it.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Local Caching (The Memory–Compute Trade-Off)&lt;/strong&gt;: Stores forward-pass activations \(a^{[l-1]}\) and pre-activations \(z^{[l]}\) so local Jacobians can be evaluated instantly during the backward sweep.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Checking (Finite-Difference Verification)&lt;/strong&gt;: Validates hand-derived or custom backward kernels against centered finite differences \(\frac{L(\theta+\varepsilon) - L(\theta-\varepsilon)}{2\varepsilon}\) to catch sign or transpose bugs.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-reverse-mode-backprop-vs-finite-differences-on-a-tiny-graph&quot;&gt;Worked example: Reverse-Mode Backprop vs. Finite Differences on a Tiny Graph&lt;/h3&gt;

&lt;p&gt;Consider the computational graph \(L = (a \cdot b + c)^2\) at \(a = 2, b = 3, c = 1\). Define intermediate nodes \(u = a \cdot b\) and \(v = u + c\), so \(L = v^2\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Forward Pass (Cache Intermediates)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;
\[u = 2 \times 3 = 6\]
      &lt;/li&gt;
      &lt;li&gt;
\[v = 6 + 1 = 7\]
      &lt;/li&gt;
      &lt;li&gt;
\[L = 7^2 = 49\]
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Single Reverse-Mode Backward Pass (Compute ALL Three Gradients Together)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Start at output: \(\frac{\partial L}{\partial L} = 1\).&lt;/li&gt;
      &lt;li&gt;Through \(L = v^2\): \(\frac{\partial L}{\partial v} = 2v = 2(7) = 14\).&lt;/li&gt;
      &lt;li&gt;Through \(v = u + c\):
\(\frac{\partial L}{\partial u} = 14 \times 1 = 14, \qquad \frac{\partial L}{\partial c} = 14 \times 1 = 14\)&lt;/li&gt;
      &lt;li&gt;Through \(u = a \cdot b\):
\(\frac{\partial L}{\partial a} = 14 \cdot b = 14(3) = 42, \qquad \frac{\partial L}{\partial b} = 14 \cdot a = 14(2) = 28\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Finite-Difference Verification for \(\frac{\partial L}{\partial a}\) (\(\varepsilon = 0.001\))&lt;/strong&gt;:
\(\frac{L(2.001, 3, 1) - L(1.999, 3, 1)}{0.002} = \frac{(7.003)^2 - (6.997)^2}{0.002} = \frac{49.042009 - 48.958009}{0.002} = \frac{0.084}{0.002} = 42.000\)
Exact match to full precision!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Backpropagation — the engine of deep learning:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Theory and Worked Example&lt;/strong&gt; — concept, math, intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implementation&lt;/strong&gt; — from-scratch and PyTorch code, papers, pitfalls, takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Backpropagation, intuitively&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 3](https://www.youtube.com/watch?v=Ilg3gGewQ5U) — 3Blue1Brown, English. The intuition: each example nudges every weight.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Backpropagation calculus&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 4](https://www.youtube.com/watch?v=tIeHLnjs5U8) — 3Blue1Brown, English. The chain-rule calculus behind that nudge.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, English. The same algorithm implemented, which is the second lesson in this block.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-03-02 Backpropagation Implementation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_03_02_Backprop_Implementation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_03_02_Backprop_Implementation</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Implementing backpropagation from scratch in pure NumPy is the ultimate stress test of your understanding: if even one matrix transpose is flipped or one batch-average divisor \(1/B\) is misplaced, your model silently learns garbage. Mastering shape-checked matrix backprop makes debugging PyTorch and custom CUDA kernels effortless.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-from-equations-to-batched-backprop-code&quot;&gt;Key ideas: From Equations to Batched Backprop Code&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Shape-Invariant Matrix Backprop&lt;/strong&gt;: For \(Z = A_{\text{prev}} W^\top + \mathbf{b}\) with \(A_{\text{prev}} \in \mathbb{R}^{B \times d_{\text{in}}}\) and \(dZ \in \mathbb{R}^{B \times d_{\text{out}}}\), dimensional analysis uniquely forces \(dW = dZ^\top A_{\text{prev}}\) (shape \(d_{\text{out}} \times d_{\text{in}}\)) and \(dA_{\text{prev}} = dZ\,W\) (shape \(B \times d_{\text{in}}\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bias Gradient Reduction&lt;/strong&gt;: Because \(\mathbf{b}\) was broadcast across all \(B\) rows during the forward pass, its backward pass must &lt;strong&gt;sum&lt;/strong&gt; (or average) &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dZ&lt;/code&gt; along &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;axis=0&lt;/code&gt; to recover shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(d_out,)&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Fused Output–Loss Gradients&lt;/strong&gt;: Computing &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;dZ = (probs - y_onehot) / B&lt;/code&gt; directly avoids dividing by near-zero probabilities inside separate &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;log&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;softmax&lt;/code&gt; backward passes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Checking Discipline&lt;/strong&gt;: Verifying relative error \(\frac{\|\mathbf{g}_{\text{ana}} - \mathbf{g}_{\text{num}}\|_2}{\|\mathbf{g}_{\text{ana}}\|_2 + \|\mathbf{g}_{\text{num}}\|_2} &amp;lt; 10^{-7}\) in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float64&lt;/code&gt; guarantees bug-free custom autograd modules.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-shape-checked-batched-backward-pass-b--2&quot;&gt;Worked example: Shape-Checked Batched Backward Pass (\(B = 2\))&lt;/h3&gt;

&lt;p&gt;Suppose a linear layer maps \(d_{\text{in}} = 3 \to d_{\text{out}} = 2\) on a batch of \(B = 2\) samples, with cached forward input \(A_{\text{prev}}\) and incoming upstream gradient \(dZ\) (already scaled by \(1/B\)):
\(A_{\text{prev}} = \begin{bmatrix} 1 &amp;amp; 0 &amp;amp; 2 \\ -1 &amp;amp; 3 &amp;amp; 1 \end{bmatrix}_{(2 \times 3)}, \qquad dZ = \begin{bmatrix} 0.5 &amp;amp; -1.0 \\ 1.0 &amp;amp; 0.5 \end{bmatrix}_{(2 \times 2)}, \qquad W = \begin{bmatrix} 2 &amp;amp; -1 &amp;amp; 0 \\ 0 &amp;amp; 1 &amp;amp; 3 \end{bmatrix}_{(2 \times 3)}\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Weight Gradient \(dW = dZ^\top A_{\text{prev}}\)&lt;/strong&gt; (shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(2,2) @ (2,3) -&amp;gt; (2,3)&lt;/code&gt;):
\(dZ^\top = \begin{bmatrix} 0.5 &amp;amp; 1.0 \\ -1.0 &amp;amp; 0.5 \end{bmatrix}\)
\(dW = \begin{bmatrix} 0.5(1)+1.0(-1) &amp;amp; 0.5(0)+1.0(3) &amp;amp; 0.5(2)+1.0(1) \\ -1.0(1)+0.5(-1) &amp;amp; -1.0(0)+0.5(3) &amp;amp; -1.0(2)+0.5(1) \end{bmatrix} = \begin{bmatrix} -0.5 &amp;amp; 3.0 &amp;amp; 2.0 \\ -1.5 &amp;amp; 1.5 &amp;amp; -1.5 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Bias Gradient \(d\mathbf{b} = \sum_{\text{batch}} dZ\)&lt;/strong&gt; (shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(2,)&lt;/code&gt;):
\(d\mathbf{b} = \begin{bmatrix} 0.5 + 1.0 &amp;amp; -1.0 + 0.5 \end{bmatrix} = \begin{bmatrix} 1.5 &amp;amp; -0.5 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Input Gradient \(dA_{\text{prev}} = dZ\,W\)&lt;/strong&gt; (shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(2,2) @ (2,3) -&amp;gt; (2,3)&lt;/code&gt;):
\(dA_{\text{prev}} = \begin{bmatrix} 0.5(2)-1.0(0) &amp;amp; 0.5(-1)-1.0(1) &amp;amp; 0.5(0)-1.0(3) \\ 1.0(2)+0.5(0) &amp;amp; 1.0(-1)+0.5(1) &amp;amp; 1.0(0)+0.5(3) \end{bmatrix} = \begin{bmatrix} 1.0 &amp;amp; -1.5 &amp;amp; -3.0 \\ 2.0 &amp;amp; -0.5 &amp;amp; 1.5 \end{bmatrix}\)
Every shape matches its forward tensor identically—ready for direct &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;numpy&lt;/code&gt; or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.autograd.Function&lt;/code&gt; verification!&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Let’s implement backpropagation from scratch to understand every detail, then show how PyTorch automates this:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Sigmoid activation: maps real numbers to (0, 1)
    
    Why sigmoid? It&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s smooth (differentiable everywhere), bounded (outputs
    don&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;t explode), and has probabilistic interpretation. The derivative
    has a beautiful form: σ&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;(z) = σ(z)(1 - σ(z)), which we can compute
    from the activation itself without storing z.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Clip for numerical stability
&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Derivative in terms of activation (not z!)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    ReLU: max(0, z) - outputs input if positive, zero otherwise
    
    Why ReLU? It&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s computationally trivial (just thresholding), doesn&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;t
    saturate for positive inputs (gradient is 1, not approaching 0),
    and induces sparse representations. These properties make it vastly
    superior for deep networks compared to sigmoid/tanh.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Derivative is 1 where z &amp;gt; 0, zero elsewhere
    
    Note: at z=0, derivative is undefined. In practice, we define it as 0
    or sometimes 0.5, but this rarely matters since exact equality is rare.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetworkBackprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Implementing backpropagation manually to understand every step.
    
    This implementation prioritizes clarity over efficiency. Each operation
    is explicit, gradients are computed manually, and we store everything
    needed for understanding. A production implementation would vectorize
    more aggressively and use automatic differentiation.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        layer_sizes: list like [2, 4, 3, 1] for 2 inputs, hidden layers of 4 and 3, 1 output
        
        We initialize weights using He initialization for hidden layers (assuming ReLU)
        and small random values for output layer. This initialization scheme ensures
        activations maintain reasonable scale through forward pass and gradients
        maintain reasonable scale through backward pass.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Number of weight layers
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;c1&quot;&gt;# He initialization for ReLU layers: variance = 2/n_in
&lt;/span&gt;                &lt;span class=&quot;c1&quot;&gt;# Why? ReLU zeros half the neurons, so we need √2 instead of √1
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;c1&quot;&gt;# Output layer: smaller weights for numerical stability
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_in&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_out&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Initialized network with architecture: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Total parameters: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;count_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Count total trainable parameters&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;size&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Forward propagation with detailed caching for backward pass.
        
        We must store Z (pre-activations) and A (activations) for each layer
        because backpropagation needs them. This is a memory vs computation tradeoff:
        we could recompute forward pass during backward pass, but storing is faster.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Hidden layers with ReLU
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Output layer with sigmoid
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;compute_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Binary cross-entropy loss with numerical stability tricks.
        
        The loss -[y log(ŷ) + (1-y) log(1-ŷ)] has a problem: if ŷ is exactly
        0 or 1, we compute log(0) = -∞. We clip predictions to [ε, 1-ε] to prevent this.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;AL_clipped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL_clipped&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL_clipped&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Backpropagation: compute all parameter gradients efficiently.
        
        The algorithm processes layers in reverse order, maintaining error terms
        and using cached forward pass values. Each layer&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s gradient depends on
        gradients from layers above it, creating the backward flow of information
        that gives the algorithm its name.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Output layer error (for BCE + sigmoid this is remarkably simple!)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dAL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Derivative of loss
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dZL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dAL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# But actually, dZL = AL - Y works directly
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Simplification for BCE + Sigmoid (should use this in practice)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dZL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Output layer gradients
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;dW&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dZL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dZL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initialize dA for propagation
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;dA&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dZL&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Hidden layers (backward through layers L-1 down to 1)
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;reversed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Current layer&apos;s error
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;dZ&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dA&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Gradients for this layer
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;dW&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dZ&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dZ&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Propagate error to previous layer (if not input layer)
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;dA&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dZ&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;update_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Gradient descent update: θ ← θ - η ∇θ L
        
        We move parameters in the direction that decreases loss. The learning
        rate η controls step size—too large causes overshooting and instability,
        too small causes slow convergence.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;dW&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;params&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;db&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;print_every&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Complete training loop: forward → loss → backward → update
        
        This is the standard training loop for neural networks. Each iteration
        processes the entire dataset (batch gradient descent). In practice, we&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;d
        use mini-batches for efficiency.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Forward propagation
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Compute loss
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;compute_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Backward propagation
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Update parameters
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;update_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;grads&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Print progress
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;print_every&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Iteration &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Accuracy = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate on XOR problem
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Neural Network on XOR using Manual Backpropagation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# XOR dataset
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                  &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Shape: (2, 4)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Shape: (1, 4)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Create and train network
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# For reproducibility
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;network&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetworkBackprop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 2→4→4→1 architecture
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;losses&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;network&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;print_every&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test final performance
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Final Results&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;AL_final&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;network&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL_final&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, True: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predicted: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Probability: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;AL_final&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Final accuracy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Success! Backpropagation enabled the network to learn XOR.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now let’s see how PyTorch automates all of this:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleNetPyTorch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Same network using PyTorch&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s automatic differentiation.
    
    Notice how we don&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;t implement backward() - PyTorch computes all gradients
    automatically by building a computational graph during forward pass and
    applying backpropagation when we call loss.backward().
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SimpleNetPyTorch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training with PyTorch
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleNetPyTorch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BCELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;SGD&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Convert to PyTorch tensors
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_torch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (4, 2)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y_torch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Y_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dtype&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;float32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (4, 1)
&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training with PyTorch Automatic Differentiation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Backward pass - PyTorch does backpropagation automatically!
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Clear old gradients
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Compute gradients via automatic differentiation
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;       &lt;span class=&quot;c1&quot;&gt;# Update weights
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;500&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;acc&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Y_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Loss = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Accuracy = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;acc&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Final test
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;final_preds&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;PyTorch Final Results&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;70&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Input: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Predicted: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;final_preds&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The comparison reveals the power of modern frameworks. Our manual implementation took ~100 lines to implement backpropagation for a simple network. PyTorch handles arbitrary architectures automatically. However, understanding the manual implementation is invaluable. When debugging why a network isn’t training, when implementing custom layers, or when reading research papers that discuss gradient flow, the deep understanding from manual implementation is essential.&lt;/p&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Backpropagation doesn’t exist in isolation—it’s intimately connected to numerous other concepts in deep learning and machine learning more broadly. Understanding these connections transforms backpropagation from a mere algorithm into a window into the fundamental principles of learning systems.&lt;/p&gt;

&lt;p&gt;The most direct connection is to gradient descent and its variants. Backpropagation solves the problem of computing gradients, but it’s gradient descent that uses these gradients to update parameters. The choice of optimization algorithm—vanilla gradient descent, SGD with momentum, Adam, etc.—determines how we use backpropagation’s gradients. Understanding this separation helps clarify responsibilities: backpropagation tells us which direction decreases loss, while the optimizer decides how far to move in that direction and potentially accumulates information across iterations.&lt;/p&gt;

&lt;p&gt;Automatic differentiation, the technology underlying PyTorch and TensorFlow, is backpropagation’s computational cousin. While backpropagation is typically described as an algorithm for neural networks, automatic differentiation is a more general technique for computing derivatives of arbitrary programs. Modern frameworks build a computational graph during the forward pass, where nodes represent operations (matrix multiply, add, ReLU, etc.) and edges represent data flow. Backpropagation is then simply reverse-mode automatic differentiation on this graph. Understanding this connection explains why frameworks can handle arbitrary architectures—as long as each operation is differentiable, backpropagation works automatically.&lt;/p&gt;

&lt;p&gt;The vanishing and exploding gradient problems are direct consequences of how backpropagation propagates errors through layers. Each layer’s error is the previous layer’s error multiplied by weights and activation derivatives. If these multipliers are consistently less than 1 (as with saturated sigmoid/tanh activations), errors shrink exponentially with depth—this is vanishing gradients. If multipliers are greater than 1, errors explode. This understanding motivated numerous innovations: ReLU activations keep gradients at 1 for positive inputs, batch normalization keeps activations in reasonable ranges, residual connections provide gradient highways bypassing many layers, and careful initialization ensures neither vanishing nor explosion at the start of training.&lt;/p&gt;

&lt;p&gt;Computational graphs and backpropagation connect to a beautiful area of computer science: automatic differentiation and the calculus of variations. Every differentiable program can be seen as defining a function from inputs to outputs, and automatic differentiation provides the gradient of this function. This generality means backpropagation isn’t limited to feedforward networks—it works for recurrent networks (backpropagation through time), for networks with complex control flow, even for networks where the architecture itself depends on the data (dynamic networks). The principle is always the same: build the computational graph, compute forward pass, compute backward pass using the chain rule.&lt;/p&gt;

&lt;p&gt;Finally, backpropagation connects to the broader question of credit assignment in learning systems. When a network makes a mistake, which parameters were responsible? Backpropagation provides one answer: assign credit proportional to gradients. But this isn’t the only possible answer. Reinforcement learning uses different credit assignment mechanisms for sequential decision problems. Attention mechanisms provide another form of credit assignment for sequence-to-sequence tasks. Understanding backpropagation as one solution to credit assignment helps us appreciate both its power and its limitations, and motivates alternative approaches when backpropagation’s assumptions don’t hold.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.nature.com/articles/323533a0&quot;&gt;“Learning representations by back-propagating errors” (1986)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: David E. Rumelhart, Geoffrey E. Hinton, Ronald J. Williams&lt;br /&gt;
This seminal Nature paper made backpropagation widely known and demonstrated its power on practical problems including speech recognition and image classification. The paper elegantly presented the algorithm, proved its correctness via the chain rule, and showed that multi-layer networks trained with backpropagation could solve problems impossible for single-layer perceptrons. The authors demonstrated learning internal representations—hidden layers discovering useful features automatically—which was revelatory at the time. This paper effectively launched the connectionist revolution and remains one of the most cited papers in all of machine learning. Reading it today, one is struck by how clearly the authors understood both the algorithm’s power and its challenges, including what we now call vanishing gradients.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf&quot;&gt;“Efficient BackProp” (1998)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Yann LeCun, Léon Bottou, Genevieve B. Orr, Klaus-Robert Müller&lt;br /&gt;
This technical report, though less famous than the original backpropagation paper, is arguably more important for practitioners. LeCun and colleagues systematically analyzed what makes backpropagation work well in practice, covering initialization (why random weights should have carefully chosen variance), normalization (why standardizing inputs helps), learning rate selection, and activation function choices. The paper provides the practical wisdom accumulated from years of making backpropagation work on real problems. Many “tricks” taught in modern deep learning courses—like He initialization and input normalization—have their roots in insights from this paper. It’s essential reading for anyone who wants to train networks effectively rather than just mechanically applying backpropagation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1211.5063&quot;&gt;“On the difficulty of training Recurrent Neural Networks” (2013)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Razvan Pascanu, Tomas Mikolov, Yoshua Bengio&lt;br /&gt;
This paper rigorously analyzed why backpropagation fails in recurrent neural networks—specifically, why gradients vanish or explode when propagating back through time. The authors showed that when unrolling an RNN through many time steps, gradients must pass through repeated matrix multiplications, and if the largest eigenvalue of the recurrent weight matrix is less than 1, gradients vanish exponentially; if greater than 1, they explode. The paper proposed gradient clipping to handle explosions (still standard practice today) and analyzed how LSTM’s gating mechanisms mitigate vanishing gradients. This work deepened our understanding of backpropagation’s limitations and motivated architectural innovations like LSTMs and GRUs that make recurrent backpropagation more stable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://openreview.net/forum?id=BJJsrmfCZ&quot;&gt;“Automatic differentiation in PyTorch” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Adam Paszke, Sam Gross, Soumith Chintala, et al.&lt;br /&gt;
This paper described PyTorch’s autograd system, which automates backpropagation using dynamic computational graphs. Unlike earlier frameworks that required defining the network structure statically, PyTorch builds the graph during forward execution, allowing for dynamic architectures (where the computation depends on the data). The paper explained how PyTorch computes gradients using reverse-mode automatic differentiation—which is backpropagation generalized to arbitrary code, not just neural networks. This flexibility made PyTorch popular in research where experimenting with novel architectures is common. Understanding how frameworks automate backpropagation helps users debug gradient issues and implement custom operations correctly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://www.deeplearningbook.org/contents/mlp.html&quot;&gt;“Deep Learning” - Chapter 6 (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ian Goodfellow, Yoshua Bengio, Aaron Courville&lt;br /&gt;
While not a research paper, this textbook chapter provides the most comprehensive and rigorous treatment of backpropagation available. It covers the algorithm from first principles, discusses computational graphs in detail, analyzes complexity, and addresses practical considerations like numerical stability and memory management. The chapter bridges theory and practice, explaining not just what backpropagation computes but why it computes it that way, how to implement it efficiently, and when it might fail. For anyone seeking a complete mathematical understanding of backpropagation, this chapter is the definitive resource. It’s also freely available online, making it accessible to all learners.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;Perhaps the most insidious pitfall in backpropagation is failing to cache forward pass values. During the forward pass, we must store both pre-activations \(\mathbf{z}^{[l]}\) and activations \(\mathbf{a}^{[l]}\) for every layer because the backward pass needs them. Forgetting to cache these values or overwriting them before the backward pass completes means you’ll have to recompute the forward pass, doubling computation time, or worse, using incorrect values and getting wrong gradients. This is why modern frameworks automatically handle caching—the computational graph remembers all intermediate values. When implementing backpropagation manually, explicitly maintain a cache dictionary is good practice.&lt;/p&gt;

&lt;p&gt;Dimension mismatches between gradients and parameters are another common error that can be subtle to debug. The gradient \(\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[l]}}\) must have exactly the same shape as \(\mathbf{W}^{[l]}\)—if \(\mathbf{W}^{[l]}\) is \(n_{out} \times n_{in}\), so must be its gradient. When computing \(\boldsymbol{\delta}^{[l]} (\mathbf{a}^{[l-1]})^T\), getting the order of multiplication wrong or forgetting the transpose can produce a matrix of the wrong shape that Python might broadcast incorrectly, leading to subtle bugs. Always assert that gradient shapes match parameter shapes after computing them.&lt;/p&gt;

&lt;p&gt;Numerical instability in gradient computation can cause training to fail in ways that aren’t immediately obvious. When computing sigmoid derivatives \(\sigma&apos;(z) = \sigma(z)(1-\sigma(z))\), if \(z\) is very large, \(\sigma(z) \approx 1\) and the derivative becomes \(1 \times (1-1) = 0\) numerically, even though mathematically it should be a small positive number. This causes gradients to vanish not due to network depth but due to floating-point precision. Clipping intermediate values to reasonable ranges and using numerically stable implementations (like log-sum-exp trick for softmax) prevents these issues.&lt;/p&gt;

&lt;p&gt;A powerful debugging technique is gradient checking through numerical approximation. For any parameter \(\theta\), we can approximate its gradient using finite differences:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \theta} \approx \frac{\mathcal{L}(\theta + \epsilon) - \mathcal{L}(\theta - \epsilon)}{2\epsilon}\]

&lt;p&gt;with \(\epsilon \approx 10^{-7}\). Comparing this numerical gradient to the backpropagation gradient reveals implementation errors. The relative difference should be less than \(10^{-7}\) for correct implementations. However, gradient checking is slow (requires multiple forward passes) so use it only for debugging, never during actual training.&lt;/p&gt;

&lt;p&gt;Gradient clipping deserves special mention as an essential trick when training recurrent networks or any deep architecture prone to gradient explosion. We monitor the global gradient norm \(\|\nabla_\theta \mathcal{L}\|_2 = \sqrt{\sum_{\theta} (\frac{\partial \mathcal{L}}{\partial \theta})^2}\) and if it exceeds a threshold (typically 5 or 10), we scale all gradients by \(\frac{\text{threshold}}{\|\nabla_\theta \mathcal{L}\|_2}\). This preserves gradient directions while preventing the explosive updates that would destabilize training. It’s a simple trick that makes training many architectures possible.&lt;/p&gt;

&lt;p&gt;Finally, understanding that backpropagation is just an efficient implementation of the chain rule means you can derive gradients for custom layers yourself. When implementing a novel operation, derive its local gradient (how outputs change with respect to inputs), and backpropagation automatically incorporates it into the full network gradient. This understanding is empowering—you’re not limited to predefined layers but can create whatever computations your problem requires, as long as you can differentiate them.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;Backpropagation is fundamentally an efficient application of the calculus chain rule to compute gradients in neural networks. Its efficiency—computing all gradients in time proportional to one forward pass—makes training deep networks tractable. The algorithm processes layers in reverse order, propagating errors backward and using cached forward pass values to compute parameter gradients. The beautiful simplicity of \(\boldsymbol{\delta}^{[L]} = \mathbf{a}^{[L]} - \mathbf{y}\) for output layers with appropriate loss/activation pairs is not coincidence but careful design. Modern frameworks automate backpropagation through automatic differentiation, building computational graphs and applying reverse-mode differentiation. Understanding backpropagation deeply means understanding not just the mechanics but the why—why we cache values, why gradients vanish or explode, why certain design choices simplify gradients—and this understanding is essential for debugging training failures, designing novel architectures, and truly mastering deep learning rather than merely applying it.&lt;/p&gt;

&lt;p&gt;The journey from manually implementing backpropagation to using it seamlessly through PyTorch mirrors the journey from understanding to application, and both are necessary for expertise.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, English. Backpropagation as an autograd engine you can read line by line.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=IN2XmBhILt4&quot;&gt;Neural Networks Pt. 2: Backpropagation Main Ideas&lt;/a&gt; — StatQuest with Josh Starmer, English. The scalar chain-rule picture to keep beside the code.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qzPQ8cEsVK8&quot;&gt;Forward and Backward Propagation (C1W4L06)&lt;/a&gt; — DeepLearningAI, English. Names forward and backward as a pair, which is the contract the implementation has to satisfy.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-03-01 Backpropagation Theory and Worked Example</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_03_01_Backprop_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_03_01_Backprop_Theory</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Every neural network textbook writes down the four fundamental equations of backpropagation, yet students often treat them as formulas to memorize rather than inevitabilities of the multivariable chain rule. Once you see that each equation is simply “upstream error \(\times\) local Jacobian,” you can derive backprop for any architecture on the fly.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-the-four-equations-of-backpropagation&quot;&gt;Key ideas: The Four Equations of Backpropagation&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Output Error Signal (\(\boldsymbol{\delta}^{[L]}\))&lt;/strong&gt;: Seeds the backward sweep at the final layer via \(\boldsymbol{\delta}^{[L]} = \nabla_{\mathbf{a}^{[L]}} L \odot g&apos;^{[L]}(\mathbf{z}^{[L]})\), which simplifies directly to \(\hat{\mathbf{y}} - \mathbf{y}\) for canonical loss–activation pairs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Backward Error Recursion (\(\boldsymbol{\delta}^{[l]}\))&lt;/strong&gt;: Pulls error signals through the transpose weight matrix via \(\boldsymbol{\delta}^{[l]} = \big((W^{[l+1]})^\top \boldsymbol{\delta}^{[l+1]}\big) \odot g&apos;^{[l]}(\mathbf{z}^{[l]})\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Weight &amp;amp; Bias Gradients (Outer Product Rule)&lt;/strong&gt;: Computes \(\frac{\partial L}{\partial W^{[l]}} = \boldsymbol{\delta}^{[l]} (\mathbf{a}^{[l-1]})^\top\) and \(\frac{\partial L}{\partial \mathbf{b}^{[l]}} = \boldsymbol{\delta}^{[l]}\)—a rank-1 outer product per sample, summed across the mini-batch.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multivariable Fan-Out Rule&lt;/strong&gt;: Whenever a tensor branches into multiple paths (as in residual connections \(\mathbf{y} = \mathbf{x} + F(\mathbf{x})\)), incoming gradients from all branches &lt;strong&gt;sum&lt;/strong&gt; at the split node.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-executing-all-four-backprop-equations-on-a-1---1---1-network&quot;&gt;Worked example: Executing All Four Backprop Equations on a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;1 -&amp;gt; 1 -&amp;gt; 1&lt;/code&gt; Network&lt;/h3&gt;

&lt;p&gt;Take a 2-layer network with input \(x = 2\), target \(y = 1\), weights \(w_1 = 0.5, b_1 = 0\), \(w_2 = 2.0, b_2 = 0\), ReLU hidden activation, linear output, and half-MSE loss \(L = \frac{1}{2}(\hat{y} - y)^2\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Forward Pass&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Layer 1: \(z_1 = w_1 x + b_1 = 0.5(2) + 0 = 1.0 \implies a_1 = \text{ReLU}(1.0) = 1.0\).&lt;/li&gt;
      &lt;li&gt;Layer 2: \(z_2 = w_2 a_1 + b_2 = 2.0(1.0) + 0 = 2.0 \implies \hat{y} = 2.0\).&lt;/li&gt;
      &lt;li&gt;Loss: \(L = \frac{1}{2}(2.0 - 1.0)^2 = 0.50\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Equation 1 (Output Error \(\delta_2\))&lt;/strong&gt;:
\(\delta_2 = \frac{\partial L}{\partial z_2} = \hat{y} - y = 2.0 - 1.0 = +1.0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Equation 3 at Layer 2 (\(\frac{\partial L}{\partial w_2}, \frac{\partial L}{\partial b_2}\))&lt;/strong&gt;:
\(\frac{\partial L}{\partial w_2} = \delta_2 \cdot a_1 = (1.0)(1.0) = 1.0, \qquad \frac{\partial L}{\partial b_2} = \delta_2 = 1.0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Equation 2 (Propagate Error to Layer 1, \(\delta_1\))&lt;/strong&gt;:
Since \(z_1 = 1.0 &amp;gt; 0\), \(\text{ReLU}&apos;(1.0) = 1\):
\(\delta_1 = (w_2^\top \delta_2) \odot \text{ReLU}&apos;(z_1) = (2.0 \times 1.0) \times 1 = 2.0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Equation 3 at Layer 1 (\(\frac{\partial L}{\partial w_1}, \frac{\partial L}{\partial b_1}\))&lt;/strong&gt;:
\(\frac{\partial L}{\partial w_1} = \delta_1 \cdot x = (2.0)(2) = 4.0, \qquad \frac{\partial L}{\partial b_1} = \delta_1 = 2.0\)
Every gradient is exact, verified without touching PyTorch!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;backpropagation-the-engine-of-deep-learning&quot;&gt;Backpropagation: The Engine of Deep Learning&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/e/e4/Backpropagation_example.svg/600px-Backpropagation_example.svg.png&quot; alt=&quot;Backpropagation Visualization&quot; /&gt;
&lt;em&gt;Hình ảnh: Minh họa quá trình Backpropagation trong mạng neural. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Backpropagation is the algorithmic heart of deep learning, the mechanism that makes training neural networks practical. Without it, deep learning as we know it would not exist. The algorithm solves a deceptively simple problem: given a neural network with potentially millions of parameters and a measure of how wrong its predictions are, how should we adjust each parameter to improve performance? The naive approach—computing the gradient of each parameter independently through finite differences—would require millions of forward passes per training example, making training prohibitively expensive. Backpropagation computes all these gradients simultaneously in roughly the same time as a single forward pass, a computational efficiency gain of millions.&lt;/p&gt;

&lt;p&gt;The fundamental insight of backpropagation is that gradients can be computed efficiently by reusing calculations. When we compute how the loss changes with respect to a parameter deep in the network, we’re applying the chain rule from calculus, but we’re doing so cleverly. Rather than recomputing the entire chain for each parameter, we compute intermediate derivatives once and reuse them. This dynamic programming approach transforms an exponential-time problem into a linear-time one, making training practical.&lt;/p&gt;

&lt;p&gt;What makes backpropagation particularly elegant is its local nature. Each layer needs only to know how to compute its own local gradients—how its outputs change with respect to its inputs and parameters. It receives gradients from the layer above and passes gradients to the layer below. This modularity means we can mix different layer types (convolutional, recurrent, attention, etc.) in the same network, and as long as each can compute its local gradients, backpropagation works seamlessly. This is why modern deep learning frameworks can support such diverse architectures—the backpropagation algorithm naturally handles any differentiable computational graph.&lt;/p&gt;

&lt;p&gt;Understanding backpropagation deeply means understanding not just the mechanics of computing gradients but why the algorithm is structured the way it is, what assumptions it makes, and where it can fail. The algorithm assumes our network consists of differentiable operations—this is why activation functions must be smooth. It assumes we can store intermediate computations from the forward pass—this is why memory limits constrain the batch sizes we can use. It propagates errors backward proportional to the weights—this is why extremely large or small weights cause gradient explosions or vanishing. These aren’t just implementation details; they’re fundamental properties that shape how we design and train networks.&lt;/p&gt;

&lt;p&gt;The historical importance of backpropagation cannot be overstated. While gradient descent had been known since the 19th century and the chain rule is elementary calculus, recognizing how to apply these efficiently to multi-layer networks was the breakthrough that revived neural network research in the 1980s after the first AI winter. The algorithm was actually discovered multiple times independently by different researchers (Werbos in 1974, Rumelhart/Hinton/Williams in 1986, and others), but it was the 1986 Nature paper that brought it to widespread attention and demonstrated its power on problems like speech recognition and image classification. This marks one of those rare moments in science where a computational technique—not new data or more powerful hardware—fundamentally expanded what was possible.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;To truly understand backpropagation, we must first be precise about what we’re computing and why. Our goal is to minimize a loss function \(\mathcal{L}(\mathbf{y}, \hat{\mathbf{y}})\) that measures the discrepancy between our network’s predictions \(\hat{\mathbf{y}}\) and the true labels \(\mathbf{y}\). The network is a composition of functions, one per layer, and each layer has parameters (weights and biases) that we can adjust. Gradient descent tells us that to minimize the loss, we should adjust each parameter \(\theta\) in the direction opposite to the gradient:&lt;/p&gt;

\[\theta \leftarrow \theta - \eta \frac{\partial \mathcal{L}}{\partial \theta}\]

&lt;p&gt;The challenge is computing \(\frac{\partial \mathcal{L}}{\partial \theta}\) efficiently for every parameter in the network. Let’s build up the mathematics carefully, starting with a simple two-layer network and then generalizing.&lt;/p&gt;

&lt;p&gt;Consider a network with input \(\mathbf{x}\), one hidden layer with activation \(\mathbf{h}\), and output \(\hat{\mathbf{y}}\). The forward pass computes:&lt;/p&gt;

&lt;p&gt;\(\mathbf{z}^{[1]} = \mathbf{W}^{[1]} \mathbf{x} + \mathbf{b}^{[1]}\)
\(\mathbf{h} = \mathbf{a}^{[1]} = g^{[1]}(\mathbf{z}^{[1]})\)
\(\mathbf{z}^{[2]} = \mathbf{W}^{[2]} \mathbf{h} + \mathbf{b}^{[2]}\)
\(\hat{\mathbf{y}} = \mathbf{a}^{[2]} = g^{[2]}(\mathbf{z}^{[2]})\)
\(\mathcal{L} = \mathcal{L}(\mathbf{y}, \hat{\mathbf{y}})\)&lt;/p&gt;

&lt;p&gt;where \(g^{[l]}\) denotes the activation function for layer \(l\). To find \(\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[1]}}\), we apply the chain rule:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[1]}} = \frac{\partial \mathcal{L}}{\partial \hat{\mathbf{y}}} \frac{\partial \hat{\mathbf{y}}}{\partial \mathbf{z}^{[2]}} \frac{\partial \mathbf{z}^{[2]}}{\partial \mathbf{h}} \frac{\partial \mathbf{h}}{\partial \mathbf{z}^{[1]}} \frac{\partial \mathbf{z}^{[1]}}{\partial \mathbf{W}^{[1]}}\]

&lt;p&gt;Computing this directly involves multiplying many Jacobian matrices, which seems expensive. The key insight of backpropagation is to compute these products right-to-left, reusing intermediate results.&lt;/p&gt;

&lt;p&gt;Define the error term for each layer as:&lt;/p&gt;

\[\boldsymbol{\delta}^{[l]} = \frac{\partial \mathcal{L}}{\partial \mathbf{z}^{[l]}}\]

&lt;p&gt;This quantity represents the sensitivity of the loss to changes in the pre-activation of layer \(l\). For the output layer with binary cross-entropy loss and sigmoid activation, something remarkable happens:&lt;/p&gt;

\[\boldsymbol{\delta}^{[L]} = \frac{\partial \mathcal{L}}{\partial \mathbf{z}^{[L]}} = \frac{\partial \mathcal{L}}{\partial \mathbf{a}^{[L]}} \frac{\partial \mathbf{a}^{[L]}}{\partial \mathbf{z}^{[L]}}\]

&lt;p&gt;The loss derivative is \(\frac{\partial \mathcal{L}}{\partial \mathbf{a}^{[L]}} = -\frac{\mathbf{y}}{\mathbf{a}^{[L]}} + \frac{1-\mathbf{y}}{1-\mathbf{a}^{[L]}}\), and the sigmoid derivative is \(\frac{\partial \mathbf{a}^{[L]}}{\partial \mathbf{z}^{[L]}} = \mathbf{a}^{[L]}(1-\mathbf{a}^{[L]})\). When you multiply these together and simplify, almost all terms cancel, leaving simply:&lt;/p&gt;

\[\boldsymbol{\delta}^{[L]} = \mathbf{a}^{[L]} - \mathbf{y}\]

&lt;p&gt;This beautiful simplification—that the output error is just the difference between prediction and truth—occurs for several common loss/activation combinations (MSE with linear, cross-entropy with sigmoid, cross-entropy with softmax). It’s not a coincidence but a deliberate design: these combinations were chosen precisely because they yield simple gradients.&lt;/p&gt;

&lt;p&gt;For hidden layers, we propagate the error backward:&lt;/p&gt;

\[\boldsymbol{\delta}^{[l]} = (\mathbf{W}^{[l+1]})^T \boldsymbol{\delta}^{[l+1]} \odot g&apos;^{[l]}(\mathbf{z}^{[l]})\]

&lt;p&gt;Let’s parse this equation carefully because it encodes the core of backpropagation. The term \((\mathbf{W}^{[l+1]})^T \boldsymbol{\delta}^{[l+1]}\) propagates the error from layer \(l+1\) back to layer \(l\), weighted by the connection strengths (the transpose of the weight matrix). If a particular hidden neuron has strong connections to neurons with large errors in the next layer, it receives a large error signal. The Hadamard product \(\odot g&apos;^{[l]}(\mathbf{z}^{[l]})\) then scales this by the local gradient of the activation function. This scaling is crucial: if the activation function is saturated (gradient near zero), the error signal is suppressed, which is exactly what causes the vanishing gradient problem in deep networks with sigmoid/tanh activations.&lt;/p&gt;

&lt;p&gt;Once we have the error terms \(\boldsymbol{\delta}^{[l]}\), computing parameter gradients becomes straightforward:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[l]}} = \boldsymbol{\delta}^{[l]} (\mathbf{a}^{[l-1]})^T\]

\[\frac{\partial \mathcal{L}}{\partial \mathbf{b}^{[l]}} = \boldsymbol{\delta}^{[l]}\]

&lt;p&gt;The weight gradient is an outer product of the error signal with the layer’s input, which has an elegant interpretation: we adjust connection strength proportionally to both the error at the output and the activation at the input. Strong input with large error means this connection should change substantially. The bias gradient is simply the error signal itself, since the bias always has an “input” of 1.&lt;/p&gt;

&lt;p&gt;The computational complexity analysis reveals backpropagation’s efficiency. A forward pass through a network with \(L\) layers, \(n\) neurons per layer, and batch size \(m\) requires \(O(L \cdot n^2 \cdot m)\) operations (dominated by matrix multiplications). Amazingly, backpropagation requires exactly the same complexity—we compute all gradients for all parameters in the same time as one forward pass. Compare this to naive gradient computation via finite differences, which would require \(O(P)\) forward passes where \(P\) is the number of parameters, potentially millions. This efficiency difference—linear versus quadratic in the number of parameters—is what makes deep learning tractable.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;Let’s work through a complete example with actual numbers to demystify backpropagation. Consider the simplest interesting case: a two-layer network for binary classification. We have two inputs, two hidden neurons with ReLU activation, and one output with sigmoid activation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Network architecture&lt;/strong&gt;:
\(\mathbf{x} \in \mathbb{R}^2 \xrightarrow{\mathbf{W}^{[1]}, \mathbf{b}^{[1]}} \mathbf{z}^{[1]} \in \mathbb{R}^2 \xrightarrow{\text{ReLU}} \mathbf{a}^{[1]} \in \mathbb{R}^2 \xrightarrow{\mathbf{W}^{[2]}, \mathbf{b}^{[2]}} z^{[2]} \in \mathbb{R} \xrightarrow{\text{Sigmoid}} \hat{y} \in (0,1)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parameters&lt;/strong&gt; (initialized):
\(\mathbf{W}^{[1]} = \begin{bmatrix} 0.5 &amp;amp; -0.3 \\ 0.2 &amp;amp; 0.8 \end{bmatrix}, \quad \mathbf{b}^{[1]} = \begin{bmatrix} 0.1 \\ -0.2 \end{bmatrix}\)&lt;/p&gt;

\[\mathbf{W}^{[2]} = \begin{bmatrix} 1.0 &amp;amp; -0.5 \end{bmatrix}, \quad b^{[2]} = 0.5\]

&lt;p&gt;&lt;strong&gt;Input and label&lt;/strong&gt;: \(\mathbf{x} = \begin{bmatrix} 1.0 \\ 2.0 \end{bmatrix}\), \(y = 1\) (true class is positive)&lt;/p&gt;

&lt;p&gt;Now let’s trace through forward and backward passes step by step, understanding what each computation means.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Forward Pass&lt;/strong&gt;:&lt;/p&gt;

\[\mathbf{z}^{[1]} = \begin{bmatrix} 0.5 &amp;amp; -0.3 \\ 0.2 &amp;amp; 0.8 \end{bmatrix} \begin{bmatrix} 1.0 \\ 2.0 \end{bmatrix} + \begin{bmatrix} 0.1 \\ -0.2 \end{bmatrix} = \begin{bmatrix} 0.5 - 0.6 + 0.1 \\ 0.2 + 1.6 - 0.2 \end{bmatrix} = \begin{bmatrix} 0.0 \\ 1.6 \end{bmatrix}\]

&lt;p&gt;The first hidden neuron receives \(z^{[1]}_1 = 0\), exactly at the ReLU threshold. The second receives \(z^{[1]}_2 = 1.6\), a strong positive signal. Applying ReLU:&lt;/p&gt;

\[\mathbf{a}^{[1]} = \max(0, \mathbf{z}^{[1]}) = \begin{bmatrix} 0.0 \\ 1.6 \end{bmatrix}\]

&lt;p&gt;The first neuron outputs zero (it’s on the boundary), while the second is active. This creates a sparse representation—only one of two neurons is contributing. Now these activations feed into the output layer:&lt;/p&gt;

\[z^{[2]} = \begin{bmatrix} 1.0 &amp;amp; -0.5 \end{bmatrix} \begin{bmatrix} 0.0 \\ 1.6 \end{bmatrix} + 0.5 = 0 - 0.8 + 0.5 = -0.3\]

&lt;p&gt;The output layer receives a slightly negative input, suggesting the network currently leans toward predicting class 0. Applying sigmoid:&lt;/p&gt;

\[\hat{y} = \sigma(-0.3) = \frac{1}{1 + e^{0.3}} \approx 0.426\]

&lt;p&gt;Our network predicts 42.6% probability of class 1, but the true label is 1 (100% probability). The loss, using binary cross-entropy, is:&lt;/p&gt;

\[\mathcal{L} = -[1 \cdot \log(0.426) + 0 \cdot \log(1-0.426)] = -\log(0.426) \approx 0.853\]

&lt;p&gt;This loss quantifies our mistake. Now backpropagation will tell us how to adjust each weight to reduce this loss.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Backward Pass&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;Starting from the output, the error is:&lt;/p&gt;

\[\delta^{[2]} = \hat{y} - y = 0.426 - 1 = -0.574\]

&lt;p&gt;This negative error means our output is too low—we need to increase it. The gradient with respect to the output layer weights is:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[2]}} = \delta^{[2]} (\mathbf{a}^{[1]})^T = -0.574 \times \begin{bmatrix} 0.0 &amp;amp; 1.6 \end{bmatrix} = \begin{bmatrix} 0 &amp;amp; -0.918 \end{bmatrix}\]

&lt;p&gt;The gradient is zero for the connection from the first hidden neuron (which was inactive) and -0.918 for the second. This tells us to increase \(W^{[2]}_2\) (currently -0.5) to make the output larger. This makes perfect sense: the second hidden neuron was active and could have contributed more to the output, so we strengthen that connection.&lt;/p&gt;

&lt;p&gt;Now we propagate error to the hidden layer:&lt;/p&gt;

\[\boldsymbol{\delta}^{[1]} = (\mathbf{W}^{[2]})^T \delta^{[2]} \odot \text{ReLU}&apos;(\mathbf{z}^{[1]})\]

&lt;p&gt;Let’s compute each part. The weights-transposed-times-error gives:&lt;/p&gt;

\[(\mathbf{W}^{[2]})^T \delta^{[2]} = \begin{bmatrix} 1.0 \\ -0.5 \end{bmatrix} \times (-0.574) = \begin{bmatrix} -0.574 \\ 0.287 \end{bmatrix}\]

&lt;p&gt;The ReLU derivative is 1 where the input was positive, 0 where it was negative:&lt;/p&gt;

\[\text{ReLU}&apos;(\mathbf{z}^{[1]}) = \text{ReLU}&apos;\begin{pmatrix} \begin{bmatrix} 0.0 \\ 1.6 \end{bmatrix} \end{pmatrix} = \begin{bmatrix} 0 \\ 1 \end{bmatrix}\]

&lt;p&gt;Note that the first hidden neuron, which was exactly at the threshold (\(z=0\)), has zero gradient. This is the dying ReLU problem in action—neurons at or below zero don’t propagate gradients. The element-wise product gives:&lt;/p&gt;

\[\boldsymbol{\delta}^{[1]} = \begin{bmatrix} -0.574 \\ 0.287 \end{bmatrix} \odot \begin{bmatrix} 0 \\ 1 \end{bmatrix} = \begin{bmatrix} 0 \\ 0.287 \end{bmatrix}\]

&lt;p&gt;Finally, the input layer weight gradients:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[1]}} = \boldsymbol{\delta}^{[1]} \mathbf{x}^T = \begin{bmatrix} 0 \\ 0.287 \end{bmatrix} \begin{bmatrix} 1.0 &amp;amp; 2.0 \end{bmatrix} = \begin{bmatrix} 0 &amp;amp; 0 \\ 0.287 &amp;amp; 0.574 \end{bmatrix}\]

&lt;p&gt;Only the second hidden neuron’s weights receive gradients. The gradient suggests increasing both weights to make this neuron activate more strongly for similar inputs, which would ultimately increase the network’s output toward the target of 1.&lt;/p&gt;

&lt;p&gt;This step-by-step walkthrough reveals the logic of backpropagation. Errors flow backward through the network, attenuated by the local derivatives. Active neurons with strong connections to high-error outputs receive large gradients and update substantially. Inactive neurons or those with weak connections receive small gradients and update little or not at all. This automatic assignment of credit and blame is what enables networks to learn complex functions—each parameter adjusts proportionally to its contribution to the error.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Backpropagation, intuitively&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 3](https://www.youtube.com/watch?v=Ilg3gGewQ5U) — 3Blue1Brown, English. One training example and the local gradient it produces.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Backpropagation calculus&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 4](https://www.youtube.com/watch?v=tIeHLnjs5U8) — 3Blue1Brown, English. Writes the chain rule the worked numerical example is computing.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=IN2XmBhILt4&quot;&gt;Neural Networks Pt. 2: Backpropagation Main Ideas&lt;/a&gt; — StatQuest with Josh Starmer, English. A fully labeled backprop pass, useful while you check the lesson’s arithmetic.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-02 Gradient Descent</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_02_Gradient_Descent/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_02_Gradient_Descent</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;In 1847, Augustin-Louis Cauchy proposed walking downhill step by step to solve astronomical orbit equations. Nearly two centuries later, that exact local descent rule—augmented with mini-batches, momentum, and adaptive step sizes—trains every large neural network on Earth.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-mechanics-of-gradient-descent&quot;&gt;Key ideas: Mechanics of Gradient Descent&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Iterative Local Minimization&lt;/strong&gt;: Updates \(\boldsymbol{\theta}_{t+1} = \boldsymbol{\theta}_t - \eta \nabla L(\boldsymbol{\theta}_t)\), relying on local first-order slopes because closed-form solutions (\(\nabla L = \mathbf{0}\)) are intractable for nonlinear networks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step-Size Stability Boundary&lt;/strong&gt;: Too small an \(\eta\) stalls convergence; too large an \(\eta\) (exceeding \(2/L_{\text{smooth}}\)) overshoots the valley and causes geometric explosion.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stochastic Mini-Batch Noise&lt;/strong&gt;: Approximating the full gradient on \(B\) samples trades variance for massive speedups per epoch and adds implicit noise that helps escape sharp minima and saddle points.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Curvature &amp;amp; Conditioning Challenges&lt;/strong&gt;: Ravines with wildly different slopes across axes cause vanilla GD to oscillate across steep walls while creeping along flat valleys.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-watching-step-size-eta-switch-between-convergence-exact-jump-and-divergence&quot;&gt;Worked example: Watching Step Size \(\eta\) Switch Between Convergence, Exact Jump, and Divergence&lt;/h3&gt;

&lt;p&gt;Minimize \(L(w) = 2w^2\) (exact minimum at \(w^* = 0\), gradient \(L&apos;(w) = 4w\), curvature \(L&apos;&apos;(w) = 4\)) starting from \(w_0 = 5\). Update rule: \(w_{t+1} = w_t - \eta(4w_t) = (1 - 4\eta)w_t\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Regime 1: Smooth Convergence (\(\eta = 0.1\))&lt;/strong&gt;:
Multiplier \(1 - 4(0.1) = 0.6\):
\(w_0 = 5 \to w_1 = 3.0 \to w_2 = 1.8 \to w_3 = 1.08 \to 0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Regime 2: Exact One-Step Convergence (\(\eta = 1/L&apos;&apos; = 0.25\))&lt;/strong&gt;:
Multiplier \(1 - 4(0.25) = 0\):
\(w_1 = 0 \quad \text{(hits the exact minimum in 1 step!)}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Regime 3: Critical Oscillation (\(\eta = 2/L&apos;&apos; = 0.5\))&lt;/strong&gt;:
Multiplier \(1 - 4(0.5) = -1\):
\(w_0 = 5 \to w_1 = -5 \to w_2 = 5 \to w_3 = -5 \quad \text{(bounces forever!)}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Regime 4: Divergence (\(\eta = 0.6 &amp;gt; 0.5\))&lt;/strong&gt;:
Multiplier \(1 - 4(0.6) = -1.4\):
\(w_0 = 5 \to w_1 = -7.0 \to w_2 = +9.8 \to w_3 = -13.72 \to \pm\infty\)
That single threshold \(\eta &amp;lt; 2/\lambda_{\max}\) governs stability across all of deep learning.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Gradient descent and its practical variants:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Descent Variants and Learning Rate&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Implementation and Challenges&lt;/strong&gt; — code, convergence criteria, common difficulties&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, English. The downhill picture of gradient descent.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, English. A numeric step-by-step of the same update, including the learning-rate choice.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vMh0zPT0tLI&quot;&gt;Stochastic Gradient Descent, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Stochastic gradient descent is the variant the lesson contrasts with full-batch descent.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-02-02 Gradient Descent Implementation and Challenges</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_02_02_GD_Implementation_and_Challenges/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_02_02_GD_Implementation_and_Challenges</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Writing a 10-line gradient descent loop in NumPy is easy; keeping it from oscillating in narrow ravines, stalling on high-dimensional saddle points, or diverging from unscaled features is where real optimization engineering begins.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-practical-obstacles-in-gradient-descent&quot;&gt;Key ideas: Practical Obstacles in Gradient Descent&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Ill-Conditioned Ravines (Anisotropic Curvature)&lt;/strong&gt;: When one parameter axis is \(100\times\) steeper than another, vanilla GD bounces violently across the narrow canyon while barely moving along the valley floor.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Saddle Points vs. Local Minima&lt;/strong&gt;: In high-dimensional parameter spaces (\(d \gg 10^6\)), nearly all critical points with \(\nabla L = \mathbf{0}\) are saddle points (some positive, some negative Hessian eigenvalues), where deterministic GD can stall indefinitely.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Feature Scaling &amp;amp; Condition Number&lt;/strong&gt;: Feeding unnormalized features (e.g., age \([0, 100]\) next to income \([0, 10^6]\)) stretches loss contours by \(10^4\times\), crippling vanilla GD until features are standardized.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vectorized Implementation &amp;amp; Numerical Checks&lt;/strong&gt;: Replacing Python loops with matrix ops and verifying analytic gradients against finite-difference numerical gradients eliminates silent bugs.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-watching-vanilla-gd-zig-zag-in-an-ill-conditioned-valley&quot;&gt;Worked example: Watching Vanilla GD Zig-Zag in an Ill-Conditioned Valley&lt;/h3&gt;

&lt;p&gt;Minimize \(L(w_1, w_2) = 0.5 w_1^2 + 5 w_2^2\) (Hessian eigenvalues \(\lambda_1 = 1, \lambda_2 = 10\), condition number \(\kappa = 10\)), starting at \((w_1, w_2) = (10, 1)\) with learning rate \(\eta = 0.18\) (just under the stability limit \(2/\lambda_2 = 0.20\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Gradients&lt;/strong&gt;:
\(\frac{\partial L}{\partial w_1} = w_1, \qquad \frac{\partial L}{\partial w_2} = 10 w_2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trace Step 1 (\(t = 0 \to 1\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(w_1^{(1)} = 10 - 0.18(10) = 8.20\) (smooth progress toward \(0\)).&lt;/li&gt;
      &lt;li&gt;\(w_2^{(1)} = 1 - 0.18(10 \times 1) = 1 - 1.8 = -0.80\) (overshot zero to the opposite wall!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Trace Step 2 (\(t = 1 \to 2\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(w_1^{(2)} = 8.20 - 0.18(8.20) = 6.724\).&lt;/li&gt;
      &lt;li&gt;\(w_2^{(2)} = -0.80 - 0.18(-8.0) = -0.80 + 1.44 = +0.64\) (bounced back across zero!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diagnosis&lt;/strong&gt;:
Even though \(\eta = 0.18\) is barely safe for \(w_2\) (decay factor \(-0.8\) per step), \(w_1\) only shrinks by \(0.82\) per step. Increasing \(\eta\) to speed up \(w_1\) immediately blows up \(w_2\)! Rescaling features or adding momentum resolves this exact bottleneck.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;implementation&quot;&gt;Implementation&lt;/h2&gt;

&lt;h3 id=&quot;basic-gradient-descent&quot;&gt;Basic Gradient Descent&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Basic gradient descent for linear regression
    
    X: (m, n) input matrix
    y: (m, 1) target vector
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Initialize parameters
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Forward pass: predictions
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute cost
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute gradient
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Update parameters
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Print progress
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Iteration &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Cost = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example usage
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 100 examples, 3 features
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 100 targets
&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;theta_optimal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;costs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;mini-batch-gradient-descent&quot;&gt;Mini-Batch Gradient Descent&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mini_batch_gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Mini-batch gradient descent
    
    X: (m, n) input matrix
    y: (m, 1) target vector
    batch_size: size of each mini-batch
    num_epochs: number of complete passes through the dataset
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Shuffle data
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;permutation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_shuffled&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;indices&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Process mini-batches
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Get batch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;y_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_shuffled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Compute gradient on batch
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size_actual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_batch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Update parameters
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Compute cost on full dataset (for monitoring)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;y_pred_full&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred_full&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: Cost = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cost_history&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example usage
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta_optimal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;costs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mini_batch_gradient_descent&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
    &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
    &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
    &lt;span class=&quot;n&quot;&gt;num_epochs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;50&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;with-learning-rate-schedule&quot;&gt;With Learning Rate Schedule&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LearningRateSchedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;get_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;decay_rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;decay_steps&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;decay_steps&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decay_steps&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;exponential&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;decay_rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.95&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;inverse&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;kwargs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;decay_rate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent_with_schedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Gradient descent with learning rate schedule&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;lr_schedule&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LearningRateSchedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;schedule_type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decay_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;decay_steps&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Get current learning rate
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr_schedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;get_lr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward and gradient computation
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Update with current learning rate
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Iteration &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;: LR = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Cost = &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example usage
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;theta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gradient_descent_with_schedule&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial_lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;num_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;convergence-criteria&quot;&gt;Convergence Criteria&lt;/h2&gt;

&lt;p&gt;How do we know when to stop training?&lt;/p&gt;

&lt;h3 id=&quot;1-maximum-iterations&quot;&gt;1. Maximum Iterations&lt;/h3&gt;

&lt;p&gt;Stop after a fixed number of iterations/epochs.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;2-cost-threshold&quot;&gt;2. Cost Threshold&lt;/h3&gt;

&lt;p&gt;Stop when cost drops below a threshold.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;threshold&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;3-gradient-magnitude&quot;&gt;3. Gradient Magnitude&lt;/h3&gt;

&lt;p&gt;Stop when gradient is very small (near stationary point).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linalg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;norm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;gradient&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;4-cost-change&quot;&gt;4. Cost Change&lt;/h3&gt;

&lt;p&gt;Stop when cost stops decreasing significantly.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cost&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;previous_cost&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;5-validation-loss-most-common-in-deep-learning&quot;&gt;5. Validation Loss (Most Common in Deep Learning)&lt;/h3&gt;

&lt;p&gt;Stop when validation loss stops improving (early stopping).&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;validation_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;best_validation_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;patience_counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;patience_counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;patience&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;best_validation_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;validation_loss&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;patience_counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;challenges-with-gradient-descent&quot;&gt;Challenges with Gradient Descent&lt;/h2&gt;

&lt;h3 id=&quot;1-local-minima&quot;&gt;1. Local Minima&lt;/h3&gt;

&lt;p&gt;Non-convex functions (like neural networks) have multiple local minima.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solutions:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Random initialization (try different starting points)&lt;/li&gt;
  &lt;li&gt;Momentum (covered in advanced optimizers)&lt;/li&gt;
  &lt;li&gt;Simulated annealing&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-saddle-points&quot;&gt;2. Saddle Points&lt;/h3&gt;

&lt;p&gt;Points where gradient is zero but not a minimum.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solutions:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Momentum and adaptive learning rates help escape&lt;/li&gt;
  &lt;li&gt;Second-order methods (Newton’s method)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-plateaus&quot;&gt;3. Plateaus&lt;/h3&gt;

&lt;p&gt;Flat regions where gradient is very small.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solutions:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Patience (wait longer)&lt;/li&gt;
  &lt;li&gt;Learning rate schedules&lt;/li&gt;
  &lt;li&gt;Adaptive optimizers (Adam, RMSprop)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-vanishingexploding-gradients&quot;&gt;4. Vanishing/Exploding Gradients&lt;/h3&gt;

&lt;p&gt;Gradients become too small or too large in deep networks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solutions:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Proper initialization (Xavier, He)&lt;/li&gt;
  &lt;li&gt;Batch normalization&lt;/li&gt;
  &lt;li&gt;Residual connections&lt;/li&gt;
  &lt;li&gt;Gradient clipping (for exploding gradients)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Gradient descent&lt;/strong&gt; is the fundamental deep-learning algorithm for neural networks&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Update rule&lt;/strong&gt;: \(\theta := \theta - \eta \nabla_{\theta} J(\theta)\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mini-batch gradient descent&lt;/strong&gt; is the most commonly used variant&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Learning rate&lt;/strong&gt; \(\eta\) is crucial: too small → slow, too large → unstable&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Learning rate schedules&lt;/strong&gt; can improve convergence&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convergence criteria&lt;/strong&gt; help determine when to stop training&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Challenges&lt;/strong&gt; include local minima, saddle points, and gradient issues&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the next lesson, we’ll explore &lt;strong&gt;backpropagation&lt;/strong&gt;, the algorithm that efficiently computes gradients in neural networks.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, English. A convergence check you can code: stop when the step gets small.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vMh0zPT0tLI&quot;&gt;Stochastic Gradient Descent, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Noise in the stochastic gradient is the main challenge the implementation section has to live with.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, English. The training loop that actually applies the update, which is the code half of this lesson.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-02-01 Gradient Descent Variants and Learning Rate</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_02_01_GD_Variants_and_Learning_Rate/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_02_01_GD_Variants_and_Learning_Rate</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Should you compute gradients over all 1,000,000 training examples before taking a single step, or update after every single sample? The answer—mini-batch SGD with a carefully scheduled learning rate—sits at the sweet spot between statistical variance, GPU vectorization, and generalization.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-gd-variants--learning-rate-dynamics&quot;&gt;Key ideas: GD Variants &amp;amp; Learning-Rate Dynamics&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Batch vs. Stochastic vs. Mini-Batch GD&lt;/strong&gt;: Trades off gradient variance (\(\propto \sigma^2 / B\)) against update frequency and hardware utilization; mini-batches (\(B = 32\) to \(4096\)) keep GPUs saturated while preserving helpful gradient noise.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Linear Scaling Rule &amp;amp; Warmup&lt;/strong&gt;: Increasing batch size by \(k\times\) reduces gradient noise, often allowing a larger learning rate, while initial linear warmup prevents early instability before curvature statistics settle.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Learning Rate Schedules (Step, Cosine, Exponential)&lt;/strong&gt;: Starts high to traverse flat plateaus and escape poor basins, then decays smoothly so stochastic updates settle tightly inside the bottom of a minimum.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Variance Floor of Constant-LR SGD&lt;/strong&gt;: With a fixed \(\eta\), noisy mini-batch gradients orbit in a ball of radius \(O(\eta \sigma^2)\) around the optimum rather than converging to zero error—necessitating decay.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-quantifying-gradient-variance-reduction-across-batch-sizes&quot;&gt;Worked example: Quantifying Gradient Variance Reduction Across Batch Sizes&lt;/h3&gt;

&lt;p&gt;Suppose a dataset of \(N = 4\) points has individual gradients \(g_1 = 2, g_2 = 6, g_3 = 10, g_4 = 14\) at the current weight \(w\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Exact Full-Batch Gradient (\(B = 4\))&lt;/strong&gt;:
\(\bar{g} = \frac{2 + 6 + 10 + 14}{4} = \frac{32}{4} = 8.0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Single-Sample SGD Variance (\(B = 1\))&lt;/strong&gt;:
\(\sigma_1^2 = \frac{1}{4}\left[(2-8)^2 + (6-8)^2 + (10-8)^2 + (14-8)^2\right] = \frac{36 + 4 + 4 + 36}{4} = \frac{80}{4} = 20.0\)
Standard deviation of a single-sample gradient is \(\sqrt{20} \approx 4.47\) (over 55% of the true gradient magnitude!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare Mini-Batch Size \(B = 2\) (Sampling With Replacement)&lt;/strong&gt;:
For i.i.d. mini-batches of size \(B\), variance scales strictly as \(\sigma_B^2 = \sigma_1^2 / B\):
\(\sigma_2^2 = \frac{20.0}{2} = 10.0 \quad (\text{std} \approx 3.16)\)
And for \(B = 64\) on a large dataset with \(\sigma_1^2 = 20.0\), variance drops to \(20/64 = 0.3125\) (std \(\approx 0.56\)), yielding an \(8\times\) cleaner descent direction per step while letting the GPU process all 64 samples in parallel!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson introduces gradient descent, the fundamental deep-learning algorithm used to train neural networks.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;the-deep-learning-problem&quot;&gt;The Deep Learning Problem&lt;/h2&gt;

&lt;p&gt;Training a neural network is an &lt;strong&gt;deep-learning problem&lt;/strong&gt;: Find parameters \(\theta = \{\mathbf{W}^{[1]}, \mathbf{b}^{[1]}, \ldots, \mathbf{W}^{[L]}, \mathbf{b}^{[L]}\}\) that minimize the cost function:&lt;/p&gt;

\[\theta^* = \arg\min_{\theta} J(\theta)\]

&lt;p&gt;where \(J(\theta)\) is the average loss over all training examples.&lt;/p&gt;

&lt;h2 id=&quot;gradient-descent-the-core-idea&quot;&gt;Gradient Descent: The Core Idea&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Gradient_descent.svg/600px-Gradient_descent.svg.png&quot; alt=&quot;Gradient Descent Visualization&quot; /&gt;
&lt;em&gt;Hình ảnh: Minh họa Gradient Descent trên hàm mất mát. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gradient descent&lt;/strong&gt; is an iterative deep-learning algorithm that moves parameters in the direction that decreases the cost function most rapidly.&lt;/p&gt;

&lt;h3 id=&quot;the-gradient&quot;&gt;The Gradient&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;gradient&lt;/strong&gt; \(\nabla_{\theta} J(\theta)\) is a vector of partial derivatives:&lt;/p&gt;

\[\nabla_{\theta} J = \begin{bmatrix} \frac{\partial J}{\partial \theta_1} \\ \frac{\partial J}{\partial \theta_2} \\ \vdots \\ \frac{\partial J}{\partial \theta_n} \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Key property&lt;/strong&gt;: The gradient points in the direction of &lt;strong&gt;steepest ascent&lt;/strong&gt;. Therefore, the negative gradient points in the direction of &lt;strong&gt;steepest descent&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;update-rule&quot;&gt;Update Rule&lt;/h3&gt;

&lt;p&gt;The gradient descent update rule is:&lt;/p&gt;

\[\theta := \theta - \eta \nabla_{\theta} J(\theta)\]

&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\eta\) is the &lt;strong&gt;learning rate&lt;/strong&gt; (a positive scalar hyperparameter)&lt;/li&gt;
  &lt;li&gt;\(:=\) denotes assignment/update&lt;/li&gt;
  &lt;li&gt;\(\nabla_{\theta} J(\theta)\) is the gradient of the cost function&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;For each parameter in a neural network:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{W}^{[l]} := \mathbf{W}^{[l]} - \eta \frac{\partial J}{\partial \mathbf{W}^{[l]}}\]

\[\mathbf{b}^{[l]} := \mathbf{b}^{[l]} - \eta \frac{\partial J}{\partial \mathbf{b}^{[l]}}\]

&lt;h3 id=&quot;geometric-intuition&quot;&gt;Geometric Intuition&lt;/h3&gt;

&lt;p&gt;Imagine you’re on a mountainside and want to reach the valley (minimum):&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Check the slope around you (compute gradient)&lt;/li&gt;
  &lt;li&gt;Take a step downhill (in the direction of negative gradient)&lt;/li&gt;
  &lt;li&gt;Repeat until you reach the bottom (convergence)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The learning rate \(\eta\) determines the &lt;strong&gt;step size&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;variants-of-gradient-descent&quot;&gt;Variants of Gradient Descent&lt;/h2&gt;

&lt;h3 id=&quot;1-batch-gradient-descent-vanilla-gd&quot;&gt;1. Batch Gradient Descent (Vanilla GD)&lt;/h3&gt;

&lt;p&gt;Uses &lt;strong&gt;all training examples&lt;/strong&gt; to compute the gradient at each step.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Algorithm:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Repeat until convergence:
    1. Compute gradient using all m examples:
       ∇J(θ) = (1/m) Σᵢ₌₁ᵐ ∇L(ŷ⁽ⁱ⁾, y⁽ⁱ⁾)
    
    2. Update parameters:
       θ := θ - η ∇J(θ)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Guaranteed to converge to global minimum (for convex functions)&lt;/li&gt;
  &lt;li&gt;Stable convergence&lt;/li&gt;
  &lt;li&gt;Can use theoretical convergence guarantees&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Very slow&lt;/strong&gt; for large datasets (must process all data before one update)&lt;/li&gt;
  &lt;li&gt;Requires entire dataset in memory&lt;/li&gt;
  &lt;li&gt;Can get stuck in local minima (for non-convex functions)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-stochastic-gradient-descent-sgd&quot;&gt;2. Stochastic Gradient Descent (SGD)&lt;/h3&gt;

&lt;p&gt;Uses &lt;strong&gt;one random training example&lt;/strong&gt; at a time to compute the gradient.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Algorithm:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Repeat until convergence:
    1. Randomly shuffle training data
    
    2. For each example i:
        a. Compute gradient using only example i:
           ∇L(ŷ⁽ⁱ⁾, y⁽ⁱ⁾)
        
        b. Update parameters:
           θ := θ - η ∇L(ŷ⁽ⁱ⁾, y⁽ⁱ⁾)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Much faster&lt;/strong&gt; updates (can start learning immediately)&lt;/li&gt;
  &lt;li&gt;Can escape local minima due to noisy updates&lt;/li&gt;
  &lt;li&gt;Online learning possible (process data streams)&lt;/li&gt;
  &lt;li&gt;Memory efficient&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Noisy gradient estimates&lt;/strong&gt; → erratic convergence path&lt;/li&gt;
  &lt;li&gt;Never truly “converges” (oscillates around minimum)&lt;/li&gt;
  &lt;li&gt;Harder to parallelize&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-mini-batch-gradient-descent-most-common&quot;&gt;3. Mini-Batch Gradient Descent (Most Common)&lt;/h3&gt;

&lt;p&gt;Uses a &lt;strong&gt;small batch of examples&lt;/strong&gt; (typically 32, 64, 128, or 256) to compute the gradient.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Algorithm:&lt;/strong&gt;&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Repeat until convergence:
    1. Randomly shuffle training data
    
    2. Divide data into mini-batches of size B
    
    3. For each mini-batch:
        a. Compute gradient using the batch:
           ∇J_batch(θ) = (1/B) Σᵢ∈batch ∇L(ŷ⁽ⁱ⁾, y⁽ⁱ⁾)
        
        b. Update parameters:
           θ := θ - η ∇J_batch(θ)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Best of both worlds&lt;/strong&gt;: Fast updates + stable convergence&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Highly parallelizable&lt;/strong&gt;: Can utilize GPU/TPU efficiently&lt;/li&gt;
  &lt;li&gt;Reduced variance in gradient estimates&lt;/li&gt;
  &lt;li&gt;Memory efficient (process batches, not entire dataset)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Introduces batch size as a hyperparameter&lt;/li&gt;
  &lt;li&gt;Still has some noise (less than SGD)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;comparison-table&quot;&gt;Comparison Table&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Variant&lt;/th&gt;
      &lt;th&gt;Examples per Update&lt;/th&gt;
      &lt;th&gt;Speed&lt;/th&gt;
      &lt;th&gt;Stability&lt;/th&gt;
      &lt;th&gt;Memory&lt;/th&gt;
      &lt;th&gt;Parallelization&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Batch GD&lt;/td&gt;
      &lt;td&gt;All (m)&lt;/td&gt;
      &lt;td&gt;Slow&lt;/td&gt;
      &lt;td&gt;High&lt;/td&gt;
      &lt;td&gt;High&lt;/td&gt;
      &lt;td&gt;Difficult&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;SGD&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;Fast&lt;/td&gt;
      &lt;td&gt;Low&lt;/td&gt;
      &lt;td&gt;Low&lt;/td&gt;
      &lt;td&gt;Difficult&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Mini-batch GD&lt;/td&gt;
      &lt;td&gt;Batch size (B)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Fast&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Medium&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Low&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Easy&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Recommendation&lt;/strong&gt;: Use &lt;strong&gt;mini-batch gradient descent&lt;/strong&gt; with batch size 32-256.&lt;/p&gt;

&lt;h2 id=&quot;the-learning-rate&quot;&gt;The Learning Rate&lt;/h2&gt;

&lt;p&gt;The learning rate \(\eta\) is one of the most important hyperparameters.&lt;/p&gt;

&lt;h3 id=&quot;effect-of-learning-rate&quot;&gt;Effect of Learning Rate&lt;/h3&gt;

&lt;h4 id=&quot;too-small-eta-too-low&quot;&gt;Too Small (\(\eta\) too low)&lt;/h4&gt;
&lt;ul&gt;
  &lt;li&gt;Very slow convergence&lt;/li&gt;
  &lt;li&gt;May take too long to train&lt;/li&gt;
  &lt;li&gt;Can get stuck in plateaus&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;too-large-eta-too-high&quot;&gt;Too Large (\(\eta\) too high)&lt;/h4&gt;
&lt;ul&gt;
  &lt;li&gt;Unstable training&lt;/li&gt;
  &lt;li&gt;May overshoot minimum&lt;/li&gt;
  &lt;li&gt;Loss may diverge (increase)&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;just-right&quot;&gt;Just Right&lt;/h4&gt;
&lt;ul&gt;
  &lt;li&gt;Smooth, steady decrease in loss&lt;/li&gt;
  &lt;li&gt;Reasonable training time&lt;/li&gt;
  &lt;li&gt;Converges to good solution&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;typical-values&quot;&gt;Typical Values&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Good starting points&lt;/strong&gt;: 0.001, 0.01, 0.1&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Deep networks&lt;/strong&gt;: Often 0.001 - 0.01&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Shallow networks&lt;/strong&gt;: Can use higher rates (0.01 - 0.1)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;learning-rate-schedules&quot;&gt;Learning Rate Schedules&lt;/h3&gt;

&lt;p&gt;Instead of a fixed learning rate, use a &lt;strong&gt;schedule&lt;/strong&gt; that changes \(\eta\) during training:&lt;/p&gt;

&lt;h4 id=&quot;1-step-decay&quot;&gt;1. Step Decay&lt;/h4&gt;

\[\eta_t = \eta_0 \cdot \gamma^{\lfloor t / k \rfloor}\]

&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\eta_0\) is initial learning rate&lt;/li&gt;
  &lt;li&gt;\(\gamma \in (0, 1)\) is decay factor (e.g., 0.5)&lt;/li&gt;
  &lt;li&gt;\(k\) is step interval (e.g., every 10 epochs)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt;: Start at 0.1, multiply by 0.5 every 10 epochs&lt;/p&gt;

&lt;h4 id=&quot;2-exponential-decay&quot;&gt;2. Exponential Decay&lt;/h4&gt;

\[\eta_t = \eta_0 \cdot e^{-\lambda t}\]

&lt;p&gt;where \(\lambda\) is decay constant.&lt;/p&gt;

&lt;h4 id=&quot;3-1t-decay&quot;&gt;3. 1/t Decay&lt;/h4&gt;

\[\eta_t = \frac{\eta_0}{1 + \lambda t}\]

&lt;h4 id=&quot;4-cosine-annealing&quot;&gt;4. Cosine Annealing&lt;/h4&gt;

\[\eta_t = \eta_{\min} + \frac{1}{2}(\eta_{\max} - \eta_{\min})\left(1 + \cos\left(\frac{t}{T}\pi\right)\right)\]

&lt;p&gt;where \(T\) is the total number of iterations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Warm restarts&lt;/strong&gt;: Periodically reset learning rate to initial value.&lt;/p&gt;

&lt;h4 id=&quot;5-learning-rate-warm-up&quot;&gt;5. Learning Rate Warm-up&lt;/h4&gt;

&lt;p&gt;Start with very small learning rate and gradually increase to target value:&lt;/p&gt;

\[\eta_t = \eta_0 \cdot \min\left(1, \frac{t}{T_{\text{warmup}}}\right)\]

&lt;p&gt;&lt;strong&gt;Use case&lt;/strong&gt;: Large batch training, transformers&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, English. The learning rate is the step length on the cost surface this lesson studies.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, English. Computes one update by hand so batch, stochastic, and mini-batch are easier to tell apart.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vMh0zPT0tLI&quot;&gt;Stochastic Gradient Descent, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Stochastic updates are the variant the lesson recommends once the dataset no longer fits in one step.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-01 Loss Functions</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_01_Loss_Functions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_01_Loss_Functions</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Tell a neural network to minimize Mean Squared Error on a dataset with 2% corrupted outliers and it will contort its entire decision surface just to appease those outliers; switch to Huber or Cross-Entropy and the exact same architecture suddenly generalizes. A loss function is the silent specification of what your model truly optimizes.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-designing-and-choosing-loss-functions&quot;&gt;Key ideas: Designing and Choosing Loss Functions&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Statistical Likelihood Correspondence&lt;/strong&gt;: Matches each loss to an underlying noise model—MSE to Gaussian noise, MAE to Laplace noise, Binary Cross-Entropy to Bernoulli labels, and Categorical Cross-Entropy to multinomial labels.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Geometry &amp;amp; Outlier Sensitivity&lt;/strong&gt;: Determines how strongly large errors pull the weights—MSE gradients grow linearly without bound (\(2e\)), MAE gradients stay constant (\(\pm 1\)), and cross-entropy gradients scale directly with probability error (\(\hat{p} - y\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Differentiability &amp;amp; Convexity in Logits&lt;/strong&gt;: Ensures smooth, well-behaved optimization with respect to the network’s final linear layer even when the full network is non-convex.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Task &amp;amp; Calibration Alignment&lt;/strong&gt;: Connects surrogate training losses (differentiable) to non-differentiable business metrics (accuracy, F1, IoU) while preserving probability calibration.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-how-one-outlier-pulls-mse-vs-mae-gradients&quot;&gt;Worked example: How One Outlier Pulls MSE vs. MAE Gradients&lt;/h3&gt;

&lt;p&gt;Suppose a constant predictor \(\hat{y} = c\) tries to fit three targets \(y = \{1, 2, 100\}\) (two normal points and one extreme outlier). Compare the optimal \(c^*\) and gradients at \(c = 2\) under MSE and MAE.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Under MSE (\(L_{\text{MSE}}(c) = \frac{1}{3}\sum (c - y_i)^2\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Residuals at \(c = 2\): \((1, 0, -98)\).&lt;/li&gt;
      &lt;li&gt;Gradient at \(c = 2\): \(\frac{2}{3}(1 + 0 - 98) = -\frac{194}{3} \approx -64.67\) (massive pull toward the outlier!).&lt;/li&gt;
      &lt;li&gt;Minimizer is the &lt;strong&gt;sample mean&lt;/strong&gt;: \(c^*_{\text{MSE}} = \frac{1 + 2 + 100}{3} = 34.33\)—terrible for the normal points \(1\) and \(2\)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Under MAE (\(L_{\text{MAE}}(c) = \frac{1}{3}\sum \lvert c - y_i\rvert\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Subgradients at \(c = 2\): \(+1\) (from \(y=1\)), \(0\) (from \(y=2\)), \(-1\) (from \(y=100\)).&lt;/li&gt;
      &lt;li&gt;Average subgradient: \(\frac{1}{3}(+1 + 0 - 1) = 0\)!&lt;/li&gt;
      &lt;li&gt;Minimizer is the &lt;strong&gt;sample median&lt;/strong&gt;: \(c^*_{\text{MAE}} = 2.0\)—completely unbothered by whether the outlier is \(100\) or \(1{,}000{,}000\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Loss functions for training neural networks:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Regression Loss Functions&lt;/strong&gt; — what is a loss, MSE, MAE, Huber&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Classification Losses and Choosing a Loss&lt;/strong&gt; — binary/multi-class losses, practical tips, selection guide&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Lecture 3&lt;/td&gt;
          &lt;td&gt;Loss Functions and Optimization](https://www.youtube.com/watch?v=h7iBpEHGVNc) — Stanford University School of Engineering, English. The role of a loss, before the regression and classification splits.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=yIYKR4sgzI8&quot;&gt;StatQuest: Logistic Regression&lt;/a&gt; — StatQuest with Josh Starmer, English. Logistic regression is the binary classification loss the second lesson derives.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is cross-entropy?&lt;/td&gt;
          &lt;td&gt;Compression is Intelligence Part 2](https://www.youtube.com/watch?v=GlYgs6v2YfU) — 3Blue1Brown, English. Cross-entropy is the multi-class and language-model loss the same lesson names.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-01-02 Classification Losses and Choosing a Loss</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_01_02_Classification_Losses/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_01_02_Classification_Losses</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Why do we never train a softmax classifier with Mean Squared Error? Try computing the gradient of MSE through a sigmoid when the network is dead wrong (\(y = 1, \hat{y} = 0.01\)): the sigmoid derivative \(\hat{y}(1-\hat{y}) \approx 0.01\) nearly zeroes out the error signal! Cross-entropy cancels that saturation factor completely.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-classification-losses--information-geometry&quot;&gt;Key ideas: Classification Losses &amp;amp; Information Geometry&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Binary Cross-Entropy (Log Loss)&lt;/strong&gt;: Measures negative log-likelihood of a Bernoulli output; paired with sigmoid, its logit gradient is simply \(\hat{p} - y\), delivering maximum corrective push when the model is confidently wrong.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Categorical &amp;amp; Sparse Cross-Entropy&lt;/strong&gt;: Generalizes BCE to \(K\) mutually exclusive classes via \(-\sum_k y_k \log p_k\); sparse cross-entropy avoids materializing huge one-hot vectors by indexing directly into the true class’s log-probability.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;KL Divergence (Distillation &amp;amp; Soft Targets)&lt;/strong&gt;: Measures directed divergence \(D_{\text{KL}}(p \| q) = \sum_k p_k \log(p_k / q_k)\), essential when training student models to match a teacher’s soft probability distribution.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hinge &amp;amp; Margin Losses&lt;/strong&gt;: Push the true class score above competing classes by a fixed geometric margin (e.g., \(\max(0, 1 - y z)\)), prioritizing decision-boundary separation over calibrated probabilities.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-computing-multi-class-cross-entropy-and-its-logit-gradient&quot;&gt;Worked example: Computing Multi-Class Cross-Entropy and Its Logit Gradient&lt;/h3&gt;

&lt;p&gt;Suppose a 3-class classifier outputs logits \(\mathbf{z} = [2.0, 1.0, 0.0]\) for an example whose true label is Class 1 (one-hot \(\mathbf{y} = [0, 1, 0]\)). Use \(e^2 \approx 7.389, e^1 \approx 2.718, e^0 = 1.000\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Softmax Probabilities \(\mathbf{p} = \text{softmax}(\mathbf{z})\)&lt;/strong&gt;:
\(Z = 7.389 + 2.718 + 1.000 = 11.107\)
\(p_0 = \frac{7.389}{11.107} \approx 0.6653, \quad p_1 = \frac{2.718}{11.107} \approx 0.2447, \quad p_2 = \frac{1.000}{11.107} \approx 0.0900\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Categorical Cross-Entropy Loss&lt;/strong&gt;:
Only the true class (\(k = 1\)) contributes:
\(L = -\ln(p_1) = -\ln(0.2447) \approx 1.4076\text{ nats}\)
(Equivalently via LogSumExp: \(L = \ln(11.107) - z_1 = 2.4076 - 1.0 = 1.4076\).)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Exact Logit Gradient \(\frac{\partial L}{\partial \mathbf{z}} = \mathbf{p} - \mathbf{y}\)&lt;/strong&gt;:
\(\frac{\partial L}{\partial \mathbf{z}} = \begin{bmatrix} 0.6653 - 0 \\ 0.2447 - 1 \\ 0.0900 - 0 \end{bmatrix} = \begin{bmatrix} +0.6653 \\ -0.7553 \\ +0.0900 \end{bmatrix}\)
Check the zero-sum conservation law: \(0.6653 - 0.7553 + 0.0900 = 0.0000\). One gradient step pushes the true logit \(z_1\) &lt;strong&gt;up&lt;/strong&gt; by \(+0.7553\eta\) while pushing wrong logits \(z_0, z_2\) &lt;strong&gt;down&lt;/strong&gt; in exact proportion to their erroneous probabilities!&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;loss-functions-for-binary-classification&quot;&gt;Loss Functions for Binary Classification&lt;/h2&gt;

&lt;h3 id=&quot;1-binary-cross-entropy-log-loss&quot;&gt;1. Binary Cross-Entropy (Log Loss)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{BCE}}(\hat{y}, y) = -[y \log(\hat{y}) + (1-y) \log(1-\hat{y})]\]

&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(y \in \{0, 1\}\) is the true label&lt;/li&gt;
  &lt;li&gt;\(\hat{y} \in (0, 1)\) is the predicted probability&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Cost function:&lt;/strong&gt;&lt;/p&gt;

\[J_{\text{BCE}} = -\frac{1}{m} \sum_{i=1}^{m} [y^{(i)} \log(\hat{y}^{(i)}) + (1-y^{(i)}) \log(1-\hat{y}^{(i)})]\]

&lt;p&gt;&lt;strong&gt;Intuition:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;If \(y = 1\): Loss is \(-\log(\hat{y})\), minimized when \(\hat{y} \to 1\)&lt;/li&gt;
  &lt;li&gt;If \(y = 0\): Loss is \(-\log(1-\hat{y})\), minimized when \(\hat{y} \to 0\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Based on maximum likelihood estimation&lt;/li&gt;
  &lt;li&gt;Smooth and differentiable&lt;/li&gt;
  &lt;li&gt;Well-suited for gradient-based optimization&lt;/li&gt;
  &lt;li&gt;Heavily penalizes confident wrong predictions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Derivative (with sigmoid output):&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For output layer with sigmoid: \(\hat{y} = \sigma(z)\)&lt;/p&gt;

\[\frac{\partial \mathcal{L}_{\text{BCE}}}{\partial z} = \hat{y} - y\]

&lt;p&gt;This remarkably simple derivative makes training efficient!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Binary classification&lt;/strong&gt;: Is this image a cat or dog?&lt;/li&gt;
  &lt;li&gt;Output layer with sigmoid activation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Proper probabilistic interpretation&lt;/li&gt;
  &lt;li&gt;Strong gradients for wrong predictions&lt;/li&gt;
  &lt;li&gt;Well-suited for sigmoid outputs&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Can produce very large losses for confident wrong predictions&lt;/li&gt;
  &lt;li&gt;Requires predicted probabilities (not logits directly)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-hinge-loss-svm-loss&quot;&gt;2. Hinge Loss (SVM Loss)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{Hinge}}(\hat{y}, y) = \max(0, 1 - y \cdot \hat{y})\]

&lt;p&gt;where \(y \in \{-1, +1\}\) and \(\hat{y}\) is the raw score (not probability).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Used in Support Vector Machines&lt;/li&gt;
  &lt;li&gt;Encourages margin maximization&lt;/li&gt;
  &lt;li&gt;Not differentiable at \(y \cdot \hat{y} = 1\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Binary classification with SVM-like objectives&lt;/li&gt;
  &lt;li&gt;When you want maximum margin classifiers&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;loss-functions-for-multi-class-classification&quot;&gt;Loss Functions for Multi-Class Classification&lt;/h2&gt;

&lt;h3 id=&quot;1-categorical-cross-entropy&quot;&gt;1. Categorical Cross-Entropy&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{CCE}}(\hat{\mathbf{y}}, \mathbf{y}) = -\sum_{c=1}^{C} y_c \log(\hat{y}_c)\]

&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{y}\) is the true label in &lt;strong&gt;one-hot encoding&lt;/strong&gt;: \(y_c \in \{0, 1\}\), \(\sum_c y_c = 1\)&lt;/li&gt;
  &lt;li&gt;\(\hat{\mathbf{y}}\) is the predicted probability distribution: \(\hat{y}_c \in (0, 1)\), \(\sum_c \hat{y}_c = 1\)&lt;/li&gt;
  &lt;li&gt;\(C\) is the number of classes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Cost function:&lt;/strong&gt;&lt;/p&gt;

\[J_{\text{CCE}} = -\frac{1}{m} \sum_{i=1}^{m} \sum_{c=1}^{C} y_c^{(i)} \log(\hat{y}_c^{(i)})\]

&lt;p&gt;&lt;strong&gt;Simplified form&lt;/strong&gt; (since only one \(y_c = 1\)):&lt;/p&gt;

\[\mathcal{L}_{\text{CCE}} = -\log(\hat{y}_{c^*})\]

&lt;p&gt;where \(c^*\) is the true class.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Derivative (with softmax output):&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;For softmax output: \(\hat{\mathbf{y}} = \text{softmax}(\mathbf{z})\)&lt;/p&gt;

\[\frac{\partial \mathcal{L}_{\text{CCE}}}{\partial z_j} = \hat{y}_j - y_j\]

&lt;p&gt;Again, remarkably simple!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Multi-class classification&lt;/strong&gt;: Digit recognition (MNIST), image classification (ImageNet)&lt;/li&gt;
  &lt;li&gt;Output layer with softmax activation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Proper probabilistic framework&lt;/li&gt;
  &lt;li&gt;Standard for multi-class problems&lt;/li&gt;
  &lt;li&gt;Simple gradients with softmax&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Requires one-hot encoded labels&lt;/li&gt;
  &lt;li&gt;Can be numerically unstable (use log-softmax trick)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-sparse-categorical-cross-entropy&quot;&gt;2. Sparse Categorical Cross-Entropy&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Same as categorical cross-entropy, but accepts integer labels instead of one-hot encoding.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Input format:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(y \in \{0, 1, \ldots, C-1\}\) (integer class index)&lt;/li&gt;
  &lt;li&gt;\(\hat{\mathbf{y}} \in \mathbb{R}^C\) (probability distribution)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{SCCE}}(\hat{\mathbf{y}}, y) = -\log(\hat{y}_y)\]

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Multi-class classification with integer labels&lt;/li&gt;
  &lt;li&gt;Memory-efficient (no need to create one-hot vectors)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-kullback-leibler-kl-divergence&quot;&gt;3. Kullback-Leibler (KL) Divergence&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{KL}}(\mathbf{p}, \mathbf{q}) = \sum_{c=1}^{C} p_c \log\left(\frac{p_c}{q_c}\right) = \sum_{c=1}^{C} [p_c \log(p_c) - p_c \log(q_c)]\]

&lt;p&gt;where \(\mathbf{p}\) is the true distribution and \(\mathbf{q}\) is the predicted distribution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Measures “distance” between two probability distributions&lt;/li&gt;
  &lt;li&gt;Always non-negative&lt;/li&gt;
  &lt;li&gt;Not symmetric: \(\text{KL}(p \| q) \neq \text{KL}(q \| p)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Relation to Cross-Entropy:&lt;/strong&gt;&lt;/p&gt;

\[\text{KL}(p \| q) = H(p, q) - H(p)\]

&lt;p&gt;where \(H(p, q)\) is cross-entropy and \(H(p)\) is entropy of \(p\).&lt;/p&gt;

&lt;p&gt;Since \(H(p)\) is constant (true distribution doesn’t change), minimizing KL divergence is equivalent to minimizing cross-entropy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Variational autoencoders (VAE)&lt;/li&gt;
  &lt;li&gt;Distribution matching&lt;/li&gt;
  &lt;li&gt;Knowledge distillation&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practical-considerations&quot;&gt;Practical Considerations&lt;/h2&gt;

&lt;h3 id=&quot;numerical-stability&quot;&gt;Numerical Stability&lt;/h3&gt;

&lt;h4 id=&quot;problem-log-of-small-numbers&quot;&gt;Problem: Log of Small Numbers&lt;/h4&gt;

&lt;p&gt;Computing \(\log(\hat{y})\) when \(\hat{y}\) is very close to 0 can cause numerical issues.&lt;/p&gt;

&lt;h4 id=&quot;solution-clip-values&quot;&gt;Solution: Clip Values&lt;/h4&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1e-7&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_pred_clipped&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred_clipped&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;better-solution-logsumexp-trick&quot;&gt;Better Solution: LogSumExp Trick&lt;/h4&gt;

&lt;p&gt;For cross-entropy with softmax, compute loss directly from logits:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax_cross_entropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Numerically stable softmax + cross-entropy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Log-sum-exp trick
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;logits_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;log_sum_exp&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logits_max&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logits_max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;log_softmax&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;logits&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_sum_exp&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Cross-entropy
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;log_softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;implementation-examples&quot;&gt;Implementation Examples&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;LossFunctions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mse&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean Squared Error&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mae&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Mean Absolute Error&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;binary_crossentropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Binary Cross-Entropy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;categorical_crossentropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Categorical Cross-Entropy&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sparse_categorical_crossentropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1e-7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sparse Categorical Cross-Entropy
        
        y_true: integer labels (m,)
        y_pred: probabilities (m, C)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;clip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epsilon&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;log_likelihood&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;m&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;log_likelihood&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;huber&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Huber Loss&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;is_small_error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;squared_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;linear_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;**&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;mean&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;is_small_error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;squared_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;linear_loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example usage
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.9&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Binary Cross-Entropy:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LossFunctions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;binary_crossentropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Multi-class example
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true_categorical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_pred_categorical&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Categorical Cross-Entropy:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;LossFunctions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;categorical_crossentropy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_true_categorical&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred_categorical&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;choosing-the-right-loss-function&quot;&gt;Choosing the Right Loss Function&lt;/h2&gt;

&lt;h3 id=&quot;decision-tree&quot;&gt;Decision Tree&lt;/h3&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Task Type?
├─ Regression
│  ├─ With outliers? → MAE or Huber Loss
│  └─ Without outliers? → MSE
│
├─ Binary Classification
│  ├─ Probabilistic output? → Binary Cross-Entropy
│  └─ Margin-based? → Hinge Loss
│
└─ Multi-class Classification
   ├─ One-hot labels? → Categorical Cross-Entropy
   └─ Integer labels? → Sparse Categorical Cross-Entropy
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;quick-reference&quot;&gt;Quick Reference&lt;/h3&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Task&lt;/th&gt;
      &lt;th&gt;Loss Function&lt;/th&gt;
      &lt;th&gt;Output Activation&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Regression&lt;/td&gt;
      &lt;td&gt;MSE, MAE, Huber&lt;/td&gt;
      &lt;td&gt;Linear&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Binary Classification&lt;/td&gt;
      &lt;td&gt;Binary Cross-Entropy&lt;/td&gt;
      &lt;td&gt;Sigmoid&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Multi-class Classification&lt;/td&gt;
      &lt;td&gt;Categorical Cross-Entropy&lt;/td&gt;
      &lt;td&gt;Softmax&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Multi-label Classification&lt;/td&gt;
      &lt;td&gt;Binary Cross-Entropy (per label)&lt;/td&gt;
      &lt;td&gt;Sigmoid (per label)&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Loss functions&lt;/strong&gt; quantify the difference between predictions and true values&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Regression losses&lt;/strong&gt;: MSE (sensitive to outliers), MAE (robust), Huber (balanced)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Classification losses&lt;/strong&gt;: Cross-entropy (probabilistic, standard choice)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Binary classification&lt;/strong&gt;: Binary cross-entropy with sigmoid&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multi-class classification&lt;/strong&gt;: Categorical cross-entropy with softmax&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Numerical stability&lt;/strong&gt; is crucial when implementing loss functions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Choice of loss&lt;/strong&gt; should match the task and data characteristics&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the next lesson, we’ll learn about gradient descent, the algorithm that uses these loss functions to update network parameters.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=yIYKR4sgzI8&quot;&gt;StatQuest: Logistic Regression&lt;/a&gt; — StatQuest with Josh Starmer, English. Logistic loss for a yes/no label is the binary section.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is cross-entropy?&lt;/td&gt;
          &lt;td&gt;Compression is Intelligence Part 2](https://www.youtube.com/watch?v=GlYgs6v2YfU) — 3Blue1Brown, English. Cross-entropy is the multi-class loss, derived from coding length rather than as a formula to memorize.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=LLux1SW--oM&quot;&gt;Softmax Regression (C2W3L08)&lt;/a&gt; — DeepLearningAI, English. Softmax regression is the multi-class head the lesson asks you to choose when labels are one of K classes.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03-01-01 Regression Loss Functions</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_01_01_Regression_Losses/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_01_01_Regression_Losses</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Predicting house prices, battery lifetimes, or bounding-box coordinates looks simple until a single data-entry typo adds an extra zero to one label. Understanding how MSE, MAE, and Huber loss trade off smooth convergence near zero against robustness to extreme errors is essential for every regression model.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-regression-loss-geometry&quot;&gt;Key ideas: Regression Loss Geometry&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Mean Squared Error (MSE / \(L_2\))&lt;/strong&gt;: Smooth everywhere with gradient \(2(\hat{y} - y)\) that shrinks naturally as predictions approach the target, converging cleanly to the conditional mean \(\mathbb{E}[Y\mid X]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mean Absolute Error (MAE / \(L_1\))&lt;/strong&gt;: Linear penalty converging to the conditional median, robust to heavy-tailed outliers, but its constant-magnitude gradient \(\pm 1\) can oscillate around the minimum unless the learning rate decays.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Huber Loss (Smooth \(L_1\) Hybrid)&lt;/strong&gt;: Acts quadratically (\(\frac{1}{2}e^2\)) for small errors \(\lvert e\rvert \leq \delta\) and linearly (\(\delta(\lvert e\rvert - \frac{1}{2}\delta)\)) for large errors \(\lvert e\rvert &amp;gt; \delta\), combining smooth convergence near \(0\) with bounded outlier gradients \(\pm\delta\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scale &amp;amp; Metric Alignment&lt;/strong&gt;: Reminds practitioners to distinguish training loss (e.g., MSE) from interpretable evaluation units (RMSE in original units, \(R^2\), or MAPE).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-comparing-mse-mae-and-huber-loss-delta--10-across-small-and-large-errors&quot;&gt;Worked example: Comparing MSE, MAE, and Huber Loss (\(\delta = 1.0\)) Across Small and Large Errors&lt;/h3&gt;

&lt;p&gt;Compute loss value and gradient magnitude \(\left\lvert \frac{\partial L}{\partial \hat{y}}\right\rvert\) for two residuals: a small error \(e_1 = 0.5\) and an outlier error \(e_2 = 10.0\) (where \(e = \hat{y} - y\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Small Error (\(e_1 = 0.5 \leq \delta = 1.0\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Half-MSE&lt;/strong&gt; (\(\frac{1}{2}e^2\)): loss \(= \frac{1}{2}(0.5)^2 = 0.125\), gradient \(= 0.5\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;MAE&lt;/strong&gt; (\(\lvert e\rvert\)): loss \(= 0.500\), gradient \(= 1.0\) (twice as aggressive near the minimum!).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Huber (\(\delta = 1.0\))&lt;/strong&gt;: since \(\lvert e_1\rvert \leq 1.0\), uses quadratic branch: loss \(= 0.125\), gradient \(= 0.5\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Outlier Error (\(e_2 = 10.0 &amp;gt; \delta = 1.0\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Half-MSE&lt;/strong&gt;: loss \(= \frac{1}{2}(10)^2 = 50.0\), gradient \(= 10.0\) (huge destabilizing kick!).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;MAE&lt;/strong&gt;: loss \(= 10.0\), gradient \(= 1.0\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Huber (\(\delta = 1.0\))&lt;/strong&gt;: uses linear branch \(\delta(\lvert e\rvert - 0.5\delta) = 1.0(10.0 - 0.5) = 9.5\), gradient \(= \delta = 1.0\) (capped!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Takeaway&lt;/strong&gt;:
Huber matches MSE’s gentle vanishing gradient (\(0.5\)) near zero while matching MAE’s capped gradient (\(1.0\)) on outliers—which is why object detectors like Faster R-CNN rely on Smooth \(L_1\) / Huber loss for bounding-box regression.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers loss functions (also called cost functions or objective functions), which quantify how well a neural network is performing.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;what-is-a-loss-function&quot;&gt;What is a Loss Function?&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;loss function&lt;/strong&gt; \(\mathcal{L}\) measures the discrepancy between the predicted output \(\hat{y}\) and the true output \(y\). The goal of training is to find parameters \(\theta\) (weights and biases) that minimize this loss.&lt;/p&gt;

&lt;h3 id=&quot;single-example-loss&quot;&gt;Single Example Loss&lt;/h3&gt;

&lt;p&gt;For a single training example:&lt;/p&gt;

\[\mathcal{L}(\hat{y}, y)\]

&lt;h3 id=&quot;cost-function-total-loss&quot;&gt;Cost Function (Total Loss)&lt;/h3&gt;

&lt;p&gt;For a dataset with \(m\) examples, the &lt;strong&gt;cost function&lt;/strong&gt; \(J\) is typically the average loss:&lt;/p&gt;

\[J(\theta) = \frac{1}{m} \sum_{i=1}^{m} \mathcal{L}(\hat{y}^{(i)}, y^{(i)})\]

&lt;p&gt;Some formulations also include regularization terms (covered later).&lt;/p&gt;

&lt;h2 id=&quot;loss-functions-for-regression&quot;&gt;Loss Functions for Regression&lt;/h2&gt;

&lt;h3 id=&quot;1-mean-squared-error-mse&quot;&gt;1. Mean Squared Error (MSE)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{MSE}}(\hat{y}, y) = \frac{1}{2}(y - \hat{y})^2\]

&lt;p&gt;&lt;strong&gt;Cost function:&lt;/strong&gt;&lt;/p&gt;

\[J_{\text{MSE}} = \frac{1}{m} \sum_{i=1}^{m} \frac{1}{2}(y^{(i)} - \hat{y}^{(i)})^2 = \frac{1}{2m} \sum_{i=1}^{m} (y^{(i)} - \hat{y}^{(i)})^2\]

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: The factor \(\frac{1}{2}\) is included for mathematical convenience (simplifies derivatives).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Always non-negative&lt;/li&gt;
  &lt;li&gt;Heavily penalizes large errors (quadratic penalty)&lt;/li&gt;
  &lt;li&gt;Sensitive to outliers&lt;/li&gt;
  &lt;li&gt;Smooth and differentiable everywhere&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Derivative:&lt;/strong&gt;&lt;/p&gt;

\[\frac{\partial \mathcal{L}_{\text{MSE}}}{\partial \hat{y}} = \hat{y} - y\]

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Regression tasks&lt;/strong&gt;: Predicting continuous values&lt;/li&gt;
  &lt;li&gt;When errors are normally distributed&lt;/li&gt;
  &lt;li&gt;When all errors should be weighted equally&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Simple and intuitive&lt;/li&gt;
  &lt;li&gt;Smooth gradients&lt;/li&gt;
  &lt;li&gt;Well-understood theoretically&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Very sensitive to outliers (large errors are heavily penalized)&lt;/li&gt;
  &lt;li&gt;Assumes errors are normally distributed&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-mean-absolute-error-mae&quot;&gt;2. Mean Absolute Error (MAE)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{MAE}}(\hat{y}, y) = |y - \hat{y}|\]

&lt;p&gt;&lt;strong&gt;Cost function:&lt;/strong&gt;&lt;/p&gt;

\[J_{\text{MAE}} = \frac{1}{m} \sum_{i=1}^{m} |y^{(i)} - \hat{y}^{(i)}|\]

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Linear penalty for errors&lt;/li&gt;
  &lt;li&gt;More robust to outliers than MSE&lt;/li&gt;
  &lt;li&gt;Not differentiable at \(\hat{y} = y\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Derivative:&lt;/strong&gt;&lt;/p&gt;

\[\frac{\partial \mathcal{L}_{\text{MAE}}}{\partial \hat{y}} = \begin{cases} 1 &amp;amp; \text{if } \hat{y} &amp;gt; y \\ -1 &amp;amp; \text{if } \hat{y} &amp;lt; y \\ \text{undefined} &amp;amp; \text{if } \hat{y} = y \end{cases}\]

&lt;p&gt;(In practice, we use subgradients or smooth approximations)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Regression with outliers&lt;/li&gt;
  &lt;li&gt;When you want equal penalty for all error magnitudes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Robust to outliers&lt;/li&gt;
  &lt;li&gt;Intuitive interpretation (average absolute error)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Non-differentiable at zero&lt;/li&gt;
  &lt;li&gt;Can be slower to converge&lt;/li&gt;
  &lt;li&gt;Constant gradient may cause issues near minimum&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-huber-loss&quot;&gt;3. Huber Loss&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Formula:&lt;/strong&gt;&lt;/p&gt;

\[\mathcal{L}_{\text{Huber}}(\hat{y}, y) = \begin{cases} \frac{1}{2}(y - \hat{y})^2 &amp;amp; \text{if } |y - \hat{y}| \leq \delta \\ \delta |y - \hat{y}| - \frac{1}{2}\delta^2 &amp;amp; \text{otherwise} \end{cases}\]

&lt;p&gt;where \(\delta\) is a threshold parameter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Combines advantages of MSE and MAE&lt;/li&gt;
  &lt;li&gt;Quadratic for small errors, linear for large errors&lt;/li&gt;
  &lt;li&gt;Smooth and differentiable everywhere&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Regression with potential outliers&lt;/li&gt;
  &lt;li&gt;When you want smooth gradients but outlier robustness&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Less sensitive to outliers than MSE&lt;/li&gt;
  &lt;li&gt;Smooth gradients (unlike MAE)&lt;/li&gt;
  &lt;li&gt;Configurable via \(\delta\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Requires tuning \(\delta\) hyperparameter&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, English. The squared difference between prediction and target is the regression cost this lesson defines.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 3&lt;/td&gt;
          &lt;td&gt;Loss Functions and Optimization](https://www.youtube.com/watch?v=h7iBpEHGVNc) — Stanford University School of Engineering, English. Places mean squared error among the other losses you will swap in later.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=sDv4f4s2SB8&quot;&gt;Gradient Descent, Step-by-Step&lt;/a&gt; — StatQuest with Josh Starmer, English. Shows a concrete loss surface being walked, which is what a regression loss looks like once parameters move.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>03 Introduction to Training Neural Networks</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter03/03_00_Introduction</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;An untrained neural network with a billion random weights is nothing more than an expensive random-number generator. What breathes intelligence into it is the closed training loop of Chapter 03: measure error with a loss function, assign credit via backpropagation, step downhill with gradient descent, and keep the dynamics stable from epoch 1 to convergence.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-the-four-part-engine-of-neural-training&quot;&gt;Key ideas: The Four-Part Engine of Neural Training&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Loss Functions (Defining the Objective)&lt;/strong&gt;: Translates task goals into a differentiable scalar surface whose global minimum corresponds to accurate, well-calibrated predictions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Descent &amp;amp; Learning Rates (Navigating the Landscape)&lt;/strong&gt;: Moves parameters iteratively opposite the gradient while balancing convergence speed against oscillation and divergence.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Backpropagation (Exact Reverse-Mode Credit Assignment)&lt;/strong&gt;: Computes the gradient of the scalar loss with respect to every weight in \(O(1)\) backward passes by reusing cached forward activations.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Practical Training Discipline (Initialization, Preprocessing, Monitoring)&lt;/strong&gt;: Prevents vanishing/exploding signals at step 0 and catches overfitting early via clean train/val monitoring.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-one-complete-training-iteration-on-a-single-neuron&quot;&gt;Worked example: One Complete Training Iteration on a Single Neuron&lt;/h3&gt;

&lt;p&gt;Train a linear-sigmoid neuron \(\hat{y} = \sigma(wx + b)\) with binary cross-entropy loss \(L = -\big[y\ln\hat{y} + (1-y)\ln(1-\hat{y})\big]\) on \((x, y) = (2.0, 1)\), starting at \(w = 0.0, b = 0.0\) with learning rate \(\eta = 0.5\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Forward Pass&lt;/strong&gt;:
\(z = 0.0(2.0) + 0.0 = 0.0 \implies \hat{y} = \sigma(0.0) = 0.5\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Loss Evaluation&lt;/strong&gt;:
\(L_0 = -\ln(0.5) \approx 0.6931\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Backward Pass (Chain Rule)&lt;/strong&gt;:
For sigmoid + BCE, the gradient with respect to the logit simplifies cleanly to \(\frac{\partial L}{\partial z} = \hat{y} - y\):
\(\frac{\partial L}{\partial z} = 0.5 - 1 = -0.5\)
\(\frac{\partial L}{\partial w} = \frac{\partial L}{\partial z} \cdot x = (-0.5)(2.0) = -1.0, \qquad \frac{\partial L}{\partial b} = -0.5\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter Update &amp;amp; Verification&lt;/strong&gt;:
\(w_1 = 0.0 - 0.5(-1.0) = 0.5, \qquad b_1 = 0.0 - 0.5(-0.5) = 0.25\)
Re-evaluate forward pass: \(z_1 = 0.5(2.0) + 0.25 = 1.25 \implies \hat{y}_1 = \sigma(1.25) \approx 0.7773 \implies L_1 = -\ln(0.7773) \approx 0.2519 &amp;lt; 0.6931\).
One clean pass cut the loss by over 63%.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Training neural networks is the process of finding the optimal weights and biases that minimize the difference between predictions and actual outputs. This chapter covers the fundamental algorithms and techniques used to train deep neural networks, including backpropagation, gradient descent, loss functions, and practical training strategies.&lt;/p&gt;

&lt;p&gt;Understanding how neural networks learn from data is crucial for building effective deep learning systems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After backpropagation and the training loop, see &lt;strong&gt;03-99 Modern Applications and Updates&lt;/strong&gt; for compiled autodiff (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;, JAX) and fused backward kernels.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (interview practice):&lt;/strong&gt; After losses and backprop, see &lt;strong&gt;03-98 Interviews Practice&lt;/strong&gt; for original autodiff / Hessian / logistic prompts; open the &lt;em&gt;Deep Learning Interviews&lt;/em&gt; PDF (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for the solved bank.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LLM hub:&lt;/strong&gt; The CE + softmax identity \(\partial\mathcal{L}/\partial z = p-t\) and log-sum-exp are restated for next-token training in &lt;strong&gt;26-01&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Gradient descent, how neural networks learn&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 2](https://www.youtube.com/watch?v=IHZwWFHWa-w) — 3Blue1Brown, English. Training is minimizing a cost by walking downhill, the subject of this chapter.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 3&lt;/td&gt;
          &lt;td&gt;Loss Functions and Optimization](https://www.youtube.com/watch?v=h7iBpEHGVNc) — Stanford University School of Engineering, English. Stanford’s lecture on the loss you minimize and the optimizer that minimizes it.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, English. The chapter ends at backpropagation; this is that algorithm built in code.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_99_Modern_Applications</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Look inside Llama 3, Qwen, or DeepSeek and you might think the humble MLP was replaced by Attention. In fact, roughly two-thirds of the parameters and FLOPs in every modern Transformer live inside its upgraded MLP blocks—powered by Pre-Norm RMSNorm, residual highways, and SwiGLU gating.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-evolution-of-the-modern-mlp-block-20222026&quot;&gt;Key ideas: Evolution of the Modern MLP Block (2022–2026)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Pre-Norm + RMSNorm&lt;/strong&gt;: Places normalization &lt;em&gt;before&lt;/em&gt; each sub-layer and drops mean-centering (\(\text{RMSNorm}(\mathbf{x}) = \frac{\mathbf{x}}{\text{RMS}(\mathbf{x})} \odot \boldsymbol{\gamma}\)), stabilizing deep Transformer gradients while cutting normalization overhead.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;SwiGLU Feedforward Blocks&lt;/strong&gt;: Replaces the 2-matrix &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear -&amp;gt; ReLU -&amp;gt; Linear&lt;/code&gt; block with a 3-matrix gated block using hidden width \(\approx \frac{8}{3}d\) so total parameter count stays matched at \(8d^2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;All-MLP Vision (MLP-Mixer)&lt;/strong&gt;: Demonstrates that alternating token-mixing MLPs and channel-mixing MLPs can rival CNNs without a single convolution or attention layer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Kolmogorov–Arnold Networks (KANs)&lt;/strong&gt;: Explores placing learnable univariate spline functions on &lt;em&gt;edges&lt;/em&gt; rather than fixed activations on &lt;em&gt;nodes&lt;/em&gt;, sparking active research in scientific function approximation.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-computing-rmsnorm-vs-layernorm-on-a-token-vector&quot;&gt;Worked example: Computing RMSNorm vs. LayerNorm on a Token Vector&lt;/h3&gt;

&lt;p&gt;Take a 4-dimensional token embedding \(\mathbf{x} = [2, 2, 2, 2]\) with unit scale weights \(\boldsymbol{\gamma} = [1, 1, 1, 1]\) and \(\varepsilon = 0\) (for clean hand arithmetic; in practice \(\varepsilon = 10^{-6}\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute RMSNorm&lt;/strong&gt;:
\(\text{RMS}(\mathbf{x}) = \sqrt{\frac{1}{4}\left(2^2 + 2^2 + 2^2 + 2^2\right)} = \sqrt{\frac{16}{4}} = \sqrt{4} = 2.0\)
\(\text{RMSNorm}(\mathbf{x}) = \frac{[2, 2, 2, 2]}{2.0} = [1, 1, 1, 1]\)
RMSNorm preserves the direction of \(\mathbf{x}\) while rescaling its root-mean-square magnitude to exactly \(1.0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare with LayerNorm on the Same Vector&lt;/strong&gt;:
Mean \(\mu = 2.0\), variance \(\sigma^2 = \frac{1}{4}\sum(2 - 2)^2 = 0\), so LayerNorm subtracts the mean and produces \([0, 0, 0, 0]\) (with \(\varepsilon &amp;gt; 0\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Now Test on \(\mathbf{v} = [1, -1, 3, -3]\)&lt;/strong&gt; (zero-mean):
    &lt;ul&gt;
      &lt;li&gt;\(\text{RMS}(\mathbf{v}) = \sqrt{\frac{1 + 1 + 9 + 9}{4}} = \sqrt{5} \approx 2.236\).&lt;/li&gt;
      &lt;li&gt;\(\text{RMSNorm}(\mathbf{v}) = \frac{1}{\sqrt{5}}[1, -1, 3, -3] \approx [0.447, -0.447, 1.342, -1.342]\).
Because RMSNorm skips computing and subtracting \(\mu\), it saves a full memory pass over the tensor while maintaining identical scale invariance on near-zero-mean hidden states.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-the-modern-multilayer-perceptron-block&quot;&gt;Optional: the modern multilayer perceptron block&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; rewrite perceptron, architecture, activation, or forward-propagation theory. It shows how those blocks are packaged in 2022–2026 foundation models.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A neuron is still \(z = \mathbf{w}^\top \mathbf{x} + b\) followed by a nonlinearity. What changed is the &lt;strong&gt;block&lt;/strong&gt;: residual paths, gated MLPs, and RMS normalization became the default “layer” that you stack.&lt;/p&gt;

&lt;h2 id=&quot;1-from-a-single-neuron-to-a-transformer-mlp&quot;&gt;1. From a single neuron to a Transformer MLP&lt;/h2&gt;

&lt;p&gt;Most LLMs use a gated feed-forward block (SwiGLU / GeGLU), not a plain &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear → ReLU → Linear&lt;/code&gt;. With input \(\mathbf{x} \in \mathbb{R}^{d}\),&lt;/p&gt;

\[\mathrm{SwiGLU}(\mathbf{x}) = \big(\mathrm{SiLU}(\mathbf{x}W_1) \odot (\mathbf{x}W_2)\big) W_3,\]

&lt;p&gt;where \(\mathrm{SiLU}(z) = z\,\sigma(z)\). This is the same forward-propagation algebra as Chapter 02, with an extra gate (the Hadamard product). &lt;a href=&quot;https://arxiv.org/abs/2002.05202&quot;&gt;Shazeer, 2020&lt;/a&gt; introduced GLU variants; they became standard in PaLM, LLaMA, and later open models.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;pre-norm--rmsnorm-instead-of-batchnorm&quot;&gt;Pre-norm + RMSNorm instead of BatchNorm&lt;/h3&gt;

&lt;p&gt;LLMs almost never use BatchNorm. They use &lt;strong&gt;RMSNorm&lt;/strong&gt;&lt;/p&gt;

\[\mathrm{RMSNorm}(\mathbf{x}) = \frac{\mathbf{x}}{\sqrt{\frac{1}{d}\sum_i x_i^2 + \varepsilon}} \odot \boldsymbol{\gamma}\]

&lt;p&gt;and place it &lt;em&gt;before&lt;/em&gt; the residual branch (pre-norm). That is an activation-scale story from the vanishing-gradient lesson, applied at 7B–400B scale.&lt;/p&gt;

&lt;h3 id=&quot;mlp-mixer-and-all-mlp-vision&quot;&gt;MLP-Mixer and all-MLP vision&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2105.01601&quot;&gt;Tolstikhin et al., 2021&lt;/a&gt; (Mixer) and later all-MLP papers showed that token-mixing + channel-mixing MLPs can classify ImageNet without convolutions. The 2022–2024 follow-up is practical: Mixers appear as cheap baselines next to ConvNeXt and ViT, not as a replacement for CNNs.&lt;/p&gt;

&lt;h3 id=&quot;kolmogorovarnold-networks-kans&quot;&gt;Kolmogorov–Arnold Networks (KANs)&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2404.19756&quot;&gt;Liu et al., 2024&lt;/a&gt; replace the fixed activation on the node with a learnable univariate function on the &lt;strong&gt;edge&lt;/strong&gt;. Treat this as an experiment on the “what is a neuron?” question — not as a new default for production vision or NLP.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.nn.SiLU&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RMSNorm&lt;/code&gt;, and SwiGLU implementations inside &lt;a href=&quot;https://github.com/meta-llama/llama&quot;&gt;LLaMA&lt;/a&gt; / &lt;a href=&quot;https://github.com/huggingface/transformers&quot;&gt;Hugging Face transformers&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/huggingface/pytorch-image-models&quot;&gt;timm&lt;/a&gt; — modern MLP and ConvNeXt blocks for vision.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2002.05202&quot;&gt;GLU Variants Improve Transformer (Shazeer, 2020)&lt;/a&gt; — gated MLPs used by later LMs (still the block you will read in 2024–2026 code).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/1910.07467&quot;&gt;Root Mean Square Layer Normalization (Zhang &amp;amp; Sennrich, 2019)&lt;/a&gt; — RMSNorm, now the LLaMA-family default.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2404.19756&quot;&gt;KAN: Kolmogorov–Arnold Networks (Liu et al., 2024)&lt;/a&gt; — learnable edge activations; complementary research, not a replacement for MLPs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Use the perceptron and activation lessons to understand \(z\) and \(\sigma\). This note only documents the &lt;strong&gt;packaging&lt;/strong&gt; (SwiGLU, RMSNorm, residuals) you will see when you open a 2025 LLM or &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;timm&lt;/code&gt; model card. Chapter &lt;strong&gt;26-07&lt;/strong&gt; puts that packaging on a full decoder stack (RoPE, GQA, accounting).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Transformers, the tech behind LLMs&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 5](https://www.youtube.com/watch?v=wjZofJX0v4M) — 3Blue1Brown, English. The MLP block inside a transformer is the modern fully connected layer this note describes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2FaI2Fen1mQ&quot;&gt;The GELU, SiLU and SwiGLU activation functions, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. SwiGLU is the activation that block actually uses.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. The original stacked-neuron picture, so the note’s ‘from one neuron to an MLP’ comparison stays grounded.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-98 Interviews Practice (neurons and activations)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_98_Interviews_Practice</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Neural-architecture interview questions rarely test obscure papers; they probe whether you can spot subtle pitfalls on a whiteboard in 60 seconds—like why removing nonlinearities collapses depth, why softmax overflows without max-subtraction, or why a dead ReLU neuron can never revive itself.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-high-frequency-architecture-interview-concepts&quot;&gt;Key ideas: High-Frequency Architecture Interview Concepts&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nonlinearity &amp;amp; Rank Collapse&lt;/strong&gt;: Proving concisely why an \(L\)-layer linear MLP has rank bounded by \(\min_l d_l\) and collapses to one affine map.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Numerical Stability of Softmax &amp;amp; LogSumExp&lt;/strong&gt;: Using shift invariance \(\text{softmax}(\mathbf{z} - c) = \text{softmax}(\mathbf{z})\) to prevent overflow and underflow in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float16&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Saturation &amp;amp; Dead-Neuron Pathology&lt;/strong&gt;: Diagnosing why large positive/negative logits freeze sigmoid gradients (\(\sigma&apos;(z) \to 0\)) and why large negative biases permanently silence ReLU units.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter &amp;amp; FLOP Estimation&lt;/strong&gt;: Mentally computing parameter counts and memory footprints of dense layers to spot capacity bottlenecks during system design.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-diagnosing-a-dead-relu-neuron-after-one-aggressive-update&quot;&gt;Worked example: Diagnosing a Dead ReLU Neuron After One Aggressive Update&lt;/h3&gt;

&lt;p&gt;Suppose a ReLU neuron \(a = \text{ReLU}(w x + b)\) receives positive inputs \(x \in [0, 1]\), starts with \(w = 0.5, b = 0.2\), and on a single outlier sample \((x = 1.0, \frac{\partial L}{\partial a} = +20.0)\) takes a gradient step with overly large learning rate \(\eta = 0.5\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Forward Activation &amp;amp; Gradients Before the Update&lt;/strong&gt;:
\(z = 0.5(1.0) + 0.2 = 0.7 &amp;gt; 0 \implies a = 0.7, \quad \frac{\partial a}{\partial z} = 1\)
\(\frac{\partial L}{\partial w} = 20.0 \times 1.0 = 20.0, \qquad \frac{\partial L}{\partial b} = 20.0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply the Aggressive Gradient Step (\(\eta = 0.5\))&lt;/strong&gt;:
\(w_{\text{new}} = 0.5 - 0.5(20.0) = -9.5, \qquad b_{\text{new}} = 0.2 - 0.5(20.0) = -9.8\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check Subsequent Pre-Activations for ANY Input \(x \in [0, 1]\)&lt;/strong&gt;:
\(z_{\text{new}} = -9.5 x - 9.8 \leq -9.8 &amp;lt; 0 \quad \forall x \in [0, 1]\)
Because \(z_{\text{new}} &amp;lt; 0\) on the entire dataset, \(\frac{\partial a}{\partial z} = 0\) forever, so \(\frac{\partial L}{\partial w} = \frac{\partial L}{\partial b} = 0\) on every future step. The neuron is permanently &lt;strong&gt;dead&lt;/strong&gt;—directly explaining why gradient clipping, moderate learning rates, and LeakyReLU/GELU exist.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-interview-practice--neurons-and-activations&quot;&gt;Optional: interview practice — neurons and activations&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; rewrite perceptron, architecture, or activation theory. After those notes, use this drill, then open &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for solved items on perceptrons, activations, and the “expanded deep learning” architecture basics.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Book themes for this chapter (study in the PDF, not here):&lt;/strong&gt; perceptrons, activation functions, and elementary MLP structure from the long deep-learning topic area.&lt;/p&gt;

&lt;p&gt;Hub: &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;practice-prompts-original&quot;&gt;Practice prompts (original)&lt;/h2&gt;

&lt;h3 id=&quot;q1-depth-without-nonlinearity&quot;&gt;Q1. Depth without nonlinearity&lt;/h3&gt;

&lt;p&gt;You stack three layers \(\mathbf{h} = W_3W_2W_1\mathbf{x}\) with no activations. Prove that there exist weights \(W\) such that \(\mathbf{h}=W\mathbf{x}\). What does that say about “adding layers” as a way to get a richer hypothesis class?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Matrix multiplication is associative.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; \(W := W_3W_2W_1\) is one linear map. Extra linear layers do not enlarge the set of representable functions; they only factor the same matrix (and can make optimization worse). Nonlinearity is what creates a genuinely deeper model. Interviewers use this to check that “more layers” is not automatically “more expressive.”&lt;/p&gt;

&lt;h3 id=&quot;q2-softmax-shift-invariance&quot;&gt;Q2. Softmax shift invariance&lt;/h3&gt;

&lt;p&gt;Show that \(\mathrm{softmax}(\mathbf{z}+c\mathbf{1}) = \mathrm{softmax}(\mathbf{z})\) for any scalar \(c\). Why do frameworks often subtract \(\max_i z_i\) before the exponentials?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Factor \(e^{c}\) out of every term.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Each numerator and the denominator pick up the same \(e^{c}\), so the ratio is unchanged. Subtracting the max is the same identity with \(c=-\max z_i\); it keeps \(e^{z_i+c}\le 1\) and avoids overflow. The invariance also means an extra bias shared by all logits is unidentified — only &lt;em&gt;differences&lt;/em&gt; of logits matter.&lt;/p&gt;

&lt;h3 id=&quot;q3-where-sigmoid-saturates&quot;&gt;Q3. Where sigmoid saturates&lt;/h3&gt;

&lt;p&gt;For \(z=10\) and \(z=-10\), estimate \(\sigma&apos;(z)\) with \(\sigma(z)=(1+e^{-z})^{-1}\). Why is that a problem in a deep stack of sigmoids?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; \(\sigma&apos;(z)=\sigma(z)(1-\sigma(z))\) peaks at \(1/4\) when \(z=0\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; \(\sigma(10)\approx 1\) so \(\sigma&apos;(10)\approx 0\); likewise at \(-10\). Backprop multiplies these factors. A chain of saturated sigmoids drives hidden gradients to zero (the classical vanishing-gradient story). ReLU avoids saturation on the positive side, at the cost of a hard zero on the negative side (next question).&lt;/p&gt;

&lt;h3 id=&quot;q4-dead-relu&quot;&gt;Q4. Dead ReLU&lt;/h3&gt;

&lt;p&gt;A hidden unit computes \(\mathrm{ReLU}(\mathbf{w}^\top\mathbf{x}+b)\). Give a simple condition on \((\mathbf{w},b)\) and the data cloud under which the unit stays at \(0\) for every training point, and stays that way after every SGD update.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; If the pre-activation is negative on the whole batch, the gradient w.r.t. \((\mathbf{w},b)\) is zero.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; If \(\mathbf{w}^\top\mathbf{x}+b&amp;lt;0\) for all training \(\mathbf{x}\), the ReLU and its local gradient are identically zero, so SGD never moves that unit. A large negative bias or a bad initialization plus a high learning rate can push many units into this state. Leaky ReLU / GELU are common mitigations; so is a smaller step size after a loss spike.&lt;/p&gt;

&lt;h3 id=&quot;q5-parameter-count-of-a-wide-mlp&quot;&gt;Q5. Parameter count of a wide MLP&lt;/h3&gt;

&lt;p&gt;An MLP maps \(784\to 256\to 256\to 10\) with biases. How many scalars are trained? What changes if you insert a \(256\)-unit residual block that is still affine-plus-ReLU?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; A layer \(\mathbb{R}^{m}\to\mathbb{R}^{n}\) has \(nm+n\) parameters.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; First layer \(784\cdot 256+256\), two hidden \(256\cdot 256+256\) each, last \(256\cdot 10+10\). That is \(784\cdot256 + 2\cdot256^{2} + 256\cdot10 + (256+256+10)\). A residual block with the same width adds another \(256^{2}+256\) (plus the skip, which has no extra weights if dimensions match). Interviews often want the count &lt;em&gt;and&lt;/em&gt; the comment that residual connections do not by themselves add parameters on the skip.&lt;/p&gt;

&lt;h2 id=&quot;attribution&quot;&gt;Attribution&lt;/h2&gt;

&lt;p&gt;Kashani, S., and Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Download the PDF from arXiv for the full solved Q&amp;amp;A. This page is original course practice, not a reprint.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. Before the neuron and activation prompts.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=68BZ5f7P94E&quot;&gt;Neural Networks Pt. 3: ReLU In Action!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. ReLU’s kink is a common prompt; the video computes it.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NkOv_k7r6no&quot;&gt;Why Non-linear Activation Functions (C1W3L07)&lt;/a&gt; — DeepLearningAI, English. Why the activation cannot be linear is the other standard prompt.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-04 Forward Propagation</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_04_Forward_Propagation/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_04_Forward_Propagation</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;If you write a forward pass with Python &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;for&lt;/code&gt; loops over individual neurons and samples, training MNIST takes hours; rewrite the exact same math as batched matrix multiplications (GEMM) and it finishes in seconds. Forward propagation is where abstract graph equations become high-throughput tensor algebra.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-batched-forward-propagation--tensor-mechanics&quot;&gt;Key ideas: Batched Forward Propagation &amp;amp; Tensor Mechanics&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Layer-by-Layer State Transitions&lt;/strong&gt;: Maps input tensor \(A^{[0]} = X \in \mathbb{R}^{B \times d_0}\) through \(Z^{[l]} = A^{[l-1]} W^{[l]\top} + \mathbf{1}\mathbf{b}^{[l]\top}\) and \(A^{[l]} = g^{[l]}(Z^{[l]})\), caching \(Z^{[l]}\) and \(A^{[l-1]}\) for the backward pass.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Broadcasting Semantics&lt;/strong&gt;: Explains how a 1D bias vector of shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(d_out,)&lt;/code&gt; automatically stretches across the batch dimension &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(B, d_out)&lt;/code&gt; without duplicating memory on disk.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vectorization &amp;amp; Hardware Arithmetic Intensity&lt;/strong&gt;: Grouping \(B\) examples into a matrix converts memory-bound matrix-vector products into compute-bound matrix-matrix multiplications that saturate GPU Tensor Cores.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Activation Caching &amp;amp; Memory Trade-Off&lt;/strong&gt;: During training, every intermediate activation \(A^{[l]}\) must stay in VRAM until backprop consumes it—which is why batch size \(B\) scales activation memory linearly.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-full-batched-matrix-forward-pass-b--2&quot;&gt;Worked example: Full Batched Matrix Forward Pass (\(B = 2\))&lt;/h3&gt;

&lt;p&gt;Compute one batched forward pass for \(B = 2\) samples in \(\mathbb{R}^2\) through a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2 -&amp;gt; 2 -&amp;gt; 1&lt;/code&gt; ReLU network:
\(X = \begin{bmatrix} 1 &amp;amp; 2 \\ -1 &amp;amp; 1 \end{bmatrix}, \quad W^{[1]} = \begin{bmatrix} 1 &amp;amp; -1 \\ 2 &amp;amp; 1 \end{bmatrix}, \quad \mathbf{b}^{[1]} = \begin{bmatrix} 0.5 \\ -1.0 \end{bmatrix}, \quad W^{[2]} = \begin{bmatrix} 3 &amp;amp; -2 \end{bmatrix}, \quad b^{[2]} = 1.0\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Layer 1 Pre-Activation \(Z^{[1]} = X W^{[1]\top} + \mathbf{b}^{[1]\top}\)&lt;/strong&gt; (shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(2,2) @ (2,2) -&amp;gt; (2,2)&lt;/code&gt;):
\(W^{[1]\top} = \begin{bmatrix} 1 &amp;amp; 2 \\ -1 &amp;amp; 1 \end{bmatrix} \implies X W^{[1]\top} = \begin{bmatrix} 1(1)+2(-1) &amp;amp; 1(2)+2(1) \\ -1(1)+1(-1) &amp;amp; -1(2)+1(1) \end{bmatrix} = \begin{bmatrix} -1 &amp;amp; 4 \\ -2 &amp;amp; -1 \end{bmatrix}\)
Broadcast and add \(\mathbf{b}^{[1]\top} = [0.5, -1.0]\) to each row:
\(Z^{[1]} = \begin{bmatrix} -0.5 &amp;amp; 3.0 \\ -1.5 &amp;amp; -2.0 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Layer 1 ReLU Activation \(A^{[1]} = \max(0, Z^{[1]})\)&lt;/strong&gt;:
\(A^{[1]} = \begin{bmatrix} 0.0 &amp;amp; 3.0 \\ 0.0 &amp;amp; 0.0 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Layer 2 Output \(\hat{\mathbf{y}} = A^{[1]} W^{[2]\top} + b^{[2]}\)&lt;/strong&gt; (shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(2,2) @ (2,1) -&amp;gt; (2,1)&lt;/code&gt;):
\(\hat{\mathbf{y}} = \begin{bmatrix} 0.0(3) + 3.0(-2) \\ 0.0(3) + 0.0(-2) \end{bmatrix} + \begin{bmatrix} 1.0 \\ 1.0 \end{bmatrix} = \begin{bmatrix} -5.0 \\ 1.0 \end{bmatrix}\)
Both samples were evaluated simultaneously in two matrix multiplications, and Sample 2’s hidden vector was completely zeroed out—a live glimpse of a dead-ReLU activation state!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson provides a comprehensive understanding of forward propagation, the process by which neural networks make predictions.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;what-is-forward-propagation&quot;&gt;What is Forward Propagation?&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Forward propagation&lt;/strong&gt; is the process of computing the output of a neural network given an input. Data “flows forward” through the network from the input layer to the output layer, passing through all hidden layers in sequence.&lt;/p&gt;

&lt;p&gt;This is the &lt;strong&gt;inference&lt;/strong&gt; or &lt;strong&gt;prediction&lt;/strong&gt; phase of a neural network.&lt;/p&gt;

&lt;h3 id=&quot;geometric-intuition-for-one-forward-step&quot;&gt;Geometric intuition for one forward step&lt;/h3&gt;

&lt;p&gt;With a ReLU hidden layer and a \(\sigma\) output, a compact forward pass is:&lt;/p&gt;

\[\mathbf{h} = (W_h \mathbf{x} + b_h)^+,\qquad \hat{\mathbf{y}} = \sigma(W_y \mathbf{h} + b_y)\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/mlp_hidden_relu_forward.jpg&quot; alt=&quot;Forward: ReLU hidden then σ output&quot; /&gt;
&lt;em&gt;Figure: Pipeline \(x \to h \to \hat{y}\) with ReLU in the hidden layer and \(\sigma\) at the output. (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Each &lt;strong&gt;affine&lt;/strong&gt; layer (multiply by \(W\), add \(b\)) reshapes space; ReLU “folds / cuts” the negative half-space — that nonlinearity is why stacked layers are far more powerful than a single linear map.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/feature_space_folding_relu.jpg&quot; alt=&quot;ReLU folding feature space&quot; /&gt;
&lt;em&gt;Figure: After \(h=(W_h x+b_h)^+\), point clouds fold/distort nonlinearly in feature space. (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/feature_space_after_transform.jpg&quot; alt=&quot;Representation after layer transforms&quot; /&gt;
&lt;em&gt;Figure: The same data viewed after successive layers — forward is a sequence of geometric transforms, not only “matrix multiplies on paper”. (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Forward = “drawing” the function.&lt;/strong&gt; In 1D regression, each \(x\) through the net yields a point \((x,\hat{y})\); repeating over many \(x\) redraws the learned curve. Hidden neurons light up differently by input region.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_predictions_complex_curve.jpg&quot; alt=&quot;Many predictions on a complex curve&quot; /&gt;
&lt;em&gt;Figure: Repeated forward passes “draw” the approximated function. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;the-forward-pass-step-by-step&quot;&gt;The Forward Pass: Step by Step&lt;/h2&gt;

&lt;p&gt;Consider a simple 3-layer network:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Input layer&lt;/strong&gt;: \(n^{[0]} = 3\) features&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hidden layer 1&lt;/strong&gt;: \(n^{[1]} = 4\) neurons with ReLU&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hidden layer 2&lt;/strong&gt;: \(n^{[2]} = 4\) neurons with ReLU&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Output layer&lt;/strong&gt;: \(n^{[3]} = 1\) neuron with sigmoid (binary classification)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;layer-0-input&quot;&gt;Layer 0: Input&lt;/h3&gt;

\[\mathbf{a}^{[0]} = \mathbf{x} = \begin{bmatrix} x_1 \\ x_2 \\ x_3 \end{bmatrix}\]

&lt;h3 id=&quot;layer-1-first-hidden-layer&quot;&gt;Layer 1: First Hidden Layer&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Linear transformation:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{z}^{[1]} = \mathbf{W}^{[1]} \mathbf{a}^{[0]} + \mathbf{b}^{[1]}\]

&lt;p&gt;Where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{W}^{[1]} \in \mathbb{R}^{4 \times 3}\) (4 neurons, 3 inputs each)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{b}^{[1]} \in \mathbb{R}^{4}\) (4 biases)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{z}^{[1]} \in \mathbb{R}^{4}\) (pre-activation values)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Activation:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{a}^{[1]} = \text{ReLU}(\mathbf{z}^{[1]}) = \max(0, \mathbf{z}^{[1]})\]

&lt;p&gt;\(\mathbf{a}^{[1]} \in \mathbb{R}^{4}\) (activations/outputs of layer 1)&lt;/p&gt;

&lt;h3 id=&quot;layer-2-second-hidden-layer&quot;&gt;Layer 2: Second Hidden Layer&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Linear transformation:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{z}^{[2]} = \mathbf{W}^{[2]} \mathbf{a}^{[1]} + \mathbf{b}^{[2]}\]

&lt;p&gt;Where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[\mathbf{W}^{[2]} \in \mathbb{R}^{4 \times 4}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbf{b}^{[2]} \in \mathbb{R}^{4}\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Activation:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{a}^{[2]} = \text{ReLU}(\mathbf{z}^{[2]})\]

&lt;h3 id=&quot;layer-3-output-layer&quot;&gt;Layer 3: Output Layer&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Linear transformation:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{z}^{[3]} = \mathbf{W}^{[3]} \mathbf{a}^{[2]} + \mathbf{b}^{[3]}\]

&lt;p&gt;Where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[\mathbf{W}^{[3]} \in \mathbb{R}^{1 \times 4}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbf{b}^{[3]} \in \mathbb{R}^{1}\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Activation (output):&lt;/strong&gt;&lt;/p&gt;

\[\hat{y} = \mathbf{a}^{[3]} = \sigma(\mathbf{z}^{[3]}) = \frac{1}{1 + e^{-\mathbf{z}^{[3]}}}\]

&lt;p&gt;This gives us the predicted probability of the positive class.&lt;/p&gt;

&lt;h2 id=&quot;vectorized-forward-propagation&quot;&gt;Vectorized Forward Propagation&lt;/h2&gt;

&lt;p&gt;For computational efficiency, we process &lt;strong&gt;multiple examples simultaneously&lt;/strong&gt; using &lt;strong&gt;vectorization&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;batch-processing&quot;&gt;Batch Processing&lt;/h3&gt;

&lt;p&gt;Instead of processing one example at a time, we organize \(m\) examples into a matrix:&lt;/p&gt;

\[\mathbf{X} = \begin{bmatrix} | &amp;amp; | &amp;amp; &amp;amp; | \\ \mathbf{x}^{(1)} &amp;amp; \mathbf{x}^{(2)} &amp;amp; \cdots &amp;amp; \mathbf{x}^{(m)} \\ | &amp;amp; | &amp;amp; &amp;amp; | \end{bmatrix} \in \mathbb{R}^{n^{[0]} \times m}\]

&lt;p&gt;Each column is one training example.&lt;/p&gt;

&lt;h3 id=&quot;vectorized-computation&quot;&gt;Vectorized Computation&lt;/h3&gt;

&lt;p&gt;For layer \(l\):&lt;/p&gt;

\[\mathbf{Z}^{[l]} = \mathbf{W}^{[l]} \mathbf{A}^{[l-1]} + \mathbf{b}^{[l]}\]

\[\mathbf{A}^{[l]} = g^{[l]}(\mathbf{Z}^{[l]})\]

&lt;p&gt;Where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{A}^{[l]} \in \mathbb{R}^{n^{[l]} \times m}\) (each column is activations for one example)&lt;/li&gt;
  &lt;li&gt;
\[\mathbf{Z}^{[l]} \in \mathbb{R}^{n^{[l]} \times m}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\mathbf{W}^{[l]} \in \mathbb{R}^{n^{[l]} \times n^{[l-1]}}\]
  &lt;/li&gt;
  &lt;li&gt;\(\mathbf{b}^{[l]} \in \mathbb{R}^{n^{[l]} \times 1}\) (broadcasted across all \(m\) examples)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;broadcasting&quot;&gt;Broadcasting&lt;/h3&gt;

&lt;p&gt;Python/NumPy automatically broadcasts \(\mathbf{b}^{[l]}\) across all examples:&lt;/p&gt;

\[\mathbf{b}^{[l]} \in \mathbb{R}^{n^{[l]} \times 1} \rightarrow \mathbb{R}^{n^{[l]} \times m}\]

&lt;p&gt;Each column of the result gets the same bias vector added.&lt;/p&gt;

&lt;h2 id=&quot;concrete-example-with-numbers&quot;&gt;Concrete Example with Numbers&lt;/h2&gt;

&lt;p&gt;Let’s work through a small example with actual numbers.&lt;/p&gt;

&lt;h3 id=&quot;network-setup&quot;&gt;Network Setup&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Input: 2 features (\(n^{[0]} = 2\))&lt;/li&gt;
  &lt;li&gt;Hidden layer: 3 neurons with ReLU (\(n^{[1]} = 3\))&lt;/li&gt;
  &lt;li&gt;Output: 1 neuron with sigmoid (\(n^{[2]} = 1\))&lt;/li&gt;
  &lt;li&gt;Batch size: 2 examples (\(m = 2\))&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;parameters&quot;&gt;Parameters&lt;/h3&gt;

\[\mathbf{W}^{[1]} = \begin{bmatrix} 0.5 &amp;amp; -0.3 \\ 0.2 &amp;amp; 0.8 \\ -0.4 &amp;amp; 0.6 \end{bmatrix}, \quad \mathbf{b}^{[1]} = \begin{bmatrix} 0.1 \\ -0.2 \\ 0.3 \end{bmatrix}\]

\[\mathbf{W}^{[2]} = \begin{bmatrix} 1.0 &amp;amp; -0.5 &amp;amp; 0.7 \end{bmatrix}, \quad \mathbf{b}^{[2]} = \begin{bmatrix} 0.5 \end{bmatrix}\]

&lt;h3 id=&quot;input-data&quot;&gt;Input Data&lt;/h3&gt;

\[\mathbf{X} = \mathbf{A}^{[0]} = \begin{bmatrix} 1.0 &amp;amp; 0.5 \\ 2.0 &amp;amp; 1.5 \end{bmatrix}\]

&lt;p&gt;Example 1: \(\mathbf{x}^{(1)} = \begin{bmatrix} 1.0 \\ 2.0 \end{bmatrix}\), Example 2: \(\mathbf{x}^{(2)} = \begin{bmatrix} 0.5 \\ 1.5 \end{bmatrix}\)&lt;/p&gt;

&lt;h3 id=&quot;forward-pass-layer-1&quot;&gt;Forward Pass: Layer 1&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Compute \(\mathbf{Z}^{[1]}\):&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{Z}^{[1]} = \mathbf{W}^{[1]} \mathbf{A}^{[0]} + \mathbf{b}^{[1]}\]

\[= \begin{bmatrix} 0.5 &amp;amp; -0.3 \\ 0.2 &amp;amp; 0.8 \\ -0.4 &amp;amp; 0.6 \end{bmatrix} \begin{bmatrix} 1.0 &amp;amp; 0.5 \\ 2.0 &amp;amp; 1.5 \end{bmatrix} + \begin{bmatrix} 0.1 \\ -0.2 \\ 0.3 \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Matrix multiplication:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First column: \(\begin{bmatrix} 0.5(1.0) + (-0.3)(2.0) \\ 0.2(1.0) + 0.8(2.0) \\ -0.4(1.0) + 0.6(2.0) \end{bmatrix} = \begin{bmatrix} -0.1 \\ 1.8 \\ 0.8 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;Second column: \(\begin{bmatrix} 0.5(0.5) + (-0.3)(1.5) \\ 0.2(0.5) + 0.8(1.5) \\ -0.4(0.5) + 0.6(1.5) \end{bmatrix} = \begin{bmatrix} -0.2 \\ 1.3 \\ 0.7 \end{bmatrix}\)&lt;/p&gt;

&lt;p&gt;After adding bias:&lt;/p&gt;

\[\mathbf{Z}^{[1]} = \begin{bmatrix} -0.1+0.1 &amp;amp; -0.2+0.1 \\ 1.8-0.2 &amp;amp; 1.3-0.2 \\ 0.8+0.3 &amp;amp; 0.7+0.3 \end{bmatrix} = \begin{bmatrix} 0.0 &amp;amp; -0.1 \\ 1.6 &amp;amp; 1.1 \\ 1.1 &amp;amp; 1.0 \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Apply ReLU activation:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{A}^{[1]} = \text{ReLU}(\mathbf{Z}^{[1]}) = \begin{bmatrix} 0.0 &amp;amp; 0.0 \\ 1.6 &amp;amp; 1.1 \\ 1.1 &amp;amp; 1.0 \end{bmatrix}\]

&lt;h3 id=&quot;forward-pass-layer-2-output&quot;&gt;Forward Pass: Layer 2 (Output)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Compute \(\mathbf{Z}^{[2]}\):&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{Z}^{[2]} = \mathbf{W}^{[2]} \mathbf{A}^{[1]} + \mathbf{b}^{[2]}\]

\[= \begin{bmatrix} 1.0 &amp;amp; -0.5 &amp;amp; 0.7 \end{bmatrix} \begin{bmatrix} 0.0 &amp;amp; 0.0 \\ 1.6 &amp;amp; 1.1 \\ 1.1 &amp;amp; 1.0 \end{bmatrix} + \begin{bmatrix} 0.5 \end{bmatrix}\]

\[= \begin{bmatrix} 1.0(0.0) + (-0.5)(1.6) + 0.7(1.1) + 0.5 &amp;amp; 1.0(0.0) + (-0.5)(1.1) + 0.7(1.0) + 0.5 \end{bmatrix}\]

\[= \begin{bmatrix} 0.47 &amp;amp; 0.65 \end{bmatrix}\]

&lt;p&gt;&lt;strong&gt;Apply sigmoid activation:&lt;/strong&gt;&lt;/p&gt;

\[\mathbf{A}^{[2]} = \sigma(\mathbf{Z}^{[2]}) = \begin{bmatrix} \frac{1}{1+e^{-0.47}} &amp;amp; \frac{1}{1+e^{-0.65}} \end{bmatrix} \approx \begin{bmatrix} 0.615 &amp;amp; 0.657 \end{bmatrix}\]

&lt;h3 id=&quot;final-predictions&quot;&gt;Final Predictions&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Example 1: \(\hat{y}^{(1)} = 0.615\) (61.5% probability of positive class)&lt;/li&gt;
  &lt;li&gt;Example 2: \(\hat{y}^{(2)} = 0.657\) (65.7% probability of positive class)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;implementation-in-python&quot;&gt;Implementation in Python&lt;/h2&gt;

&lt;h3 id=&quot;basic-implementation&quot;&gt;Basic Implementation&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward_propagation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Arguments:
    X -- input data of shape (n_x, m)
    parameters -- python dictionary containing W1, b1, W2, b2, W3, b3, ...
    
    Returns:
    AL -- last post-activation value (predictions)
    caches -- list of caches containing (A_prev, W, b, Z) for each layer
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;//&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# number of layers
&lt;/span&gt;    
    &lt;span class=&quot;c1&quot;&gt;# Forward through hidden layers (ReLU activation)
&lt;/span&gt;    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Output layer (sigmoid activation)
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cache&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;AL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example usage
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
              &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.8&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt;
                    &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b1&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W2&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.7&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]]),&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b2&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward_propagation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Output: Predictions: [[0.615 0.657]]
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;object-oriented-implementation&quot;&gt;Object-Oriented Implementation&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Arguments:
        layer_dims -- list containing dimensions of each layer
                     Example: [2, 3, 1] means 2 inputs, 3 hidden, 1 output
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;initialize_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;initialize_parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;seed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{}&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_dims&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Forward propagation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Hidden layers with ReLU
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;l&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# ReLU
&lt;/span&gt;            
            &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Output layer with sigmoid
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;L&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        
        &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Sigmoid
&lt;/span&gt;        
        &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Make predictions (0 or 1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;A&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Usage
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;caches&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;common-issues-and-debugging&quot;&gt;Common Issues and Debugging&lt;/h2&gt;

&lt;h3 id=&quot;1-dimension-mismatch&quot;&gt;1. Dimension Mismatch&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Matrix multiplication fails due to incompatible dimensions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Check that \(\mathbf{W}^{[l]}\) has shape \((n^{[l]}, n^{[l-1]})\)&lt;/li&gt;
  &lt;li&gt;Check that \(\mathbf{A}^{[l-1]}\) has shape \((n^{[l-1]}, m)\)&lt;/li&gt;
  &lt;li&gt;Use print statements or debugger to verify shapes&lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Layer &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;l&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  W shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;W&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  A_prev shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;A_prev&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  b shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Z shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;2-numerical-instability&quot;&gt;2. Numerical Instability&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Overflow or underflow in exponentials (especially sigmoid/softmax).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Use numerical stability tricks:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Unstable
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid_unstable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Stable version
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid_stable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; 
                    &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)),&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;3-incorrect-broadcasting&quot;&gt;3. Incorrect Broadcasting&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Problem&lt;/strong&gt;: Bias not broadcast correctly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Solution&lt;/strong&gt;: Ensure bias has shape \((n^{[l]}, 1)\) not \((n^{[l]},)\)&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Correct
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Shape (n_l, 1)
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Incorrect (may cause issues)
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_l&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Shape (n_l,)
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;forward-propagation-complexity&quot;&gt;Forward Propagation Complexity&lt;/h2&gt;

&lt;h3 id=&quot;time-complexity&quot;&gt;Time Complexity&lt;/h3&gt;

&lt;p&gt;For a network with \(L\) layers and \(n\) neurons per layer:&lt;/p&gt;

\[O(L \cdot n^2 \cdot m)\]

&lt;p&gt;where \(m\) is the batch size.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Breakdown:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Each layer: \(O(n^2 \cdot m)\) for matrix multiplication \(\mathbf{W}^{[l]} \mathbf{A}^{[l-1]}\)&lt;/li&gt;
  &lt;li&gt;\(L\) layers total&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;space-complexity&quot;&gt;Space Complexity&lt;/h3&gt;

\[O(L \cdot n \cdot m)\]

&lt;p&gt;Need to store activations for each layer (needed for backpropagation).&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Forward propagation&lt;/strong&gt; computes predictions by passing inputs through the network&lt;/li&gt;
  &lt;li&gt;Each layer performs: &lt;strong&gt;linear transformation&lt;/strong&gt; → &lt;strong&gt;activation function&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vectorization&lt;/strong&gt; allows efficient batch processing of multiple examples&lt;/li&gt;
  &lt;li&gt;The process is: \(\mathbf{Z}^{[l]} = \mathbf{W}^{[l]} \mathbf{A}^{[l-1]} + \mathbf{b}^{[l]}, \quad \mathbf{A}^{[l]} = g^{[l]}(\mathbf{Z}^{[l]})\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Caching&lt;/strong&gt; intermediate values is essential for efficient backpropagation&lt;/li&gt;
  &lt;li&gt;Proper handling of &lt;strong&gt;dimensions&lt;/strong&gt; and &lt;strong&gt;numerical stability&lt;/strong&gt; is crucial&lt;/li&gt;
  &lt;li&gt;Forward propagation is &lt;strong&gt;computationally efficient&lt;/strong&gt; (\(O(L \cdot n^2 \cdot m)\))&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now that we understand how networks make predictions, we need to learn how to train them. In the next chapter, we’ll cover &lt;strong&gt;backpropagation&lt;/strong&gt; and &lt;strong&gt;gradient descent&lt;/strong&gt;, the algorithms that enable neural networks to learn from data.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/793200140509765&quot;&gt;Neural network intuition (Perceptron → Deep Learning)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/720970114372332&quot;&gt;Neural nets as function approximators&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=a8i2eJin0lY&quot;&gt;Forward Propagation in a Deep Network (C1W4L02)&lt;/a&gt; — DeepLearningAI, English. The forward equations, one layer at a time, are this lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qzPQ8cEsVK8&quot;&gt;Forward and Backward Propagation (C1W4L06)&lt;/a&gt; — DeepLearningAI, English. Puts the forward pass next to the backward pass so the shapes you just computed have a destination.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VVDHU_TWwUg&quot;&gt;PyTorch Tutorial 06 - Training Pipeline: Model, Loss, and Optimizer&lt;/a&gt; — Patrick Loeber, English. The same forward pass inside a PyTorch training step, which is the implementation section.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-03 Activation Functions in Detail</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_03_Activation_Functions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_03_Activation_Functions</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Remove every activation function from a 100-layer neural network and the entire billion-parameter monument collapses mathematically into a single linear regression layer. Activation functions are the sole source of nonlinearity—and simultaneously the primary gatekeepers of gradient flow.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-why-activation-functions-govern-both-expressivity-and-trainability&quot;&gt;Key ideas: Why Activation Functions Govern Both Expressivity and Trainability&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Linear Collapse Theorem&lt;/strong&gt;: Without nonlinear activations, \(W_L(\dots(W_2(W_1 \mathbf{x}))\dots) = (W_L \cdots W_1)\mathbf{x} = W_{\text{eff}}\mathbf{x}\), destroying all benefits of depth.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Derivative Magnitude &amp;amp; Gradient Flow&lt;/strong&gt;: Because backprop multiplies by \(g&apos;(z^{[l]})\) at every layer, activations with \(g&apos;(z) \ll 1\) (like saturated sigmoid) shrink gradients exponentially to zero across depth.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Zero-Centered Outputs &amp;amp; Optimization Geometry&lt;/strong&gt;: Strictly positive outputs (like sigmoid) force all weight gradients entering a neuron to share the same sign, causing inefficient zig-zagging updates.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Modern Smooth Gating (GELU, SiLU/Swish, SwiGLU)&lt;/strong&gt;: Trades ReLU’s sharp corner at zero for smooth, non-monotonic curves that preserve small negative gradients and improve Transformer convergence.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-proving-linear-collapse-numerically-on-a-2-layer-network&quot;&gt;Worked example: Proving Linear Collapse Numerically on a 2-Layer Network&lt;/h3&gt;

&lt;p&gt;Consider two linear layers with &lt;strong&gt;no activation function&lt;/strong&gt;:
\(W_1 = \begin{bmatrix} 2 &amp;amp; -1 \\ 0 &amp;amp; 3 \end{bmatrix}, \quad W_2 = \begin{bmatrix} 1 &amp;amp; 2 \\ -1 &amp;amp; 1 \end{bmatrix}, \quad \mathbf{x} = \begin{bmatrix} 4 \\ 1 \end{bmatrix}\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Pass \(\mathbf{x}\) Through Both Layers Sequentially&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Layer 1: \(\mathbf{h} = W_1\mathbf{x} = \begin{bmatrix} 2(4) - 1(1) \\ 0(4) + 3(1) \end{bmatrix} = \begin{bmatrix} 7 \\ 3 \end{bmatrix}\).&lt;/li&gt;
      &lt;li&gt;Layer 2: \(\mathbf{y} = W_2\mathbf{h} = \begin{bmatrix} 1(7) + 2(3) \\ -1(7) + 1(3) \end{bmatrix} = \begin{bmatrix} 13 \\ -4 \end{bmatrix}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Collapse Into One Single Matrix \(W_{\text{eff}} = W_2 W_1\)&lt;/strong&gt;:
\(W_{\text{eff}} = \begin{bmatrix} 1 &amp;amp; 2 \\ -1 &amp;amp; 1 \end{bmatrix}\begin{bmatrix} 2 &amp;amp; -1 \\ 0 &amp;amp; 3 \end{bmatrix} = \begin{bmatrix} 2 &amp;amp; 5 \\ -2 &amp;amp; 4 \end{bmatrix}\)
Check: \(W_{\text{eff}}\mathbf{x} = \begin{bmatrix} 2(4) + 5(1) \\ -2(4) + 4(1) \end{bmatrix} = \begin{bmatrix} 13 \\ -4 \end{bmatrix}\). Identical for &lt;em&gt;every&lt;/em&gt; input \(\mathbf{x} \in \mathbb{R}^2\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Insert Just One ReLU Between Layers (Test on \(\mathbf{x}&apos; = [-1, -1]^\top\))&lt;/strong&gt;:
With ReLU, \(\mathbf{h}&apos; = \text{ReLU}([-1, -3]^\top) = [0, 0]^\top \implies \mathbf{y}&apos; = [0, 0]^\top\), whereas \(W_{\text{eff}}\mathbf{x}&apos; = [-7, -2]^\top \neq [0, 0]^\top\). That single elementwise bend breaks linear collapse forever.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Activation functions in depth:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Classic Activation Functions&lt;/strong&gt; — why activations matter, common functions, comparison&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Modern Activations and Vanishing Gradients&lt;/strong&gt; — choosing activations, implementation, vanishing gradients&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NkOv_k7r6no&quot;&gt;Why Non-linear Activation Functions (C1W3L07)&lt;/a&gt; — DeepLearningAI, English. Without a nonlinearity the whole stack collapses to one matrix.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=68BZ5f7P94E&quot;&gt;Neural Networks Pt. 3: ReLU In Action!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. ReLU, the default classic activation the first lesson in this block computes.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2FaI2Fen1mQ&quot;&gt;The GELU, SiLU and SwiGLU activation functions, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. The modern activations the second lesson compares with ReLU.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-03-02 Modern Activations and Vanishing Gradients</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_03_02_Modern_Activations_and_Vanishing_Gradients/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_03_02_Modern_Activations_and_Vanishing_Gradients</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Open the source code of GPT, Llama, or Gemma and you will not find a single ReLU in the Transformer blocks—instead you will see GELU, SiLU (Swish), and SwiGLU. Modern activations combine ReLU’s non-saturating positive ray with smooth curvature near zero to stabilize deep optimization.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-modern-activations--gradient-preservation&quot;&gt;Key ideas: Modern Activations &amp;amp; Gradient Preservation&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;GELU &amp;amp; SiLU/Swish (Smooth Stochastic Gating)&lt;/strong&gt;: Weight each input smoothly by a probability gate—\(\text{SiLU}(z) = z\sigma(z)\) and \(\text{GELU}(z) = z\Phi(z)\)—giving smooth derivatives everywhere and slight non-monotonicity for negative \(z\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gated Linear Units (SwiGLU)&lt;/strong&gt;: Splits the hidden projection into two pathways, \(\text{SwiGLU}(\mathbf{x}) = \text{SiLU}(\mathbf{x}W_1) \odot (\mathbf{x}W_2)\), providing multiplicative feature interaction that consistently lowers LLM perplexity per FLOP.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Output-Layer Matching Principle&lt;/strong&gt;: Pairs the final activation strictly with the task’s probability model—linear for regression, sigmoid for binary/multi-label, and numerically stabilized log-softmax for multi-class classification.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vanishing Gradient Mitigation Stack&lt;/strong&gt;: Combines non-saturating activations with variance-preserving initialization (He/Xavier), normalization (LayerNorm/RMSNorm), and residual skip connections.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-computing-silu-swish-value-derivative-and-numerically-stable-softmax&quot;&gt;Worked example: Computing SiLU (Swish) Value, Derivative, and Numerically Stable Softmax&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;SiLU Forward &amp;amp; Backward at \(z = 0\) and \(z = -1\)&lt;/strong&gt; (\(\text{SiLU}(z) = z\sigma(z)\)):
By the product rule:
\(\text{SiLU}&apos;(z) = \sigma(z) + z\,\sigma(z)(1 - \sigma(z)) = \sigma(z)\big(1 + z(1 - \sigma(z))\big)\)
    &lt;ul&gt;
      &lt;li&gt;At \(z = 0\) (\(\sigma(0) = 0.5\)):
\(\text{SiLU}(0) = 0, \qquad \text{SiLU}&apos;(0) = 0.5(1 + 0) = 0.500\)&lt;/li&gt;
      &lt;li&gt;At \(z = -1\) (\(\sigma(-1) \approx 0.2689\)):
\(\text{SiLU}(-1) = -0.2689, \qquad \text{SiLU}&apos;(-1) = 0.2689\big(1 - 1(0.7311)\big) = 0.2689(0.2689) \approx +0.0723\)
Unlike ReLU (whose derivative is identically \(0\) at \(z = -1\)), SiLU remains smoothly differentiable with a gentle nonzero gradient.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why Shift-Invariant Softmax Prevents Overflow&lt;/strong&gt;:
Suppose logits are \(\mathbf{z} = [1000, 1001, 1000]\). Direct &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;exp(1000)&lt;/code&gt; overflows &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt; (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;inf / inf = NaN&lt;/code&gt;).
Subtract \(\max(\mathbf{z}) = 1001\) first: \(\tilde{\mathbf{z}} = [-1, 0, -1]\).
\(e^{-1} \approx 0.3679, \quad e^0 = 1.0000 \implies Z = 1.7358\)
\(\text{softmax}(\mathbf{z}) = \left[\frac{0.3679}{1.7358}, \frac{1.0000}{1.7358}, \frac{0.3679}{1.7358}\right] \approx [0.2119, 0.5761, 0.2119]\)
Exact mathematical equality, zero floating-point overflow!&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;choosing-the-right-activation-function&quot;&gt;Choosing the Right Activation Function&lt;/h2&gt;

&lt;h3 id=&quot;for-hidden-layers&quot;&gt;For Hidden Layers&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Default recommendation: ReLU&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Start with ReLU for most applications&lt;/li&gt;
  &lt;li&gt;Computationally efficient&lt;/li&gt;
  &lt;li&gt;Works well in practice&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;If dying ReLU is a problem:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Try Leaky ReLU or ELU&lt;/li&gt;
  &lt;li&gt;Check learning rate and initialization&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;For modern/large-scale models:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;GELU for transformers and NLP&lt;/li&gt;
  &lt;li&gt;Swish for image models when performance is critical&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;For very deep networks:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Consider ELU or SELU&lt;/li&gt;
  &lt;li&gt;May need normalization techniques (covered later)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;for-output-layers&quot;&gt;For Output Layers&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Binary classification:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid&lt;/strong&gt;: Outputs probability for positive class&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Multi-class classification:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Softmax&lt;/strong&gt;: Outputs probability distribution over classes&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Regression:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Linear (identity)&lt;/strong&gt;: For unbounded outputs&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ReLU&lt;/strong&gt;: For non-negative outputs (e.g., prices, counts)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid/tanh&lt;/strong&gt;: For bounded outputs&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Multi-label classification:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid&lt;/strong&gt;: Independent probability for each label&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practical-implementation&quot;&gt;Practical Implementation&lt;/h2&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;sigmoid_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;tanh_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;return &lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;astype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;leaky_relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;leaky_relu_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;elu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;elu_derivative&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;elu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;alpha&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Numerical stability: subtract max
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;swish&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;nd&quot;&gt;@staticmethod&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;gelu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Approximation
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pi&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.044715&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example usage
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;ReLU:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Leaky ReLU:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;leaky_relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Sigmoid:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Tanh:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;Activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;the-vanishing-gradient-problem&quot;&gt;The Vanishing Gradient Problem&lt;/h2&gt;

&lt;h3 id=&quot;why-it-matters&quot;&gt;Why It Matters&lt;/h3&gt;

&lt;p&gt;During backpropagation, gradients are multiplied through layers:&lt;/p&gt;

\[\frac{\partial \mathcal{L}}{\partial \mathbf{W}^{[1]}} = \frac{\partial \mathcal{L}}{\partial \mathbf{a}^{[L]}} \cdot \frac{\partial \mathbf{a}^{[L]}}{\partial \mathbf{z}^{[L]}} \cdot \ldots \cdot \frac{\partial \mathbf{z}^{[2]}}{\partial \mathbf{a}^{[1]}} \cdot \frac{\partial \mathbf{a}^{[1]}}{\partial \mathbf{z}^{[1]}} \cdot \frac{\partial \mathbf{z}^{[1]}}{\partial \mathbf{W}^{[1]}}\]

&lt;h3 id=&quot;problem-with-sigmoidtanh&quot;&gt;Problem with Sigmoid/Tanh&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Maximum derivative: \(\sigma&apos;(z) = 0.25\) (sigmoid), \(\tanh&apos;(z) = 1\) (tanh at \(z=0\))&lt;/li&gt;
  &lt;li&gt;Typical derivative: Much smaller (\(&amp;lt; 0.25\) for sigmoid)&lt;/li&gt;
  &lt;li&gt;After many layers: \(0.25^{10} \approx 9.5 \times 10^{-7}\) (extremely small!)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Result&lt;/strong&gt;: Gradients vanish, early layers learn very slowly or not at all.&lt;/p&gt;

&lt;h3 id=&quot;relu-to-the-rescue&quot;&gt;ReLU to the Rescue&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Derivative is 1 for positive inputs (no vanishing)&lt;/li&gt;
  &lt;li&gt;Gradient flows unchanged through active ReLU units&lt;/li&gt;
  &lt;li&gt;Enables training of much deeper networks&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;the-dying-relu-problem&quot;&gt;The Dying ReLU Problem&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;If \(z &amp;lt; 0\) always, gradient is 0, no learning&lt;/li&gt;
  &lt;li&gt;Can happen with:
    &lt;ul&gt;
      &lt;li&gt;Poor initialization&lt;/li&gt;
      &lt;li&gt;High learning rates&lt;/li&gt;
      &lt;li&gt;Unlucky updates&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Solutions:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Use Leaky ReLU, ELU, or other variants&lt;/li&gt;
  &lt;li&gt;Proper initialization (He initialization for ReLU)&lt;/li&gt;
  &lt;li&gt;Reasonable learning rates&lt;/li&gt;
  &lt;li&gt;Batch normalization (covered later)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Activation functions&lt;/strong&gt; introduce nonlinearity, enabling networks to learn complex patterns&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ReLU&lt;/strong&gt; is the default choice for hidden layers in modern deep learning&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid&lt;/strong&gt; is used for binary classification outputs&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Softmax&lt;/strong&gt; is used for multi-class classification outputs&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Advanced activations&lt;/strong&gt; (ELU, Swish, GELU) can provide performance improvements&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vanishing gradients&lt;/strong&gt; are a major issue with sigmoid/tanh in deep networks&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ReLU&lt;/strong&gt; alleviates vanishing gradients but introduces the dying ReLU problem&lt;/li&gt;
  &lt;li&gt;Choice of activation function significantly impacts training and performance&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the next lesson, we’ll explore forward propagation in detail with concrete examples.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=2FaI2Fen1mQ&quot;&gt;The GELU, SiLU and SwiGLU activation functions, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. GELU, SiLU, and SwiGLU are the modern functions this lesson adds after ReLU.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qhXZsFVxGKo&quot;&gt;Vanishing/Exploding Gradients (C2W1L10)&lt;/a&gt; — DeepLearningAI, English. Vanishing and exploding gradients are the failure mode the lesson uses to justify those choices.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=68BZ5f7P94E&quot;&gt;Neural Networks Pt. 3: ReLU In Action!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. ReLU is the baseline those newer functions are compared with.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-03-01 Classic Activation Functions</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_03_01_Classic_Activations/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_03_01_Classic_Activations</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;For twenty years, researchers defaulted to sigmoid and tanh because they looked like smooth biological firing rates—until deep networks refused to train past five layers. Switching to the deceptively trivial function \(\max(0, z)\) (ReLU) unlocked deep vision models overnight, and understanding its derivative explains why.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-comparing-classic-activation-families&quot;&gt;Key ideas: Comparing Classic Activation Families&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sigmoid (\(\sigma(z) = \frac{1}{1+e^{-z}}\))&lt;/strong&gt;: Squashes \(\mathbb{R} \to (0, 1)\), ideal for binary probability outputs and LSTM gates, but suffers from saturation (\(\max \sigma&apos;(z) = 0.25\)) and non-zero-centered outputs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hyperbolic Tangent (\(\tanh(z)\))&lt;/strong&gt;: Rescales sigmoid to \((-1, 1)\) with zero-centered outputs and steeper peak slope (\(\tanh&apos;(0) = 1\)), yet still saturates exponentially for \(\lvert z\rvert &amp;gt; 3\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;ReLU (\(\max(0, z)\))&lt;/strong&gt;: Maintains an exact unit derivative \(1\) for all \(z &amp;gt; 0\) (eliminating positive-side vanishing gradients) at trivial compute cost, but risks “dying ReLUs” if weights push \(z &amp;lt; 0\) permanently.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Leaky ReLU &amp;amp; ELU&lt;/strong&gt;: Restore a small nonzero slope (\(\alpha = 0.01\) or smooth exponential tail) for \(z &amp;lt; 0\) so negative pre-activations still receive recovery gradients.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-comparing-forward-values-and-gradients-at-z--0-and-z--4&quot;&gt;Worked example: Comparing Forward Values and Gradients at \(z = 0\) and \(z = 4\)&lt;/h3&gt;

&lt;p&gt;Evaluate Sigmoid, Tanh, ReLU, and Leaky ReLU (\(\alpha = 0.01\)) at both \(z = 0\) (active center) and \(z = 4\) (large pre-activation, noting \(e^{-4} \approx 0.0183\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;At \(z = 0\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Sigmoid&lt;/strong&gt;: \(\sigma(0) = 0.500\), derivative \(\sigma&apos;(0) = 0.5(1 - 0.5) = 0.250\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tanh&lt;/strong&gt;: \(\tanh(0) = 0.000\), derivative \(\tanh&apos;(0) = 1 - 0^2 = 1.000\).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;ReLU / Leaky ReLU&lt;/strong&gt;: value \(0.000\), right derivative \(1.000\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;At \(z = 4\) (Large Activation Regime)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Sigmoid&lt;/strong&gt;: \(\sigma(4) = \frac{1}{1 + 0.0183} \approx 0.9820\), derivative:
\(\sigma&apos;(4) = 0.9820 \times 0.0180 \approx 0.0177\) (over \(56\times\) smaller than 1!).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Tanh&lt;/strong&gt;: \(\tanh(4) \approx 0.9993\), derivative:
\(\tanh&apos;(4) = 1 - (0.9993)^2 \approx 0.0013\) (over \(750\times\) smaller than 1!).&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;ReLU &amp;amp; Leaky ReLU&lt;/strong&gt;: value \(4.000\), derivative \(1.000\) (zero attenuation!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chain-Rule Consequence Across 10 Layers&lt;/strong&gt;:
Even at the &lt;em&gt;best possible&lt;/em&gt; point \(z = 0\), multiplying \(\sigma&apos;(0) = 0.25\) across 10 layers shrinks the gradient by \((0.25)^{10} = 9.54 \times 10^{-7}\)—a million-fold vanish! ReLU preserves \(1^{10} = 1\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson provides an in-depth exploration of activation functions, their properties, and how to choose the right one for your neural network.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;why-activation-functions-matter&quot;&gt;Why Activation Functions Matter&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Without activation functions&lt;/strong&gt;, neural networks would be limited to learning only linear transformations. No matter how many layers you stack, a composition of linear functions is still linear:&lt;/p&gt;

\[f(g(h(\mathbf{x}))) = \mathbf{A}_1(\mathbf{A}_2(\mathbf{A}_3 \mathbf{x})) = (\mathbf{A}_1 \mathbf{A}_2 \mathbf{A}_3)\mathbf{x} = \mathbf{A}\mathbf{x}\]

&lt;p&gt;&lt;strong&gt;Activation functions introduce nonlinearity&lt;/strong&gt;, enabling networks to learn complex patterns and approximate arbitrary functions.&lt;/p&gt;

&lt;h2 id=&quot;desirable-properties-of-activation-functions&quot;&gt;Desirable Properties of Activation Functions&lt;/h2&gt;

&lt;p&gt;An ideal activation function should have:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Nonlinearity&lt;/strong&gt;: Enable learning of complex patterns&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Differentiability&lt;/strong&gt;: Enable gradient-based deep-learning&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Monotonicity&lt;/strong&gt;: Preserve ordering (helpful for deep-learning)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Computational efficiency&lt;/strong&gt;: Fast to compute forward and backward&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bounded or unbounded appropriately&lt;/strong&gt;: Depending on the task&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Zero-centered&lt;/strong&gt;: Help with gradient flow (for hidden layers)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Avoid saturation&lt;/strong&gt;: Prevent vanishing gradients&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;No single activation function satisfies all properties perfectly, so the choice depends on the specific use case.&lt;/p&gt;

&lt;h2 id=&quot;common-activation-functions&quot;&gt;Common Activation Functions&lt;/h2&gt;

&lt;h3 id=&quot;1-sigmoid-logistic-function&quot;&gt;1. Sigmoid (Logistic Function)&lt;/h3&gt;

\[\sigma(z) = \frac{1}{1 + e^{-z}}\]

&lt;p&gt;&lt;strong&gt;Derivative:&lt;/strong&gt;&lt;/p&gt;

\[\sigma&apos;(z) = \sigma(z)(1 - \sigma(z))\]

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Range: \((0, 1)\)&lt;/li&gt;
  &lt;li&gt;Smooth, differentiable everywhere&lt;/li&gt;
  &lt;li&gt;Monotonically increasing&lt;/li&gt;
  &lt;li&gt;Saturates at both ends&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Clear probabilistic interpretation&lt;/li&gt;
  &lt;li&gt;Smooth gradient&lt;/li&gt;
  &lt;li&gt;Historically popular&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Vanishing gradient problem&lt;/strong&gt;: Gradients near 0 for $$&lt;/td&gt;
          &lt;td&gt;z&lt;/td&gt;
          &lt;td&gt;&amp;gt; 4$$&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Not zero-centered&lt;/strong&gt;: Outputs always positive&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Computationally expensive&lt;/strong&gt;: Requires exponential calculation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Output layer for binary classification&lt;/li&gt;
  &lt;li&gt;Gate activations in LSTMs&lt;/li&gt;
  &lt;li&gt;Generally avoided in hidden layers of deep networks&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-hyperbolic-tangent-tanh&quot;&gt;2. Hyperbolic Tangent (tanh)&lt;/h3&gt;

\[\tanh(z) = \frac{e^z - e^{-z}}{e^z + e^{-z}} = \frac{e^{2z} - 1}{e^{2z} + 1} = 2\sigma(2z) - 1\]

&lt;p&gt;&lt;strong&gt;Derivative:&lt;/strong&gt;&lt;/p&gt;

\[\tanh&apos;(z) = 1 - \tanh^2(z)\]

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Range: \((-1, 1)\)&lt;/li&gt;
  &lt;li&gt;Zero-centered (improvement over sigmoid)&lt;/li&gt;
  &lt;li&gt;Saturates at both ends&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Zero-centered (better gradient flow)&lt;/li&gt;
  &lt;li&gt;Stronger gradients than sigmoid (derivative range: \((0, 1]\))&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Still suffers from vanishing gradients&lt;/li&gt;
  &lt;li&gt;Computationally expensive&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Hidden layers (better than sigmoid but worse than ReLU)&lt;/li&gt;
  &lt;li&gt;RNN/LSTM cells&lt;/li&gt;
  &lt;li&gt;When zero-centered outputs are beneficial&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-rectified-linear-unit-relu&quot;&gt;3. Rectified Linear Unit (ReLU)&lt;/h3&gt;

\[\text{ReLU}(z) = \max(0, z) = \begin{cases} z &amp;amp; \text{if } z &amp;gt; 0 \\ 0 &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/relu_function.jpg&quot; alt=&quot;ReLU function graph&quot; /&gt;
&lt;em&gt;Figure: \(\mathrm{ReLU}(x)=\max(0,x)=(x)^+\) — \(y=0\) for \(x&amp;lt;0\) and \(y=x\) for \(x\geq 0\). (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Derivative:&lt;/strong&gt;&lt;/p&gt;

\[\text{ReLU}&apos;(z) = \begin{cases} 1 &amp;amp; \text{if } z &amp;gt; 0 \\ 0 &amp;amp; \text{if } z \leq 0 \\ \text{undefined} &amp;amp; \text{if } z = 0 \end{cases}\]

&lt;p&gt;(In practice, we define \(\text{ReLU}&apos;(0) = 0\) or \(0.5\))&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Range: \([0, \infty)\)&lt;/li&gt;
  &lt;li&gt;Not saturating for positive values&lt;/li&gt;
  &lt;li&gt;Sparse activation (many neurons output 0)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Computational efficiency&lt;/strong&gt;: Just thresholding at zero&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Alleviates vanishing gradient&lt;/strong&gt;: Gradient is 1 for positive inputs&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sparse representations&lt;/strong&gt;: Natural sparsity&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Empirically successful&lt;/strong&gt;: Works very well in practice&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Not zero-centered&lt;/strong&gt;: All outputs are non-negative&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Dying ReLU problem&lt;/strong&gt;: Neurons can become inactive forever
    &lt;ul&gt;
      &lt;li&gt;If \(z &amp;lt; 0\) always, gradient is always 0, no learning occurs&lt;/li&gt;
      &lt;li&gt;Can happen with high learning rates or poor initialization&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Default choice&lt;/strong&gt; for hidden layers in deep networks&lt;/li&gt;
  &lt;li&gt;CNNs, ResNets, most modern architectures&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-leaky-relu&quot;&gt;4. Leaky ReLU&lt;/h3&gt;

\[\text{LeakyReLU}(z) = \begin{cases} z &amp;amp; \text{if } z &amp;gt; 0 \\ \alpha z &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;where \(\alpha\) is a small constant (typically 0.01)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Derivative:&lt;/strong&gt;&lt;/p&gt;

\[\text{LeakyReLU}&apos;(z) = \begin{cases} 1 &amp;amp; \text{if } z &amp;gt; 0 \\ \alpha &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Prevents dying ReLU&lt;/strong&gt;: Small gradient even for negative inputs&lt;/li&gt;
  &lt;li&gt;Computationally efficient&lt;/li&gt;
  &lt;li&gt;All benefits of ReLU&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Introduces hyperparameter \(\alpha\)&lt;/li&gt;
  &lt;li&gt;Not always better than ReLU in practice&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Variants:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Parametric ReLU (PReLU)&lt;/strong&gt;: \(\alpha\) is learned during training&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Randomized Leaky ReLU (RReLU)&lt;/strong&gt;: \(\alpha\) is randomly sampled during training&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;5-exponential-linear-unit-elu&quot;&gt;5. Exponential Linear Unit (ELU)&lt;/h3&gt;

\[\text{ELU}(z) = \begin{cases} z &amp;amp; \text{if } z &amp;gt; 0 \\ \alpha(e^z - 1) &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;where \(\alpha &amp;gt; 0\) (typically \(\alpha = 1\))&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Derivative:&lt;/strong&gt;&lt;/p&gt;

\[\text{ELU}&apos;(z) = \begin{cases} 1 &amp;amp; \text{if } z &amp;gt; 0 \\ \alpha e^z = \text{ELU}(z) + \alpha &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Smooth everywhere&lt;/li&gt;
  &lt;li&gt;Negative values push mean activation closer to zero&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Closer to zero-centered&lt;/strong&gt;: Negative outputs possible&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;No dying ReLU problem&lt;/strong&gt;: Gradients exist for all inputs&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Smooth&lt;/strong&gt;: Better deep-learning landscape&lt;/li&gt;
  &lt;li&gt;Often leads to faster learning and better performance&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Computationally more expensive (exponential)&lt;/li&gt;
  &lt;li&gt;Introduces hyperparameter \(\alpha\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Alternative to ReLU when extra computation is acceptable&lt;/li&gt;
  &lt;li&gt;Tasks where zero-centered activations help&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;6-scaled-exponential-linear-unit-selu&quot;&gt;6. Scaled Exponential Linear Unit (SELU)&lt;/h3&gt;

\[\text{SELU}(z) = \lambda \begin{cases} z &amp;amp; \text{if } z &amp;gt; 0 \\ \alpha(e^z - 1) &amp;amp; \text{if } z \leq 0 \end{cases}\]

&lt;p&gt;where \(\lambda \approx 1.0507\) and \(\alpha \approx 1.6733\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Self-normalizing&lt;/strong&gt;: Under certain conditions, activations automatically converge to zero mean and unit variance&lt;/li&gt;
  &lt;li&gt;Requires specific initialization (LeCun normal)&lt;/li&gt;
  &lt;li&gt;Requires specific architecture (fully connected layers)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Can enable very deep networks without batch normalization&lt;/li&gt;
  &lt;li&gt;Theoretical guarantees about convergence&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Strict requirements on network architecture&lt;/li&gt;
  &lt;li&gt;Not widely adopted&lt;/li&gt;
  &lt;li&gt;Doesn’t work well with dropout or convolutional layers&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;7-swish-silu---sigmoid-linear-unit&quot;&gt;7. Swish (SiLU - Sigmoid Linear Unit)&lt;/h3&gt;

\[\text{Swish}(z) = z \cdot \sigma(z) = \frac{z}{1 + e^{-z}}\]

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Smooth, non-monotonic&lt;/li&gt;
  &lt;li&gt;Unbounded above, bounded below&lt;/li&gt;
  &lt;li&gt;Self-gated (input modulated by sigmoid of itself)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Better performance&lt;/strong&gt;: Empirically shown to outperform ReLU in some tasks&lt;/li&gt;
  &lt;li&gt;Smooth gradients&lt;/li&gt;
  &lt;li&gt;Non-monotonicity can be beneficial&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Computationally more expensive than ReLU&lt;/li&gt;
  &lt;li&gt;Requires careful tuning&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Modern architectures (EfficientNet uses Swish)&lt;/li&gt;
  &lt;li&gt;When computational cost is not critical&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;8-gelu-gaussian-error-linear-unit&quot;&gt;8. GELU (Gaussian Error Linear Unit)&lt;/h3&gt;

\[\text{GELU}(z) = z \cdot \Phi(z)\]

&lt;p&gt;where \(\Phi(z)\) is the cumulative distribution function of the standard normal distribution.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Approximation:&lt;/strong&gt;&lt;/p&gt;

\[\text{GELU}(z) \approx 0.5z\left(1 + \tanh\left(\sqrt{\frac{2}{\pi}}(z + 0.044715z^3)\right)\right)\]

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Smooth, non-monotonic&lt;/li&gt;
  &lt;li&gt;Stochastic regularizer interpretation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;State-of-the-art performance&lt;/strong&gt;: Used in BERT, GPT models&lt;/li&gt;
  &lt;li&gt;Smooth everywhere&lt;/li&gt;
  &lt;li&gt;Captures aspects of dropout and zoneout&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Computationally expensive&lt;/li&gt;
  &lt;li&gt;Harder to interpret&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Transformer models&lt;/strong&gt;: BERT, GPT-2, GPT-3&lt;/li&gt;
  &lt;li&gt;NLP tasks&lt;/li&gt;
  &lt;li&gt;Modern large-scale models&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;9-softmax-output-layer&quot;&gt;9. Softmax (Output Layer)&lt;/h3&gt;

\[\text{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_{j=1}^K e^{z_j}}\]

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Converts logits to probability distribution&lt;/li&gt;
  &lt;li&gt;Output range: \((0, 1)\) with \(\sum_i p_i = 1\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Derivative (for class \(i\) with respect to \(z_j\)):&lt;/strong&gt;&lt;/p&gt;

\[\frac{\partial \text{softmax}(\mathbf{z})_i}{\partial z_j} = \begin{cases} \text{softmax}(\mathbf{z})_i(1 - \text{softmax}(\mathbf{z})_i) &amp;amp; \text{if } i = j \\ -\text{softmax}(\mathbf{z})_i \cdot \text{softmax}(\mathbf{z})_j &amp;amp; \text{if } i \neq j \end{cases}\]

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Multi-class classification&lt;/strong&gt; output layer&lt;/li&gt;
  &lt;li&gt;Attention mechanisms&lt;/li&gt;
  &lt;li&gt;Any scenario requiring probability distribution over classes&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;10-softplus&quot;&gt;10. Softplus&lt;/h3&gt;

\[\text{softplus}(z) = \ln(1 + e^z)\]

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Smooth approximation of ReLU&lt;/li&gt;
  &lt;li&gt;Always positive&lt;/li&gt;
  &lt;li&gt;Asymptotically approaches ReLU for large \(z\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Derivative:&lt;/strong&gt;&lt;/p&gt;

\[\text{softplus}&apos;(z) = \frac{e^z}{1 + e^z} = \sigma(z)\]

&lt;p&gt;&lt;strong&gt;Use cases:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Occasionally used in hidden layers&lt;/li&gt;
  &lt;li&gt;Generative models (ensuring positive outputs)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;comparison-summary&quot;&gt;Comparison Summary&lt;/h2&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Activation&lt;/th&gt;
      &lt;th&gt;Range&lt;/th&gt;
      &lt;th&gt;Zero-Centered&lt;/th&gt;
      &lt;th&gt;Vanishing Gradient&lt;/th&gt;
      &lt;th&gt;Dying Units&lt;/th&gt;
      &lt;th&gt;Computational Cost&lt;/th&gt;
      &lt;th&gt;Common Use&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Sigmoid&lt;/td&gt;
      &lt;td&gt;(0,1)&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;High&lt;/td&gt;
      &lt;td&gt;Output (binary)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;tanh&lt;/td&gt;
      &lt;td&gt;(-1,1)&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;High&lt;/td&gt;
      &lt;td&gt;Hidden (old), RNN&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ReLU&lt;/td&gt;
      &lt;td&gt;[0,∞)&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;No (for z&amp;gt;0)&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Low&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Hidden (default)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Leaky ReLU&lt;/td&gt;
      &lt;td&gt;(-∞,∞)&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Low&lt;/strong&gt;&lt;/td&gt;
      &lt;td&gt;Hidden&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;ELU&lt;/td&gt;
      &lt;td&gt;(-α,∞)&lt;/td&gt;
      &lt;td&gt;~Yes&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Medium&lt;/td&gt;
      &lt;td&gt;Hidden&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;SELU&lt;/td&gt;
      &lt;td&gt;(-λα,∞)&lt;/td&gt;
      &lt;td&gt;Yes (self-norm)&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Medium&lt;/td&gt;
      &lt;td&gt;Hidden (specific)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Swish&lt;/td&gt;
      &lt;td&gt;(-∞,∞)&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;Medium&lt;/td&gt;
      &lt;td&gt;Hidden (modern)&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;GELU&lt;/td&gt;
      &lt;td&gt;(-∞,∞)&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;High&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Transformers&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Softmax&lt;/td&gt;
      &lt;td&gt;(0,1)&lt;/td&gt;
      &lt;td&gt;N/A&lt;/td&gt;
      &lt;td&gt;Yes&lt;/td&gt;
      &lt;td&gt;No&lt;/td&gt;
      &lt;td&gt;High&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;Output (multi-class)&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/793200140509765&quot;&gt;Neural network intuition (Perceptron → Deep Learning)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=NkOv_k7r6no&quot;&gt;Why Non-linear Activation Functions (C1W3L07)&lt;/a&gt; — DeepLearningAI, English. The properties a useful activation must have.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=68BZ5f7P94E&quot;&gt;Neural Networks Pt. 3: ReLU In Action!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. ReLU in a numerical forward pass, which is the worked example for the classic list (step, sigmoid, tanh, ReLU).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=KpKog-L9veg&quot;&gt;Neural Networks Part 5: ArgMax and SoftMax&lt;/a&gt; — StatQuest with Josh Starmer, English. Softmax is the output activation the comparison table needs for classification heads.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-02 Neural Network Architecture</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_02_Neural_Network_Architecture/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_02_Neural_Network_Architecture</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Give two engineers the exact same budget of one million parameters—one builds a single wide layer, the other builds a structured 8-layer bottleneck—and their test accuracies can differ by twenty points. Architecture is how we encode assumptions about the geometry of the problem directly into the computational graph.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-principles-of-neural-architecture-design&quot;&gt;Key ideas: Principles of Neural Architecture Design&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hierarchical Composition&lt;/strong&gt;: Early layers extract local, reusable primitives while deeper layers assemble them into invariant global concepts.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Width vs. Depth Trade-Off&lt;/strong&gt;: Width expands instantaneous representational bandwidth and eases optimization; depth multiplies compositional expressivity exponentially per parameter.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Information Bottlenecks &amp;amp; Skip Connections&lt;/strong&gt;: Bottlenecks force compression of task-relevant signals (as in autoencoders), while residual pathways preserve gradient flow across very deep stacks.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter &amp;amp; Activation Memory Budgeting&lt;/strong&gt;: Balances expressivity against overfitting and hardware memory limits by sizing each layer deliberately rather than arbitrarily.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-comparing-two-equal-parameter-architectures-wide-vs-deep&quot;&gt;Worked example: Comparing Two Equal-Parameter Architectures (Wide vs. Deep)&lt;/h3&gt;

&lt;p&gt;Suppose an input has dimension \(d_{\text{in}} = 64\) and output has \(d_{\text{out}} = 4\), and we compare two MLPs with nearly identical parameter counts (ignoring biases for quick estimation):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Architecture A (Wide, 1 hidden layer)&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;64 -&amp;gt; 128 -&amp;gt; 4&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Architecture B (Deep, 2 hidden layers)&lt;/strong&gt;: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;64 -&amp;gt; 64 -&amp;gt; 64 -&amp;gt; 4&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Count Parameters of Architecture A (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;64 -&amp;gt; 128 -&amp;gt; 4&lt;/code&gt;)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Layer 1: \(64 \times 128 + 128 = 8{,}320\)&lt;/li&gt;
      &lt;li&gt;Layer 2: \(128 \times 4 + 4 = 516\)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Total A&lt;/strong&gt;: \(8{,}836\) parameters.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Count Parameters of Architecture B (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;64 -&amp;gt; 64 -&amp;gt; 64 -&amp;gt; 4&lt;/code&gt;)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Layer 1: \(64 \times 64 + 64 = 4{,}160\)&lt;/li&gt;
      &lt;li&gt;Layer 2: \(64 \times 64 + 64 = 4{,}160\)&lt;/li&gt;
      &lt;li&gt;Layer 3: \(64 \times 4 + 4 = 260\)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Total B&lt;/strong&gt;: \(8{,}580\) parameters (even fewer than A!).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Architectural Comparison&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Latency / Parallelism&lt;/strong&gt;: Architecture A executes in 2 sequential matrix multiplies; B requires 3.&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Representational Capacity&lt;/strong&gt;: Architecture B composes two nonlinear warps in 64D space, giving it exponentially higher piecewise-linear region capacity per parameter than Architecture A—showing why moderate depth almost always outperforms a single wide slab at equal parameter cost.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Neural network architecture from neurons to deep systems:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Architecture Theory&lt;/strong&gt; — concept overview, math, and intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Depth, Width, and Design Patterns&lt;/strong&gt; — design choices, representation, implementation, considerations&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. Depth as a stack of learned functions.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=CqOfi41LfDw&quot;&gt;The Essential Main Ideas of Neural Networks&lt;/a&gt; — StatQuest with Josh Starmer, English. Makes width concrete: more hidden units, a more flexible squiggle.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 4&lt;/td&gt;
          &lt;td&gt;Introduction to Neural Networks](https://www.youtube.com/watch?v=d14TUNcbn1k) — Stanford University School of Engineering, English. Stanford’s architecture picture for fully connected nets, before later chapters change the wiring.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-02-02 Depth, Width, and Design Patterns</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_02_02_Depth_Width_and_Design/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_02_02_Depth_Width_and_Design</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Look at modern architectures across deep learning—the tapered pyramid of VGG classifiers, the hourglass bottleneck of autoencoders and U-Nets, or the uniform residual stream of Transformers—and you will see deliberate width profiles engineered to control information flow and compute.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-width-profiles--architectural-patterns&quot;&gt;Key ideas: Width Profiles &amp;amp; Architectural Patterns&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tapered / Decreasing Width (Classification Funnels)&lt;/strong&gt;: Progressively compresses high-dimensional raw inputs (e.g., &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;784 -&amp;gt; 256 -&amp;gt; 64 -&amp;gt; 10&lt;/code&gt;) into low-dimensional class logits, discarding nuisance variation layer by layer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hourglass / Bottleneck Pattern (Compression &amp;amp; Denoising)&lt;/strong&gt;: Forces representations through a narrow latent waist \(d_z \ll d_{\text{in}}\) before expanding back, compelling the network to retain only the true generative factors of the data.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Uniform Width &amp;amp; Residual Streams (Transformers &amp;amp; ResNets)&lt;/strong&gt;: Keeps feature dimension \(d_{\text{model}}\) constant across blocks so identity skip connections \(\mathbf{x} + F(\mathbf{x})\) add cleanly without shape-matching projections.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Inverted Bottlenecks (MobileNet &amp;amp; Transformer FFNs)&lt;/strong&gt;: Temporarily expands width (e.g., \(d \to 4d \to d\)) to apply nonlinearities in a richer higher-dimensional space before projecting back to the compact residual stream.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-compute--memory-analysis-of-a-transformer-inverted-bottleneck-d-to-4d-to-d&quot;&gt;Worked example: Compute &amp;amp; Memory Analysis of a Transformer Inverted Bottleneck (\(d \to 4d \to d\))&lt;/h3&gt;

&lt;p&gt;Consider a standard Transformer MLP block with residual width \(d = 512\) and expansion ratio \(4\times\) (hidden width \(4d = 2048\)), processing a sequence of \(T = 128\) tokens (batch \(B = 1\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Parameter Count of the Two Linear Layers&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Up-projection (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;512 -&amp;gt; 2048&lt;/code&gt;): \(512 \times 2048 + 2048 = 1{,}050{,}624\)&lt;/li&gt;
      &lt;li&gt;Down-projection (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;2048 -&amp;gt; 512&lt;/code&gt;): \(2048 \times 512 + 512 = 1{,}049{,}088\)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Total parameters&lt;/strong&gt;: \(2{,}099{,}712 \approx 2.10\text{M}\) (roughly \(8d^2\)).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Forward-Pass FLOPs (Multiply-Adds = \(2 \times \text{MACs}\))&lt;/strong&gt;:
Each token performs \(512 \times 2048 = 1{,}048{,}576\) MACs in each layer (\(2 \times 1.049\text{M} = 2.097\text{M}\) MACs total, or \(4.194\text{M}\) FLOPs per token). Across \(T = 128\) tokens:
\(\text{Total FLOPs} = 128 \times 4.194 \times 10^6 \approx 5.37 \times 10^8\text{ FLOPs (0.537 GFLOPs)}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Peak Activation Memory (Stored for Backprop in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FP16&lt;/code&gt;, 2 bytes/element)&lt;/strong&gt;:
The expanded hidden tensor has shape &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(128, 2048)&lt;/code&gt; = \(262{,}144\) elements \(\times 2\text{ bytes} = 524{,}288\text{ bytes} = 512\text{ KB}\) per layer—showing why expanding width boosts nonlinearity capacity while multiplying activation memory linearly with the expansion factor.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;network-depth-and-width&quot;&gt;Network Depth and Width&lt;/h2&gt;

&lt;h3 id=&quot;width&quot;&gt;Width&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;width&lt;/strong&gt; of a layer refers to the number of neurons it contains.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Wider networks&lt;/strong&gt;: More neurons per layer
    &lt;ul&gt;
      &lt;li&gt;Greater capacity to learn complex patterns within a single layer&lt;/li&gt;
      &lt;li&gt;More parameters (can lead to overfitting)&lt;/li&gt;
      &lt;li&gt;More computational cost per layer&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;depth&quot;&gt;Depth&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;depth&lt;/strong&gt; of a network refers to the number of layers.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Deeper networks&lt;/strong&gt;: More layers
    &lt;ul&gt;
      &lt;li&gt;Can learn hierarchical representations&lt;/li&gt;
      &lt;li&gt;More expressive (can represent more complex functions)&lt;/li&gt;
      &lt;li&gt;Can be harder to train (vanishing/exploding gradients)&lt;/li&gt;
      &lt;li&gt;The term “deep learning” comes from using deep networks&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;the-universal-approximation-theorem&quot;&gt;The Universal Approximation Theorem&lt;/h3&gt;

&lt;div class=&quot;textbook-theorem&quot;&gt;
  &lt;p&gt;&lt;strong&gt;Theorem&lt;/strong&gt;: A feedforward neural network with:&lt;/p&gt;
  &lt;ul&gt;
    &lt;li&gt;A single hidden layer&lt;/li&gt;
    &lt;li&gt;Finite number of neurons&lt;/li&gt;
    &lt;li&gt;Appropriate activation function (e.g., sigmoid, ReLU)&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;can approximate any continuous function on a compact subset of \(\mathbb{R}^n\) to arbitrary accuracy.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important Notes:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;This is an &lt;strong&gt;existence theorem&lt;/strong&gt;, not a practical guideline&lt;/li&gt;
  &lt;li&gt;It doesn’t specify how many neurons are needed (could be exponentially many)&lt;/li&gt;
  &lt;li&gt;Deeper networks can often approximate functions with far fewer parameters&lt;/li&gt;
  &lt;li&gt;Deeper networks tend to learn hierarchical features naturally&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Visualizing depth/width via 1D curve fitting:&lt;/strong&gt; same wavy data — low capacity → poor fit; more hidden units + training → strong fit (see Architecture Theory for the full image set).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_shallow_poor_fit.jpg&quot; alt=&quot;Poor fit with low capacity&quot; /&gt;
&lt;em&gt;Figure: Too thin/shallow to approximate the target. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_deeper_good_fit.jpg&quot; alt=&quot;Good fit with enough capacity&quot; /&gt;
&lt;em&gt;Figure: Enough depth/width + training → near-perfect function approximation. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;common-design-patterns&quot;&gt;Common Design Patterns&lt;/h2&gt;

&lt;h3 id=&quot;decreasing-width&quot;&gt;Decreasing Width&lt;/h3&gt;

&lt;p&gt;A common pattern is to gradually decrease the layer width:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (784) → 512 → 256 → 128 → 64 → Output (10)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Rationale&lt;/strong&gt;: Progressively compress information into higher-level abstractions.&lt;/p&gt;

&lt;h3 id=&quot;hourglassbottleneck-architecture&quot;&gt;Hourglass/Bottleneck Architecture&lt;/h3&gt;

&lt;p&gt;Decrease then increase width:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (784) → 256 → 64 → 256 → Output (784)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Use case&lt;/strong&gt;: Autoencoders for dimensionality reduction and reconstruction.&lt;/p&gt;

&lt;h3 id=&quot;uniform-width&quot;&gt;Uniform Width&lt;/h3&gt;

&lt;p&gt;Keep all hidden layers the same size:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (784) → 256 → 256 → 256 → Output (10)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Rationale&lt;/strong&gt;: Simplicity and easier hyperparameter tuning.&lt;/p&gt;

&lt;h2 id=&quot;activation-functions-per-layer&quot;&gt;Activation Functions Per Layer&lt;/h2&gt;

&lt;p&gt;Different layers can use different activation functions:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Typical configuration:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Hidden layers&lt;/strong&gt;: ReLU (or variants like Leaky ReLU, ELU)
    &lt;ul&gt;
      &lt;li&gt;Computational efficiency&lt;/li&gt;
      &lt;li&gt;Mitigates vanishing gradient&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Output layer&lt;/strong&gt;: Task-dependent
    &lt;ul&gt;
      &lt;li&gt;Binary classification: Sigmoid&lt;/li&gt;
      &lt;li&gt;Multi-class classification: Softmax&lt;/li&gt;
      &lt;li&gt;Regression: Linear (identity function)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;fully-connected-vs-other-architectures&quot;&gt;Fully Connected vs. Other Architectures&lt;/h2&gt;

&lt;h3 id=&quot;fully-connected-dense-layers&quot;&gt;Fully Connected (Dense) Layers&lt;/h3&gt;

&lt;p&gt;Every neuron in layer \(l\) is connected to every neuron in layer \(l-1\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Advantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Maximum flexibility&lt;/li&gt;
  &lt;li&gt;Can learn any pattern (given enough neurons)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disadvantages:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Many parameters (\(n^{[l]} \times n^{[l-1]}\))&lt;/li&gt;
  &lt;li&gt;No built-in assumption about input structure&lt;/li&gt;
  &lt;li&gt;Not efficient for structured data (images, sequences)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;specialized-architectures&quot;&gt;Specialized Architectures&lt;/h3&gt;

&lt;p&gt;For specific data types, specialized architectures are more efficient:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Convolutional layers&lt;/strong&gt;: For images (spatial structure)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Recurrent layers&lt;/strong&gt;: For sequences (temporal structure)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Attention mechanisms&lt;/strong&gt;: For handling long-range dependencies&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;We’ll cover these in later chapters.&lt;/p&gt;

&lt;h2 id=&quot;network-representation&quot;&gt;Network Representation&lt;/h2&gt;

&lt;h3 id=&quot;graphical-representation&quot;&gt;Graphical Representation&lt;/h3&gt;

&lt;p&gt;Networks are often visualized as directed acyclic graphs (DAGs):&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;      Input Layer    Hidden Layer 1   Hidden Layer 2   Output Layer
         (3)             (4)              (4)              (2)
    
    x₁  ○────────────────●──────────────────●──────────────────●  ŷ₁
                        ╱│╲              ╱│╲              ╱│
    x₂  ○──────────────●─●─●────────────●─●─●────────────●─●
                        ╲│╱              ╲│╱              ╲│
    x₃  ○────────────────●──────────────────●──────────────────●  ŷ₂
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;matrix-representation&quot;&gt;Matrix Representation&lt;/h3&gt;

&lt;p&gt;For computational efficiency, we represent operations as matrix multiplications:&lt;/p&gt;

\[\mathbf{Z}^{[l]} = \mathbf{W}^{[l]} \mathbf{A}^{[l-1]} + \mathbf{b}^{[l]}\]

&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{A}^{[l-1]}\): activation matrix (each column is one example)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}^{[l]}\): weight matrix&lt;/li&gt;
  &lt;li&gt;\(\mathbf{b}^{[l]}\): bias vector (broadcasted across examples)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;practical-implementation&quot;&gt;Practical Implementation&lt;/h2&gt;

&lt;h3 id=&quot;example-simple-neural-network-in-python&quot;&gt;Example: Simple Neural Network in Python&lt;/h3&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        layer_sizes: list of layer sizes including input and output
        Example: [784, 128, 64, 10] for MNIST
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Initialize weights and biases
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;biases&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# He initialization for ReLU networks
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;w&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;layer_sizes&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;w&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;biases&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;maximum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;exp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;exp_z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;keepdims&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        x: input of shape (input_size, num_examples)
        Returns: output of shape (output_size, num_examples)
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;zs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Forward through hidden layers
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;num_layers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;biases&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;zs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Output layer (softmax)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;@&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;biases&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;softmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;zs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;zs&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Returns class predictions&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;axis&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Example usage
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;network&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;NeuralNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# 5 examples
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;network&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Output shape: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;shape&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# (10, 5)
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;network&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;design-considerations&quot;&gt;Design Considerations&lt;/h2&gt;

&lt;h3 id=&quot;number-of-layers&quot;&gt;Number of Layers&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;1-2 hidden layers&lt;/strong&gt;: Simple problems, small datasets&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;3-5 hidden layers&lt;/strong&gt;: Moderate complexity&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;5+ hidden layers&lt;/strong&gt;: Complex problems, large datasets, “deep” learning&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;number-of-neurons-per-layer&quot;&gt;Number of Neurons Per Layer&lt;/h3&gt;

&lt;p&gt;Rules of thumb:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Start with layers of size between input and output size&lt;/li&gt;
  &lt;li&gt;Common sizes: 32, 64, 128, 256, 512&lt;/li&gt;
  &lt;li&gt;More neurons = more capacity but more overfitting risk&lt;/li&gt;
  &lt;li&gt;Use validation performance to guide choices&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;architecture-search&quot;&gt;Architecture Search&lt;/h3&gt;

&lt;p&gt;Finding the optimal architecture is often done through:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Manual experimentation&lt;/strong&gt;: Try different configurations&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Grid search&lt;/strong&gt;: Systematically try combinations&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Random search&lt;/strong&gt;: Often more efficient than grid search&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Neural Architecture Search (NAS)&lt;/strong&gt;: Automated methods (advanced topic)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Neural networks&lt;/strong&gt; consist of layers of neurons organized into input, hidden, and output layers&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Feedforward networks&lt;/strong&gt; (MLPs) are the simplest architecture where information flows in one direction&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Forward propagation&lt;/strong&gt; computes the output by passing inputs through successive layers&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Network depth&lt;/strong&gt; (number of layers) and &lt;strong&gt;width&lt;/strong&gt; (neurons per layer) determine capacity&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Universal Approximation Theorem&lt;/strong&gt; shows networks can approximate any function, but doesn’t guarantee efficiency&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Fully connected layers&lt;/strong&gt; connect every neuron to every neuron in adjacent layers&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Proper architecture design&lt;/strong&gt; depends on the problem, data, and computational resources&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the next lesson, we’ll explore activation functions in more detail and understand their critical role in learning.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/720970114372332&quot;&gt;Neural nets as function approximators&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. What extra depth buys, before the design-pattern section.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qhXZsFVxGKo&quot;&gt;Vanishing/Exploding Gradients (C2W1L10)&lt;/a&gt; — DeepLearningAI, English. Vanishing gradients are the reason naive depth fails, which this lesson’s design section is reacting to.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2FaI2Fen1mQ&quot;&gt;The GELU, SiLU and SwiGLU activation functions, clearly explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. GELU, SiLU, and SwiGLU are the modern per-layer choices the design section points toward.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-02-01 Neural Network Architecture Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_02_01_Architecture_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_02_01_Architecture_Theory</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;A feedforward neural network is formally nothing more than a directed acyclic graph of affine maps and elementwise nonlinearities. Yet out of that clean algebraic recursion emerges the Universal Approximation Theorem and the geometric power to untangle knotted data manifolds.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-formal-theory-of-feedforward-architectures&quot;&gt;Key ideas: Formal Theory of Feedforward Architectures&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Feedforward Recursion&lt;/strong&gt;: Defines layer \(l\) strictly via \(\mathbf{z}^{[l]} = W^{[l]}\mathbf{a}^{[l-1]} + \mathbf{b}^{[l]}\) and \(\mathbf{a}^{[l]} = g^{[l]}(\mathbf{z}^{[l]})\), with \(\mathbf{a}^{[0]} = \mathbf{x}\) and \(\hat{\mathbf{y}} = \mathbf{a}^{[L]}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Manifold Untangling View&lt;/strong&gt;: Each layer acts as a homeomorphic/piecewise-linear warp of \(\mathbb{R}^{d_l}\) whose goal is to deform curved, interwoven class manifolds until the final linear head can slice them with a flat hyperplane.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Universal Approximation (Cybenko / Hornik)&lt;/strong&gt;: Proves density of single-hidden-layer networks in \(C(K)\) on compact sets \(K \subset \mathbb{R}^d\), while warning that required width can grow exponentially in dimension \(d\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Depth Separation Theorems&lt;/strong&gt;: Demonstrate explicit functions (e.g., radial indicators and high-frequency compositions) representable by a polynomial-size 3-layer network that require exponential width in a 2-layer network.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-solving-2d-xor-exactly-by-warping-input-space&quot;&gt;Worked example: Solving 2D XOR Exactly by Warping Input Space&lt;/h3&gt;

&lt;p&gt;Recall the 4 XOR points in \(\mathbb{R}^2\): \((0,0)\to 0\), \((0,1)\to 1\), \((1,0)\to 1\), \((1,1)\to 0\). Let us apply one ReLU hidden layer with:
\(W^{[1]} = \begin{bmatrix} 1 &amp;amp; 1 \\ 1 &amp;amp; 1 \end{bmatrix}, \quad \mathbf{b}^{[1]} = \begin{bmatrix} 0 \\ -1 \end{bmatrix}, \quad W^{[2]} = \begin{bmatrix} 1 &amp;amp; -2 \end{bmatrix}, \quad b^{[2]} = 0\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Map All 4 Inputs Into Hidden Space \(\mathbf{a}^{[1]} = \text{ReLU}(W^{[1]}\mathbf{x} + \mathbf{b}^{[1]})\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(\mathbf{x} = (0,0)\): \(\mathbf{z}^{[1]} = (0, -1) \implies \mathbf{a}^{[1]} = (0, 0)\)&lt;/li&gt;
      &lt;li&gt;\(\mathbf{x} = (0,1)\): \(\mathbf{z}^{[1]} = (1, 0) \implies \mathbf{a}^{[1]} = (1, 0)\)&lt;/li&gt;
      &lt;li&gt;\(\mathbf{x} = (1,0)\): \(\mathbf{z}^{[1]} = (1, 0) \implies \mathbf{a}^{[1]} = (1, 0)\)&lt;/li&gt;
      &lt;li&gt;\(\mathbf{x} = (1,1)\): \(\mathbf{z}^{[1]} = (2, 1) \implies \mathbf{a}^{[1]} = (2, 1)\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Observe the Geometric Collapse&lt;/strong&gt;:
Both positive XOR corners \((0,1)\) and \((1,0)\) collapsed onto the exact same hidden coordinate \((1, 0)\), while \((0,0)\) and \((1,1)\) lie on the line \(a_1 - 2a_2 = 0\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply the Linear Output Head \(\hat{y} = a_1^{[1]} - 2a_2^{[1]}\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;
\[(0,0) \mapsto 0 - 2(0) = 0\]
      &lt;/li&gt;
      &lt;li&gt;
\[(0,1) \mapsto 1 - 2(0) = 1\]
      &lt;/li&gt;
      &lt;li&gt;
\[(1,0) \mapsto 1 - 2(0) = 1\]
      &lt;/li&gt;
      &lt;li&gt;\((1,1) \mapsto 2 - 2(1) = 0\)
Zero error on all four points—a textbook demonstration of how hidden layers untangle non-linearly separable manifolds.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;neural-network-architecture-from-neurons-to-deep-systems&quot;&gt;Neural Network Architecture: From Neurons to Deep Systems&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/4/46/Colored_neural_network.svg/500px-Colored_neural_network.svg.png&quot; alt=&quot;Neural Network Layers&quot; /&gt;
&lt;em&gt;Figure: Neural network architecture with input, hidden, and output layers. Source: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/mlp_fully_connected.jpg&quot; alt=&quot;Fully connected multilayer network&quot; /&gt;
&lt;em&gt;Figure: Fully connected feedforward network — input (pink), hidden (green), output (blue). (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;Neural network architecture is the blueprint that defines how individual neurons are organized, connected, and structured to solve complex problems. While a single neuron can only learn linear decision boundaries (as we saw with the perceptron), the true power of deep learning emerges when we compose many neurons into layers and stack these layers into deep architectures. This compositional structure is not merely a engineering convenience—it reflects a profound insight about how complex intelligence can emerge from simple computational units working in concert.&lt;/p&gt;

&lt;p&gt;Understanding architecture is crucial because the way we organize neurons fundamentally determines what a network can learn and how efficiently it learns. A poorly designed architecture might fail to learn even simple patterns, while a well-designed one can discover intricate relationships in data with remarkable efficiency. The architecture embodies our inductive biases—our assumptions about the problem structure—allowing the network to learn more effectively than treating all problems as completely general function approximation tasks.&lt;/p&gt;

&lt;h3 id=&quot;the-layered-paradigm&quot;&gt;The Layered Paradigm&lt;/h3&gt;

&lt;p&gt;The fundamental organizing principle of neural networks is &lt;strong&gt;layers&lt;/strong&gt;—groups of neurons that perform transformations at the same stage of computation. This layered structure naturally implements compositional computation: each layer transforms its input into a new representation, and subsequent layers build on these representations to create increasingly abstract features. When recognizing a face, early layers might detect edges, middle layers combine edges into facial features (eyes, nose, mouth), and deep layers recognize complete identities.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Digit-image example.&lt;/strong&gt; A \(28\times28\) image is flattened to \(784\) inputs, passed through hidden layers, then to \(10\) outputs (classes \(0\)–\(9\)). There is no fixed formula for hidden width — that is an architecture choice — but the pipeline is always: vectorize → stack layers → task-specific outputs.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/mnist_mlp_10_outputs.jpg&quot; alt=&quot;Digit MLP: 784 → hidden → 10&quot; /&gt;
&lt;em&gt;Figure: MNIST-style pipeline — \(784\) pixels → hidden layers → \(10\) logits for digit classes. (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This hierarchical processing mirrors both biological neural systems and the compositional nature of many real-world concepts. A “car” is composed of wheels, windows, and doors; these components are composed of shapes and textures; these are composed of edges and colors. Neural network layers naturally capture this hierarchy through learned transformations, with each layer learning the appropriate level of abstraction for its position in the processing pipeline.&lt;/p&gt;

&lt;h3 id=&quot;why-architecture-matters-the-depth-vs-width-tradeoff&quot;&gt;Why Architecture Matters: The Depth vs Width Tradeoff&lt;/h3&gt;

&lt;p&gt;A critical insight from both theory and practice is that &lt;strong&gt;depth&lt;/strong&gt; (number of layers) and &lt;strong&gt;width&lt;/strong&gt; (neurons per layer) have fundamentally different effects on network capacity and learning. The Universal Approximation Theorem tells us that a single hidden layer with sufficiently many neurons can approximate any continuous function. Yet in practice, deep networks with relatively few neurons per layer dramatically outperform shallow wide networks on complex tasks.&lt;/p&gt;

&lt;p&gt;This isn’t just about parameter efficiency, though deep networks often achieve the same representational power with exponentially fewer parameters than shallow ones. Deep networks learn hierarchical features naturally—you don’t need to tell them to detect edges first, then shapes, then objects; this emerges automatically from the training process. They also exhibit better generalization: the intermediate representations learned by deep networks transfer across tasks, enabling powerful techniques like transfer learning and pre-training that shallow networks don’t support nearly as well.&lt;/p&gt;

&lt;p&gt;Understanding the tradeoff between depth and width, and how architecture choices affect training dynamics, generalization, and computational efficiency, is essential for designing effective neural networks. This lesson provides the foundational understanding of how networks are structured, why these structures work, and how to make informed architectural decisions for your own applications.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;h3 id=&quot;feedforward-neural-networks-formal-definition&quot;&gt;Feedforward Neural Networks: Formal Definition&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;feedforward neural network&lt;/strong&gt; (also called &lt;strong&gt;Multilayer Perceptron&lt;/strong&gt; or &lt;strong&gt;MLP&lt;/strong&gt;) is a function \(f: \mathbb{R}^{n_0} \to \mathbb{R}^{n_L}\) defined by composition of layer transformations. For a network with \(L\) layers, the function is:&lt;/p&gt;

\[f(\mathbf{x}) = f^{[L]} \circ f^{[L-1]} \circ \cdots \circ f^{[1]}(\mathbf{x})\]

&lt;p&gt;where each layer function \(f^{[l]}\) is an affine transformation followed by an element-wise nonlinearity:&lt;/p&gt;

\[f^{[l]}(\mathbf{a}^{[l-1]}) = \sigma^{[l]}(\mathbf{W}^{[l]} \mathbf{a}^{[l-1]} + \mathbf{b}^{[l]})\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_hidden_activation_formula.jpg&quot; alt=&quot;Hidden layer + activation formulas&quot; /&gt;
&lt;em&gt;Figure: One hidden layer \(z_1=\sigma(xw+b)\) then a linear output \(f(x)\). (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_width_parameters_formula.jpg&quot; alt=&quot;Increasing width (more hidden units)&quot; /&gt;
&lt;em&gt;Figure: Growing the width of \(W\) (more hidden neurons) increases parameters and capacity. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_hidden_layer_diagram.jpg&quot; alt=&quot;Hidden layer diagram&quot; /&gt;
&lt;em&gt;Figure: Input → hidden → output edges correspond to the matrices \(W\). (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Let’s carefully unpack each component and understand why this seemingly simple formulation is so powerful.&lt;/p&gt;

&lt;h3 id=&quot;layer-by-layer-computation&quot;&gt;Layer-by-Layer Computation&lt;/h3&gt;

&lt;p&gt;For a network with \(L\) layers (not counting the input), layer \(l \in \{1, 2, \ldots, L\}\) computes:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pre-activation (linear transformation)&lt;/strong&gt;:
\(\mathbf{z}^{[l]} = \mathbf{W}^{[l]} \mathbf{a}^{[l-1]} + \mathbf{b}^{[l]}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Activation (nonlinear transformation)&lt;/strong&gt;:
\(\mathbf{a}^{[l]} = \sigma^{[l]}(\mathbf{z}^{[l]})\)&lt;/p&gt;

&lt;p&gt;The dimensions are:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{a}^{[l-1]} \in \mathbb{R}^{n_{l-1}}\): input to layer \(l\) (output from previous layer)&lt;/li&gt;
  &lt;li&gt;\(\mathbf{W}^{[l]} \in \mathbb{R}^{n_l \times n_{l-1}}\): weight matrix&lt;/li&gt;
  &lt;li&gt;\(\mathbf{b}^{[l]} \in \mathbb{R}^{n_l}\): bias vector&lt;/li&gt;
  &lt;li&gt;\(\mathbf{z}^{[l]} \in \mathbb{R}^{n_l}\): pre-activation values&lt;/li&gt;
  &lt;li&gt;\(\mathbf{a}^{[l]} \in \mathbb{R}^{n_l}\): post-activation values (layer output)&lt;/li&gt;
  &lt;li&gt;\(n_l\): number of neurons in layer \(l\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;the-role-of-each-component&quot;&gt;The Role of Each Component&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Weight Matrix \(\mathbf{W}^{[l]}\)&lt;/strong&gt;: Each row \(\mathbf{w}_i^{[l]}\) defines one neuron’s linear combination of inputs. The matrix multiplication \(\mathbf{W}^{[l]} \mathbf{a}^{[l-1]}\) computes all neurons’ pre-activations in parallel. The weights are the learnable parameters that adapt during training to capture patterns in data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bias Vector \(\mathbf{b}^{[l]}\)&lt;/strong&gt;: Shifts the activation function left or right, allowing neurons to activate even when inputs are near zero. Without bias, a ReLU neuron with all-zero inputs would always output zero, limiting expressiveness. Bias is crucial for learning appropriate thresholds.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Activation Function \(\sigma^{[l]}\)&lt;/strong&gt;: Introduces nonlinearity, enabling the network to learn non-linear decision boundaries. Without activation functions, stacking layers would be pointless—multiple linear transformations compose into a single linear transformation. Common choices include:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;ReLU: \(\sigma(z) = \max(0, z)\)&lt;/li&gt;
  &lt;li&gt;Sigmoid: \(\sigma(z) = \frac{1}{1+e^{-z}}\)&lt;/li&gt;
  &lt;li&gt;Tanh: \(\sigma(z) = \tanh(z)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;output-layer-design&quot;&gt;Output Layer Design&lt;/h3&gt;

&lt;p&gt;The output layer’s structure depends fundamentally on the task, as it must produce outputs in the appropriate format for the loss function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Binary Classification&lt;/strong&gt; (\(y \in \{0, 1\}\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Single output neuron with sigmoid activation&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Interpretation: $$\hat{y} = P(y=1&lt;/td&gt;
          &lt;td&gt;\mathbf{x})$$&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;Output: \(\hat{y} = \sigma(z) = \frac{1}{1 + e^{-z}} \in (0,1)\)&lt;/li&gt;
  &lt;li&gt;Loss: Binary cross-entropy \(\mathcal{L} = -[y \log \hat{y} + (1-y) \log(1-\hat{y})]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Multi-class Classification&lt;/strong&gt; (\(y \in \{1,2,\ldots,K\}\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(K\) output neurons with softmax activation&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;Interpretation: $$\hat{y}_k = P(y=k&lt;/td&gt;
          &lt;td&gt;\mathbf{x})$$&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;Output: \(\hat{y}_k = \frac{e^{z_k}}{\sum_{j=1}^K e^{z_j}}\) where \(\sum_{k=1}^K \hat{y}_k = 1\)&lt;/li&gt;
  &lt;li&gt;Loss: Categorical cross-entropy \(\mathcal{L} = -\sum_{k=1}^K y_k \log \hat{y}_k\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The softmax function has elegant properties: it’s differentiable, outputs form a probability distribution, and it “softens” the argmax operation (hence the name), allowing gradient-based learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Regression&lt;/strong&gt; (\(y \in \mathbb{R}\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;One or more output neurons with linear (identity) activation&lt;/li&gt;
  &lt;li&gt;Output: \(\hat{y} = z\) (no activation function)&lt;/li&gt;
  &lt;li&gt;Loss: Mean Squared Error \(\mathcal{L} = \frac{1}{2}(y - \hat{y})^2\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;forward-propagation-the-complete-picture&quot;&gt;Forward Propagation: The Complete Picture&lt;/h3&gt;

&lt;p&gt;Given input \(\mathbf{x} \in \mathbb{R}^{n_0}\), forward propagation computes:&lt;/p&gt;

\[\begin{align}
\mathbf{a}^{[0]} &amp;amp;= \mathbf{x} \quad \text{(initialize with input)} \\
\\
\text{For } l &amp;amp;= 1 \text{ to } L: \\
\mathbf{z}^{[l]} &amp;amp;= \mathbf{W}^{[l]} \mathbf{a}^{[l-1]} + \mathbf{b}^{[l]} \quad \text{(affine transformation)} \\
\mathbf{a}^{[l]} &amp;amp;= \sigma^{[l]}(\mathbf{z}^{[l]}) \quad \text{(nonlinear activation)} \\
\\
\hat{\mathbf{y}} &amp;amp;= \mathbf{a}^{[L]} \quad \text{(final output)}
\end{align}\]

&lt;p&gt;This sequential computation builds increasingly complex representations. Each layer learns features at a different level of abstraction, with the composition of layers enabling the network to represent highly complex functions.&lt;/p&gt;

&lt;h3 id=&quot;parameter-count-and-complexity&quot;&gt;Parameter Count and Complexity&lt;/h3&gt;

&lt;p&gt;The total number of learnable parameters is:&lt;/p&gt;

\[\text{Parameters} = \sum_{l=1}^{L} (n_l \times n_{l-1} + n_l) = \sum_{l=1}^{L} n_l(n_{l-1} + 1)\]

&lt;p&gt;For a concrete example with architecture [784, 128, 64, 10]:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Layer 1: \(128 \times 784 + 128 = 100,480\) parameters&lt;/li&gt;
  &lt;li&gt;Layer 2: \(64 \times 128 + 64 = 8,256\) parameters&lt;/li&gt;
  &lt;li&gt;Layer 3: \(10 \times 64 + 10 = 650\) parameters&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Total&lt;/strong&gt;: \(109,386\) parameters&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This parameter count grows quadratically with layer width but only linearly with depth, explaining why deep narrow networks are often more parameter-efficient than shallow wide ones for similar representational capacity.&lt;/p&gt;

&lt;h3 id=&quot;the-universal-approximation-theorem&quot;&gt;The Universal Approximation Theorem&lt;/h3&gt;

&lt;div class=&quot;textbook-theorem&quot;&gt;
  &lt;p&gt;&lt;strong&gt;Theorem&lt;/strong&gt; (Cybenko 1989, Hornik et al. 1989): Let \(\sigma\) be a non-constant, bounded, monotonically-increasing continuous function (e.g., sigmoid). Then for any continuous function \(g\) on a compact subset \(K \subset \mathbb{R}^n\), any \(\epsilon &amp;gt; 0\), and any probability measure \(\mu\) on \(K\), there exists a one-hidden-layer neural network \(f\) such that:&lt;/p&gt;

  &lt;p&gt;\(\int_K |f(\mathbf{x}) - g(\mathbf{x})| d\mu(\mathbf{x}) &amp;lt; \epsilon\)&lt;/p&gt;
&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;What This Means&lt;/strong&gt;: Neural networks can approximate any continuous function arbitrarily well. This is remarkable—it means neural networks are universal function approximators, capable of representing any relationship we might want to learn.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1D experimental intuition.&lt;/strong&gt; On the same wavy cloud of points: a low-capacity / shallow net fits poorly; with enough width/depth and training, the prediction curve hugs the data almost perfectly.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_shallow_poor_fit.jpg&quot; alt=&quot;Shallow / low capacity: poor fit&quot; /&gt;
&lt;em&gt;Figure: Low capacity — the prediction curve (pink) misses the data. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_deeper_good_fit.jpg&quot; alt=&quot;Deeper / wider: good fit&quot; /&gt;
&lt;em&gt;Figure: After scaling the architecture and training — near-perfect fit. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_predictions_complex_curve.jpg&quot; alt=&quot;Predictions on a complex curve&quot; /&gt;
&lt;em&gt;Figure: Forward passes at many \(x\) “draw” the whole function. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/nn_prediction_neuron_activation.jpg&quot; alt=&quot;Different neurons light up by region&quot; /&gt;
&lt;em&gt;Figure: For each \(x\), a different subset of hidden neurons activates — partitioning input space. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important Caveats&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Existence ≠ Learnability&lt;/strong&gt;: The theorem guarantees a solution exists but doesn’t tell us how to find it via gradient descent&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Width Requirements&lt;/strong&gt;: May need exponentially many neurons (in input dimension or precision \(1/\epsilon\))&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Depth Efficiency&lt;/strong&gt;: Deeper networks can often achieve the same approximation with exponentially fewer parameters&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;No Guidance on Architecture&lt;/strong&gt;: Doesn’t tell us what activation functions, initializations, or learning rates to use&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The theorem explains &lt;em&gt;why&lt;/em&gt; neural networks work in principle, but practical deep learning success comes from additional insights about depth, architecture, optimization, and regularization that the theorem doesn’t address.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;To solidify understanding of neural network architecture, let’s trace through a concrete example step by step, watching how information transforms as it flows through layers.&lt;/p&gt;

&lt;h3 id=&quot;example-3-layer-network-for-mnist&quot;&gt;Example: 3-Layer Network for MNIST&lt;/h3&gt;

&lt;p&gt;Consider a network designed to classify handwritten digits (28×28 grayscale images into 10 classes):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Architecture&lt;/strong&gt;: [784 → 128 → 64 → 10]&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Input&lt;/strong&gt;: 784 pixels (28×28 flattened)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hidden Layer 1&lt;/strong&gt;: 128 neurons with ReLU&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hidden Layer 2&lt;/strong&gt;: 64 neurons with ReLU&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Output Layer&lt;/strong&gt;: 10 neurons with softmax&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;information-flow-a-detailed-walkthrough&quot;&gt;Information Flow: A Detailed Walkthrough&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Input (Layer 0)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We receive a 28×28 image of the digit “3”. Flattened into a vector:
\(\mathbf{a}^{[0]} = [0.2, 0.1, 0.0, 0.8, 0.9, \ldots] \in \mathbb{R}^{784}\)&lt;/p&gt;

&lt;p&gt;Each value represents a pixel intensity (0=black, 1=white). The network sees this as a point in 784-dimensional space.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: First Hidden Layer (Layer 1)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This layer has 128 neurons, each looking for different patterns:&lt;/p&gt;

\[\mathbf{z}^{[1]} = \mathbf{W}^{[1]} \mathbf{a}^{[0]} + \mathbf{b}^{[1]}\]

&lt;p&gt;Where \(\mathbf{W}^{[1]} \in \mathbb{R}^{128 \times 784}\) and \(\mathbf{b}^{[1]} \in \mathbb{R}^{128}\).&lt;/p&gt;

&lt;p&gt;Each of the 128 neurons computes:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Neuron 1 might activate for vertical edges in the top-left&lt;/li&gt;
  &lt;li&gt;Neuron 2 might activate for circular curves&lt;/li&gt;
  &lt;li&gt;Neuron 3 might activate for diagonal strokes&lt;/li&gt;
  &lt;li&gt;… and so on&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After ReLU activation: \(\mathbf{a}^{[1]} = \max(0, \mathbf{z}^{[1]}) \in \mathbb{R}^{128}\)&lt;/p&gt;

&lt;p&gt;Some neurons fire strongly (values close to their maximum), others don’t fire at all (zeroed out by ReLU). The network has transformed the raw pixel representation into a feature representation: “this image has strong vertical edges, moderate curves, weak horizontal strokes.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Second Hidden Layer (Layer 2)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This layer combines the low-level features from Layer 1 into higher-level concepts:&lt;/p&gt;

\[\mathbf{z}^{[2]} = \mathbf{W}^{[2]} \mathbf{a}^{[1]} + \mathbf{b}^{[2]}\]

&lt;p&gt;Where \(\mathbf{W}^{[2]} \in \mathbb{R}^{64 \times 128}\).&lt;/p&gt;

&lt;p&gt;These 64 neurons might recognize:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Neuron 1: “top loop” (combining curves and top-positioned edges)&lt;/li&gt;
  &lt;li&gt;Neuron 2: “bottom loop” (different curve combinations)&lt;/li&gt;
  &lt;li&gt;Neuron 3: “vertical stroke” (combining vertical edges)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;After ReLU: \(\mathbf{a}^{[2]} = \max(0, \mathbf{z}^{[2]}) \in \mathbb{R}^{64}\)&lt;/p&gt;

&lt;p&gt;The representation is now even more abstract: “this image has a top loop and a bottom loop, characteristic of digits like 3, 8, or possibly 0.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Output Layer (Layer 3)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The final layer makes the classification decision:&lt;/p&gt;

\[\mathbf{z}^{[3]} = \mathbf{W}^{[3]} \mathbf{a}^{[2]} + \mathbf{b}^{[3]} \in \mathbb{R}^{10}\]

&lt;p&gt;where \(\mathbf{W}^{[3]} \in \mathbb{R}^{10 \times 64}\).&lt;/p&gt;

&lt;p&gt;This gives raw scores (logits) for each digit. To convert to probabilities:&lt;/p&gt;

\[\hat{\mathbf{y}} = \text{softmax}(\mathbf{z}^{[3]})\]

&lt;p&gt;Resulting in something like:
\(\hat{\mathbf{y}} = [0.01, 0.02, 0.05, 0.82, 0.03, 0.01, 0.02, 0.02, 0.01, 0.01]\)&lt;/p&gt;

&lt;p&gt;The network is 82% confident this is a “3” (index 3), with some probability mass on other digits that share similar features.&lt;/p&gt;

&lt;h3 id=&quot;why-this-layered-structure-works&quot;&gt;Why This Layered Structure Works&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Hierarchical Feature Learning&lt;/strong&gt;: Layer 1 learned edges and curves. Layer 2 combined these into digit parts. Layer 3 combined parts into complete digit predictions. This hierarchy emerges automatically from training—we never explicitly told the network to detect edges first!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Distributed Representation&lt;/strong&gt;: The digit “3” isn’t represented by a single neuron but by a pattern of activation across all 64 neurons in Layer 2. This makes the representation robust (losing a few neurons doesn’t destroy the concept) and efficient (the same features help recognize multiple digits).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Dimensionality Reduction&lt;/strong&gt;: We started with 784 dimensions and compressed through 128 → 64 → 10. Each reduction forced the network to extract increasingly essential information, discarding noise and irrelevant details while preserving discriminative features.&lt;/p&gt;

&lt;h3 id=&quot;intuition-why-depth-beats-width&quot;&gt;Intuition: Why Depth Beats Width&lt;/h3&gt;

&lt;p&gt;Consider two alternative networks for the same task:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Shallow-Wide&lt;/strong&gt;: [784 → 4096 → 10]&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Single massive hidden layer with 4096 neurons&lt;/li&gt;
  &lt;li&gt;Total parameters: ~3.2M&lt;/li&gt;
  &lt;li&gt;Each neuron must learn complete pattern from raw pixels&lt;/li&gt;
  &lt;li&gt;No explicit feature hierarchy&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Deep-Narrow&lt;/strong&gt;: [784 → 128 → 64 → 32 → 10]&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Four smaller hidden layers&lt;/li&gt;
  &lt;li&gt;Total parameters: ~110K (29× fewer!)&lt;/li&gt;
  &lt;li&gt;Natural feature hierarchy emerges&lt;/li&gt;
  &lt;li&gt;Better generalization, easier to train&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The deep network wins because most real-world patterns are compositional. Faces are composed of eyes, noses, mouths (not random pixel patterns). Sentences are composed of phrases, composed of words, composed of letters. Deep networks naturally capture this compositional structure through their layered architecture.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/793200140509765&quot;&gt;Neural network intuition (Perceptron → Deep Learning)&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/720970114372332&quot;&gt;Neural nets as function approximators&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. A layer is an affine map followed by a nonlinearity, the formula this lesson writes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=CqOfi41LfDw&quot;&gt;The Essential Main Ideas of Neural Networks&lt;/a&gt; — StatQuest with Josh Starmer, English. Walks one hidden layer with every matrix shape visible.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 4&lt;/td&gt;
          &lt;td&gt;Introduction to Neural Networks](https://www.youtube.com/watch?v=d14TUNcbn1k) — Stanford University School of Engineering, English. States the same layer equation in lecture form, including why composition is the point of depth.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02-01 The Perceptron and Artificial Neurons</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_01_Perceptron_and_Neurons/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_01_Perceptron_and_Neurons</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;In 1969, Marvin Minsky and Seymour Papert proved that a single perceptron can never solve the humble 2-bit XOR gate, triggering the first AI winter. Understanding why a single hyperplane fails on XOR—and how adding just one hidden layer resolves it—is the foundational rite of passage in neural network theory.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-geometry-of-the-perceptron&quot;&gt;Key ideas: Geometry of the Perceptron&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hyperplane Decision Boundary&lt;/strong&gt;: The equation \(\mathbf{w}^\top \mathbf{x} + b = 0\) defines a flat hyperplane with normal vector \(\mathbf{w}\) pointing into the positive half-space and signed distance \(-b / \|\mathbf{w}\|\) from the origin.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Perceptron Convergence Theorem&lt;/strong&gt;: Guarantees that if a dataset is strictly linearly separable with margin \(\gamma &amp;gt; 0\), the classical mistake-driven update \(\mathbf{w} \leftarrow \mathbf{w} + y\mathbf{x}\) terminates in at most \((R/\gamma)^2\) mistakes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Linear Separability Ceiling (The XOR Barrier)&lt;/strong&gt;: Any function whose positive and negative points cannot be separated by a single flat cut (like XOR: \((0,0),(1,1) \to 0\) vs. \((0,1),(1,0) \to 1\)) is impossible for a single neuron.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;From Step Functions to Smooth Neurons&lt;/strong&gt;: Replacing the zero-derivative Heaviside step with smooth activations (sigmoid, tanh, ReLU) makes neurons differentiable so multi-layer networks can train via gradient descent.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-two-mistake-driven-perceptron-updates-by-hand&quot;&gt;Worked example: Two Mistake-Driven Perceptron Updates by Hand&lt;/h3&gt;

&lt;p&gt;Train a perceptron with initial weights \(\mathbf{w}_0 = [0, 0]^\top\), bias \(b_0 = 0\), and learning rate \(\eta = 1\) on two labeled examples (labels \(y \in \{-1, +1\}\)):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Example 1: \(\mathbf{x}_1 = [2, 1]^\top, y_1 = +1\)&lt;/li&gt;
  &lt;li&gt;Example 2: \(\mathbf{x}_2 = [1, -2]^\top, y_2 = -1\)
Prediction rule: \(\hat{y} = +1\) if \(\mathbf{w}^\top\mathbf{x} + b &amp;gt; 0\), else \(-1\).&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Step 1 (Evaluate Example 1)&lt;/strong&gt;:
\(z_1 = \mathbf{w}_0^\top \mathbf{x}_1 + b_0 = 0(2) + 0(1) + 0 = 0 \implies \hat{y}_1 = -1 \neq +1\text{ (mistake!)}\)
Update weights and bias:
\(\mathbf{w}_1 = \mathbf{w}_0 + y_1\mathbf{x}_1 = \begin{bmatrix} 0 \\ 0 \end{bmatrix} + (+1)\begin{bmatrix} 2 \\ 1 \end{bmatrix} = \begin{bmatrix} 2 \\ 1 \end{bmatrix}, \quad b_1 = 0 + (+1) = 1\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step 2 (Evaluate Example 2 with \(\mathbf{w}_1, b_1\))&lt;/strong&gt;:
\(z_2 = 2(1) + 1(-2) + 1 = 1 &amp;gt; 0 \implies \hat{y}_2 = +1 \neq -1\text{ (mistake!)}\)
Update weights and bias:
\(\mathbf{w}_2 = \mathbf{w}_1 + y_2\mathbf{x}_2 = \begin{bmatrix} 2 \\ 1 \end{bmatrix} + (-1)\begin{bmatrix} 1 \\ -2 \end{bmatrix} = \begin{bmatrix} 1 \\ 3 \end{bmatrix}, \quad b_2 = 1 + (-1) = 0\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify Both Examples Now Classify Correctly&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Example 1: \(\mathbf{w}_2^\top\mathbf{x}_1 + b_2 = 1(2) + 3(1) + 0 = +5 &amp;gt; 0 \implies \hat{y}_1 = +1\) (correct!).&lt;/li&gt;
      &lt;li&gt;Example 2: \(\mathbf{w}_2^\top\mathbf{x}_2 + b_2 = 1(1) + 3(-2) + 0 = -5 \leq 0 \implies \hat{y}_2 = -1\) (correct!).
In just two updates, the hyperplane \(x_1 + 3x_2 = 0\) separates both points with wide margin.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;the-perceptron-and-artificial-neurons&quot;&gt;The Perceptron and Artificial Neurons&lt;/h1&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Perceptron_moj.png/400px-Perceptron_moj.png&quot; alt=&quot;Perceptron Diagram&quot; /&gt;
&lt;em&gt;Hình ảnh: Sơ đồ cấu trúc của một Perceptron. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;The journey into deep learning begins with understanding its most fundamental building block: the artificial neuron. While modern deep learning has evolved far beyond the simple perceptron introduced by Frank Rosenblatt in 1958, comprehending this historical starting point is essential for grasping why contemporary neural networks are designed the way they are. The perceptron represents humanity’s first attempt to create a machine that could learn from examples, mimicking in an extremely simplified way how biological neurons process information.&lt;/p&gt;

&lt;p&gt;The perceptron is, at its core, a binary classifier. It takes multiple numerical inputs, combines them using learned weights, and produces a single binary output indicating which of two classes the input belongs to. What makes this seemingly simple mechanism profound is that it can learn these weights automatically from examples, adjusting them iteratively until it correctly classifies the training data. This learning capability, primitive as it may seem compared to modern standards, was revolutionary in its time and laid the conceptual groundwork for all subsequent developments in neural networks.&lt;/p&gt;

&lt;p&gt;Understanding the perceptron is crucial because it introduces several concepts that persist throughout deep learning. The notion of weighted inputs captures the idea that different features contribute differently to a decision. The bias term allows the decision boundary to shift away from the origin. The learning rule demonstrates how we can adjust parameters based on errors. Perhaps most importantly, the perceptron’s fundamental limitation—its inability to solve non-linearly separable problems like XOR—directly motivates the need for multiple layers and the deep architectures that define modern deep learning.&lt;/p&gt;

&lt;p&gt;The transition from the perceptron to modern artificial neurons involves replacing the harsh step function with smooth, differentiable activation functions. This seemingly small change has profound implications. Smooth activation functions enable gradient-based learning through backpropagation, allowing us to train networks with many layers. They introduce the nonlinearity necessary for neural networks to approximate complex functions. The choice of activation function affects everything from training speed to the network’s ability to represent certain types of patterns, making this one of the most important architectural decisions in deep learning.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/1/10/Blausen_0657_MultipolarNeuron.png/500px-Blausen_0657_MultipolarNeuron.png&quot; alt=&quot;Biological vs Artificial Neuron&quot; /&gt;
&lt;em&gt;Hình ảnh: Neuron sinh học (trái) đã truyền cảm hứng cho neuron nhân tạo. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The perceptron performs a remarkably simple computation, yet understanding its mathematical formulation reveals deep insights about linear classifiers and decision boundaries. Given an input vector \(\mathbf{x} = (x_1, x_2, \ldots, x_n)\) where each \(x_i\) represents a feature, and a corresponding weight vector \(\mathbf{w} = (w_1, w_2, \ldots, w_n)\), the perceptron first computes a weighted sum:&lt;/p&gt;

\[z = \sum_{i=1}^{n} w_i x_i + b = \mathbf{w}^T \mathbf{x} + b\]

&lt;p&gt;This quantity \(z\), often called the pre-activation or logit, represents a linear combination of the inputs. Each weight \(w_i\) determines how strongly the corresponding input \(x_i\) influences the final decision. The bias term \(b\) provides a threshold that allows the decision boundary to be positioned optimally in the input space, independent of whether all inputs are zero.&lt;/p&gt;

&lt;p&gt;The perceptron then applies the Heaviside step function to this linear combination to produce a binary output:&lt;/p&gt;

\[y = H(z) = \begin{cases} 
1 &amp;amp; \text{if } z \geq 0 \\
0 &amp;amp; \text{if } z &amp;lt; 0
\end{cases}\]

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/heaviside_step_function.jpg&quot; alt=&quot;Heaviside step function graph&quot; /&gt;
&lt;em&gt;Figure: Heaviside step \(H(x)\) — the output is only \(0\) or \(1\). (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This step function creates a sharp decision boundary. Everything on one side gets classified as positive (1), everything on the other side as negative (0). The geometric interpretation of this is elegant: the weights define a hyperplane in the input space according to the equation \(\mathbf{w}^T \mathbf{x} + b = 0\). Points are classified based on which side of this hyperplane they fall on.&lt;/p&gt;

&lt;p&gt;The weight vector \(\mathbf{w}\) is perpendicular (orthogonal) to the decision hyperplane. This is a fundamental geometric fact: if two points \(\mathbf{x}_1\) and \(\mathbf{x}_2\) lie on the hyperplane, then \(\mathbf{w}^T(\mathbf{x}_1 - \mathbf{x}_2) = 0\), meaning \(\mathbf{w}\) is orthogonal to any vector in the hyperplane. The magnitude of \(\mathbf{w}\) determines how quickly the activation \(z\) changes as we move perpendicular to the hyperplane, while the bias \(b\) controls the hyperplane’s distance from the origin along the direction of \(\mathbf{w}\).&lt;/p&gt;

&lt;p&gt;The perceptron learning algorithm provides a simple yet elegant way to find appropriate weights when the data is linearly separable. Starting from initial weights (often zeros or small random values), the algorithm processes each training example \((\mathbf{x}_i, y_i)\). When it makes a correct prediction, it does nothing. When it misclassifies, it adjusts the weights according to:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; $$\mathbf{w} \leftarrow \mathbf{w} + \eta (y_i - \hat{y}_i) \mathbf{x}_i$$
 $$b \leftarrow b + \eta (y_i - \hat{y}_i)$$
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Here \(\eta\) is the learning rate controlling step size, and \((y_i - \hat{y}_i)\) is the error. If the true label is 1 but we predicted 0, the error is +1, and we move the weights in the direction of \(\mathbf{x}_i\), making this input more likely to be classified as 1 in the future. If we predicted 1 but the truth is 0, we move away from \(\mathbf{x}_i\). This geometric intuition—moving the decision boundary toward correctly classified points and away from incorrectly classified ones—underlies much of machine learning.&lt;/p&gt;

&lt;p&gt;The Perceptron Convergence Theorem guarantees that if the training data is linearly separable, this algorithm will find a separating hyperplane in a finite number of steps. However, this theorem also reveals the perceptron’s fundamental limitation: it cannot solve problems where the classes are not linearly separable. The classic example is the XOR problem, where the positive and negative classes are interleaved in such a way that no single straight line (or hyperplane in higher dimensions) can separate them. This limitation sparked the first “AI winter” in the 1970s when it became clear that single-layer perceptrons could not solve many practical problems.&lt;/p&gt;

&lt;p&gt;Modern artificial neurons address these limitations while preserving the core insight of weighted summation. Instead of the step function, we apply a smooth activation function \(\sigma\):&lt;/p&gt;

\[a = \sigma\left(\sum_{i=1}^{n} w_i x_i + b\right) = \sigma(\mathbf{w}^T \mathbf{x} + b)\]

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/6/6f/Gjl-t%28x%29.svg/500px-Gjl-t%28x%29.svg.png&quot; alt=&quot;Activation Functions&quot; /&gt;
&lt;em&gt;Hình ảnh: Các hàm kích hoạt phổ biến (Sigmoid, Tanh, ReLU). Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The choice of \(\sigma\) dramatically affects the neuron’s behavior. The sigmoid function \(\sigma(z) = \frac{1}{1+e^{-z}}\) smoothly transitions between 0 and 1, providing a probabilistic interpretation and crucially, being differentiable everywhere. The hyperbolic tangent \(\tanh(z)\) ranges from -1 to 1 and is zero-centered, which often improves gradient flow. The Rectified Linear Unit (ReLU), defined as \(\max(0, z)\), has become dominant in modern deep learning because it’s computationally efficient, doesn’t saturate for positive inputs (avoiding vanishing gradients), and introduces useful sparsity where negative-activated neurons output exactly zero.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;h3 id=&quot;31-geometric-intuition-from-1d-to-3d&quot;&gt;3.1. Geometric intuition: from 1D to 3D&lt;/h3&gt;

&lt;p&gt;Before returning to AND/XOR, picture the perceptron as a &lt;strong&gt;decision boundary&lt;/strong&gt; in input space.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;One dimension (e.g. temperature).&lt;/strong&gt; A neuron takes a scalar \(x\) (°C). Weight and bias place a threshold — say at \(20\): Inactive on one side, Active on the other. The unit only flips based on which side of that threshold you are on.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/perceptron_1d_threshold.jpg&quot; alt=&quot;1D boundary: Inactive vs Active&quot; /&gt;
&lt;em&gt;Figure: A 1D perceptron places a boundary (e.g. at 20) on the Input Space axis. (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Flipping the &lt;strong&gt;sign of the weight&lt;/strong&gt; reverses the active region. For example, \(\hat{y} = H(-x + 20)\) is active when \(x\) is small (Active to the left of 20).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/perceptron_1d_weight_sign.jpg&quot; alt=&quot;Flipping the boundary with the weight sign&quot; /&gt;
&lt;em&gt;Figure: \(\hat{y}=H(-x+20)\) — a negative weight flips Active/Inactive. (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Two dimensions (e.g. Temp + Humidity).&lt;/strong&gt; Two features → the decision boundary is a &lt;strong&gt;line&lt;/strong&gt;. Class points lie on opposite sides of that line (yellow in the figure below).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/perceptron_2d_decision_boundary.jpg&quot; alt=&quot;2D decision boundary&quot; /&gt;
&lt;em&gt;Figure: Two-input perceptron (Temp, Humidity) and a linear separator in the plane. (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In compact vector/matrix form:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/perceptron_vector_form.jpg&quot; alt=&quot;Vector form of the perceptron&quot; /&gt;
&lt;em&gt;Figure: \(\hat{y}=H(w_1x_1+w_2x_2+b)=H(\mathbf{W}\mathbf{x}+b)\). (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Three or more dimensions.&lt;/strong&gt; Adding a feature (e.g. Wind Speed) makes the boundary a &lt;strong&gt;hyperplane&lt;/strong&gt; in input space:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/perceptron_3d_hyperplane.jpg&quot; alt=&quot;3D decision hyperplane&quot; /&gt;
&lt;em&gt;Figure: Three inputs (Temp, Humidity, Wind Speed) and a classifying hyperplane in 3D. (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/linearly_separable.jpg&quot; alt=&quot;Linearly separable data&quot; /&gt;
&lt;em&gt;Figure: Two *linearly separable&lt;/em&gt; classes — one straight line is enough. When data is not linearly separable, we need nonlinearity and multiple layers. (Illustration from an introductory neural-network video)*&lt;/p&gt;

&lt;h3 id=&quot;32-logic-examples-and-and-xor&quot;&gt;3.2. Logic examples: AND and XOR&lt;/h3&gt;

&lt;p&gt;To truly understand how a perceptron works, let’s walk through a concrete example that reveals both its power and limitations. Consider the simple logical AND function, which outputs 1 only when both inputs are 1. While this seems trivial, it was groundbreaking that a machine could learn this relationship from examples alone.&lt;/p&gt;

&lt;p&gt;Suppose we want a perceptron to learn AND using these examples: (0,0)→0, (0,1)→0, (1,0)→0, (1,1)→1. Let’s initialize with \(w_1 = 0, w_2 = 0, b = 0\) and use learning rate \(\eta = 1\). For the first example (0,0) with label 0, our prediction is \(H(0 \cdot 0 + 0 \cdot 0 + 0) = H(0) = 1\), which is wrong! The error is \(0 - 1 = -1\), so we update: \(w_1 \leftarrow 0 + 1 \cdot (-1) \cdot 0 = 0\), \(w_2 \leftarrow 0\), \(b \leftarrow 0 + 1 \cdot (-1) = -1\). Now we have a bias of -1, which provides a threshold.&lt;/p&gt;

&lt;p&gt;Continuing this process through the training examples, the perceptron eventually converges to weights like \(w_1 = 1, w_2 = 1, b = -1.5\). Let’s verify this works: For input (1,1), we get \(z = 1 \cdot 1 + 1 \cdot 1 - 1.5 = 0.5\), so \(H(0.5) = 1\) ✓. For (1,0), we get \(z = 1 \cdot 1 + 1 \cdot 0 - 1.5 = -0.5\), so \(H(-0.5) = 0\) ✓. The perceptron has learned to require both inputs to exceed the threshold of 1.5 combined.&lt;/p&gt;

&lt;p&gt;Now consider why the XOR problem is impossible for a single perceptron. XOR outputs 1 when inputs differ: (0,0)→0, (0,1)→1, (1,0)→1, (1,1)→0. If you plot these points in 2D space, you’ll see that the positive examples (0,1) and (1,0) are diagonally opposite, with negative examples (0,0) and (1,1) at the other diagonal. No single straight line can separate these classes—you would need a nonlinear boundary, like a curve or multiple line segments. This geometric impossibility reveals a fundamental computational limitation: single-layer linear models cannot capture certain logical relationships.&lt;/p&gt;

&lt;p&gt;This limitation drove the development of multi-layer networks. If we stack two perceptrons feeding into a third, we can solve XOR. The first layer can learn to detect \(x_1\) OR \(x_2\), and \(x_1\) AND \(x_2\), and the second layer can learn “OR but not AND,” which is exactly XOR. This demonstrates a crucial principle: depth (multiple layers) enables learning increasingly complex decision boundaries. Each additional layer can combine features from previous layers in new ways, exponentially expanding the space of representable functions.&lt;/p&gt;

&lt;p&gt;The biological inspiration, while imperfect, provides useful intuition. Real neurons in the brain receive signals through dendrites, integrate these signals in the cell body (soma), and fire an action potential down the axon if the integrated signal exceeds a threshold. The synapse strengths correspond to our weights—stronger synapses contribute more to whether the neuron fires. However, we must be careful not to take this analogy too far. Biological neurons are vastly more complex than artificial ones, with intricate biochemistry, complex dendritic computations, and temporal dynamics that our simple weighted-sum model doesn’t capture. Artificial neurons are engineering tools inspired by biology, not accurate models of brain function.&lt;/p&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Let’s implement both a classical perceptron and a modern neuron to understand their similarities and differences. We’ll start with a clean NumPy implementation that makes the learning process transparent:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;numpy&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Classical Perceptron with step function activation&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Initialize perceptron with random small weights.
        
        Why small random weights? We need to break symmetry - if all weights
        start equal, all neurons learn the same features. Small values ensure
        we start in a region where gradients (for smooth activations) are meaningful.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Start with zeros for classical perceptron (simple and works for linearly separable data)
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zeros&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;errors_&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Track errors per epoch for diagnostics
&lt;/span&gt;    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;activation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Heaviside step function: outputs 1 if z &amp;gt;= 0, else 0
        
        This creates a sharp decision boundary. Everything above the threshold
        gets classified as 1, everything below as 0. This all-or-nothing nature
        is both the perceptron&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s strength (clear decisions) and weakness 
        (not differentiable, can&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;t use gradient descent).
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;where&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Make predictions for input X.
        
        The computation X @ weights is a batch matrix-vector product.
        For each example (row of X), we compute the dot product with weights,
        add bias, and apply activation. This vectorized approach is orders of
        magnitude faster than looping through examples.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;activation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Train perceptron using the perceptron learning rule.
        
        Why does this work? The perceptron learning rule has a beautiful
        geometric interpretation: when we misclassify a point, we adjust
        the decision boundary to move toward that point (if it should be
        positive) or away from it (if it should be negative). For linearly
        separable data, this process is guaranteed to converge.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;errors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
                &lt;span class=&quot;c1&quot;&gt;# Compute prediction
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dot&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;
                &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;activation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                
                &lt;span class=&quot;c1&quot;&gt;# Update only if prediction is wrong
&lt;/span&gt;                &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_pred&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                    &lt;span class=&quot;c1&quot;&gt;# The update rule: w ← w + η(y - ŷ)x
&lt;/span&gt;                    &lt;span class=&quot;c1&quot;&gt;# When y=1, ŷ=0: error=+1, move toward x (increase dot product)
&lt;/span&gt;                    &lt;span class=&quot;c1&quot;&gt;# When y=0, ŷ=1: error=-1, move away from x (decrease dot product)
&lt;/span&gt;                    &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x_i&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;
                    &lt;span class=&quot;n&quot;&gt;errors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;errors_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;errors&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            
            &lt;span class=&quot;c1&quot;&gt;# Early stopping if converged
&lt;/span&gt;            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;errors&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Converged at iteration &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;iteration&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;break&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate learning the AND function
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training Perceptron on AND gate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_and&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_and&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_and&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_and&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Learned weights: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Learned bias: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_and&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True labels:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_and&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Decision boundary equation: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;*x1 + &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weights&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;*x2 + &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bias&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; = 0&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Demonstrate XOR impossibility
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Attempting to learn XOR (will fail!)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;np&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;array&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;perceptron_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Perceptron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n_features&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;learning_rate&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n_iterations&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;perceptron_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;predictions_xor&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;perceptron_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;predict&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Predictions: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions_xor&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;True labels:  &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y_xor&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Errors remaining: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;perceptron_xor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;errors_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Note: Perceptron cannot solve XOR because it&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s not linearly separable!&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Now let’s implement a modern neuron with smooth activation functions that enable gradient-based learning:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;ModernNeuron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Modern artificial neuron with smooth activation function.
    
    The key difference from the perceptron is the activation function.
    Instead of a step function that&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;s either 0 or 1, we use smooth functions
    that can output any value in a range and, crucially, are differentiable.
    This differentiability is what enables backpropagation and gradient descent.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ModernNeuron&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Linear layer: y = Wx + b
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# PyTorch initializes weights using Kaiming uniform by default,
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# which is designed for ReLU activations
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;linear&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Choose activation function
&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Each has different properties and use cases
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# ReLU: max(0, z) - most common, prevents vanishing gradients
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Sigmoid: 1/(1+e^(-z)) - outputs [0,1], good for probabilities
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Tanh: (e^z - e^(-z))/(e^z + e^(-z)) - outputs [-1,1], zero-centered
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;# Linear: f(z) = z - for regression
&lt;/span&gt;            &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;activation&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Identity&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
        Forward pass through the neuron.
        
        The computation is the same as perceptron (weighted sum + bias)
        but we apply a smooth activation function. This smoothness is critical:
        it means small changes in weights cause small changes in output,
        enabling gradient descent to work effectively.
        &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Linear combination: z = w^T x + b
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;activation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Apply nonlinear activation
&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Demonstrate that modern neurons can learn XOR with multiple layers
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TwoLayerNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    Two-layer network that CAN solve XOR.
    
    This demonstrates why depth matters: the first layer creates a new
    representation space where XOR becomes linearly separable, and the
    second layer can then separate it with a linear boundary.
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;TwoLayerNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# First layer creates nonlinear features
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;h&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;hidden&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Second layer combines these features
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train on XOR
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training 2-Layer Network on XOR&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;X_xor_torch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;y_xor_torch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;1.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;],&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;TwoLayerNetwork&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;input_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;hidden_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;BCELoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Binary Cross-Entropy
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.01&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training loop
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;5000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# Forward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_xor_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;c1&quot;&gt;# Backward pass
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;d&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Test the learned model
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;final_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;binary_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;final_predictions&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;0.5&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Final Predictions (probabilities):&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zip&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;X_xor_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;final_predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y_xor_torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)):&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Input &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;inp&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;numpy&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; → Pred: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, True: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;
          &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Classified as: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;binary_predictions&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;i&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;].&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Success! The network learned XOR, something a single perceptron cannot do.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;This demonstrates why depth (multiple layers) is fundamental to neural networks.&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Let’s also understand how different activation functions shape neuron behavior by examining their effects on the same input:&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Compare activation functions
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;linspace&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;relu_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;sigmoid_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;tanh_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;z&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Activation Function Characteristics&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;60&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;For z = -2.0:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ReLU:    &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (zero for negative)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Sigmoid: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (near 0, but not exactly)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tanh:    &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (negative output)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;For z = 2.0:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  ReLU:    &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (linear for positive)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Sigmoid: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sigmoid&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (approaching 1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  Tanh:    &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tanh&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;tensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;2.0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  (approaching 1)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Key observations:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - ReLU: Outputs exactly zero for negative inputs, creates sparsity&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Sigmoid: Always positive, good for probabilities but can saturate&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;  - Tanh: Zero-centered (outputs can be negative), better gradient flow than sigmoid&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The reason ReLU has become dominant deserves deeper explanation. When using sigmoid or tanh, the gradient becomes very small when the input is large in magnitude (positive or negative). This “saturation” means that during backpropagation, gradients diminish as they propagate backward through layers, making it difficult to train deep networks. ReLU doesn’t saturate for positive inputs—its gradient is exactly 1—allowing gradients to flow unchanged through many layers. This property enabled the training of much deeper networks and was crucial to the deep learning revolution of the 2010s.&lt;/p&gt;

&lt;p&gt;However, ReLU introduces its own challenge: the “dying ReLU” problem. If a neuron’s input is always negative during training, its output is always zero, and its gradient is also always zero, meaning it never updates and effectively dies. This can happen with poor initialization or excessively high learning rates. Variants like Leaky ReLU (\(\max(\alpha z, z)\) with \(\alpha \approx 0.01\)) address this by allowing small negative values, ensuring gradients never completely vanish.&lt;/p&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Understanding the perceptron and artificial neurons properly requires seeing how they connect to the broader landscape of machine learning and deep learning. The perceptron is essentially a simplified form of logistic regression when we replace the step function with a sigmoid activation. In logistic regression, we model the probability of class membership as $$P(y=1&lt;/td&gt;
      &lt;td&gt;\mathbf{x}) = \sigma(\mathbf{w}^T \mathbf{x} + b)$$, which is exactly a perceptron with sigmoid activation. The connection runs deeper: logistic regression is typically trained using maximum likelihood estimation, which, for the binary case, leads to minimizing binary cross-entropy loss. This same loss function is used to train the output layer of neural networks for binary classification.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;The relationship to Support Vector Machines (SVMs) is also illuminating. Like the perceptron, SVMs find a separating hyperplane for linearly separable data. However, SVMs optimize for the maximum margin hyperplane—the one that’s as far as possible from the nearest data points of both classes. This margin maximization provides better generalization guarantees. The perceptron, in contrast, is satisfied with any separating hyperplane and doesn’t optimize for margin. Despite this theoretical advantage of SVMs, deep neural networks built from perceptron-like units have proven more practical for complex, high-dimensional problems because they can learn nonlinear features through multiple layers.&lt;/p&gt;

&lt;p&gt;The evolution from perceptron to Multi-Layer Perceptron (MLP) represents one of the most important developments in machine learning. An MLP is simply multiple layers of neurons, where each layer’s outputs become the next layer’s inputs. This stacking enables the network to learn hierarchical representations. The first layer might learn to detect simple patterns (edges in images, or common word combinations in text). The second layer combines these simple patterns into mid-level features (shapes formed by edges, or phrase meanings). Deeper layers build even higher-level concepts. This hierarchical learning is arguably the most powerful aspect of deep neural networks and is only possible because we moved beyond single-layer perceptrons.&lt;/p&gt;

&lt;p&gt;The connection to biological neural networks, while limited, provides useful intuition about why distributed representations work. In the brain, memories and concepts aren’t stored in single neurons but in patterns of activity across many neurons. Similarly, in artificial neural networks, representations are distributed across multiple neurons. This distribution provides robustness—if a few neurons fail or are dropped (as in dropout), the network can still function. It also enables the network to represent exponentially many concepts with linearly many neurons, a property called representational efficiency that partially explains deep learning’s success.&lt;/p&gt;

&lt;p&gt;Finally, understanding why we need smooth activation functions connects to the broader topic of optimization. Gradient descent, the primary algorithm for training neural networks, requires gradients. The step function’s gradient is zero almost everywhere (and undefined at the threshold), making gradient-based optimization impossible. Smooth activation functions like sigmoid, tanh, and especially ReLU provide meaningful gradients that guide the learning process. The choice of activation function affects not just whether we can compute gradients but also their magnitudes, which determines how quickly different layers learn—a consideration that becomes critical in deep networks where gradients must propagate through many layers.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://psycnet.apa.org/record/1959-09865-001&quot;&gt;“The Perceptron: A Probabilistic Model for Information Storage and Organization in the Brain” (1958)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Author&lt;/em&gt;: Frank Rosenblatt&lt;br /&gt;
This foundational paper introduced the perceptron and demonstrated that a simple artificial neuron could learn from examples. Rosenblatt showed both the theoretical convergence properties and practical implementations, building physical machines that could perform pattern recognition. The perceptron’s success sparked immense optimism about artificial intelligence, though this was later tempered by the discovery of its limitations. The paper is historically significant not just for the algorithm but for establishing the paradigm of learning from data that underlies all of modern machine learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://mitpress.mit.edu/books/perceptrons&quot;&gt;“Perceptrons: An Introduction to Computational Geometry” (1969)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Marvin Minsky and Seymour Papert&lt;br /&gt;
While not available on arXiv, this influential book rigorously analyzed the perceptron’s limitations, proving that single-layer perceptrons cannot solve problems like XOR. The analysis was so thorough and the conclusions so discouraging that it contributed to the first AI winter, with research funding for neural networks drying up for over a decade. Ironically, Minsky and Papert noted that multi-layer networks could overcome these limitations, but the lack of a training algorithm (backpropagation hadn’t been rediscovered) meant this observation didn’t prevent the field’s decline. The book remains important for understanding both the mathematical foundations of linear classifiers and the historical development of neural networks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.nature.com/articles/323533a0&quot;&gt;“Learning representations by back-propagating errors” (1986)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: David E. Rumelhart, Geoffrey E. Hinton, Ronald J. Williams&lt;br /&gt;
This paper revitalized neural network research by showing how to train multi-layer networks of perceptron-like units using backpropagation. The key insight was that by computing gradients layer by layer using the chain rule, we could assign credit (or blame) for errors to all weights in the network, not just the output layer. This enabled training networks deep enough to solve XOR and many other problems that single perceptrons couldn’t handle. The paper marked the beginning of connectionism’s resurgence and laid the groundwork for modern deep learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://proceedings.mlr.press/v15/glorot11a.html&quot;&gt;“Deep Sparse Rectifier Neural Networks” (2011)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Xavier Glorot, Antoine Bordes, Yoshua Bengio&lt;br /&gt;
This paper introduced the Rectified Linear Unit (ReLU) as a superior activation function for deep networks and empirically demonstrated its advantages over sigmoid and tanh. The authors showed that ReLU enables training deeper networks by avoiding the vanishing gradient problem that plagued earlier activation functions. ReLU neurons are also computationally efficient (just a max operation) and induce sparse representations (many neurons output exactly zero), which can be both computationally beneficial and interpretable. The adoption of ReLU was a critical factor in the deep learning revolution, enabling the training of networks with dozens or even hundreds of layers.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1502.01852&quot;&gt;“Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification” (2015)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun&lt;br /&gt;
This paper introduced both PReLU (Parametric ReLU, where the slope for negative inputs is learned) and He initialization, a weight initialization scheme specifically designed for ReLU networks. The paper demonstrated that with proper initialization, extremely deep networks (22 layers at the time, which seemed very deep) could not only train successfully but surpass human performance on ImageNet classification. The He initialization scheme, which uses variance \(\sqrt{2/n_{in}}\) instead of \(\sqrt{1/n_{in}}\) (Xavier), accounts for the fact that ReLU zeros out half the neurons on average, maintaining appropriate activation and gradient magnitudes through deep networks.&lt;/p&gt;

&lt;h2 id=&quot;common-pitfalls-and-tricks&quot;&gt;Common Pitfalls and Tricks&lt;/h2&gt;

&lt;p&gt;One of the most common mistakes when implementing neurons is initializing all weights to the same value, particularly zero. This might seem sensible—start from a “neutral” position and let the data guide learning—but it has a devastating consequence called the symmetry problem. If all neurons in a layer start with identical weights, they receive identical gradients during backpropagation and thus make identical updates. They remain identical throughout training, learning exactly the same features. A layer of 100 neurons with identical weights is no more powerful than a single neuron. Random initialization breaks this symmetry, ensuring each neuron follows a different learning trajectory and learns to detect different patterns.&lt;/p&gt;

&lt;p&gt;The scale of initialization also matters profoundly, though the reasons are subtle. If weights are too large, activations can saturate (for sigmoid/tanh) or explode (growing exponentially through layers), while gradients can also explode, causing training instability. If weights are too small, activations shrink toward zero through layers, and gradients vanish, making learning impossibly slow, especially in deep networks. The solution is to scale initial weights based on layer dimensions. Xavier initialization (\(\mathcal{N}(0, 1/n_{in})\)) works well for sigmoid and tanh, maintaining variance of activations across layers. He initialization (\(\mathcal{N}(0, 2/n_{in})\)) is specifically designed for ReLU, accounting for its property of zeroing negative inputs.&lt;/p&gt;

&lt;p&gt;The dying ReLU problem deserves special attention because it’s a common failure mode in practice. When a ReLU neuron’s input becomes negative during training and remains negative, the neuron outputs zero and has zero gradient, so it never updates. This can happen due to unlucky initialization, too-high learning rates causing large weight updates that push neurons into the negative region, or systematic biases in the data. Once a neuron dies, it’s permanently dead for that training run. To diagnose this, monitor what fraction of neurons are always outputting zero. If more than 20-30% are dead, you likely have a problem. Solutions include using Leaky ReLU (which has small gradient even for negative inputs), reducing learning rate, improving initialization, or using batch normalization (which we’ll cover later) to keep activations in reasonable ranges.&lt;/p&gt;

&lt;p&gt;A powerful technique that’s often overlooked is using small positive biases for ReLU neurons. While weights should be random, initializing biases to small positive values like 0.01 ensures that most neurons are initially active (outputting positive values) rather than starting in the zero region. This gives them a chance to learn before potentially dying. This is a simple trick that can noticeably improve training in very deep networks.&lt;/p&gt;

&lt;p&gt;Understanding the geometric interpretation of weights helps debug and interpret models. The weight vector defines a direction in input space that the neuron is “looking” along. Its magnitude determines sensitivity—larger weights mean the neuron responds more strongly to changes in that direction. In image processing, you can literally visualize what a neuron has learned by finding the input pattern that maximally activates it, often revealing that low-level neurons learn to detect oriented edges, while deeper neurons learn to detect increasingly complex patterns like textures, object parts, or eventually complete objects.&lt;/p&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;The perceptron, despite its simplicity, introduces fundamental concepts that persist throughout deep learning: the idea that we can learn from examples by adjusting weights based on errors, that weighted combinations of inputs can perform computation, and that linear models have inherent limitations necessitating nonlinearity and depth. Modern neurons extend the perceptron by using smooth, differentiable activation functions, enabling gradient-based learning through arbitrarily deep networks. The choice of activation function profoundly affects training dynamics, with ReLU emerging as the dominant choice for hidden layers due to its computational efficiency and resistance to vanishing gradients. Proper initialization breaks symmetry while maintaining appropriate activation and gradient scales, with He initialization being standard for ReLU networks. Understanding these foundational concepts deeply—not just what the formulas are but why they work and when they fail—is essential for anyone seeking to master deep learning rather than merely apply it superficially.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/793200140509765&quot;&gt;Neural network intuition (Perceptron → Deep Learning)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=i1G7PXZMnSc&quot;&gt;The Perceptron Explained&lt;/a&gt; — Alice Heiman, English. The perceptron is a weighted sum plus a threshold, which is this lesson’s opening model.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. Shows what changes when many perceptrons are stacked and the threshold becomes a smooth activation.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NkOv_k7r6no&quot;&gt;Why Non-linear Activation Functions (C1W3L07)&lt;/a&gt; — DeepLearningAI, English. Why a purely linear neuron is not enough, the step the lesson takes after the single perceptron.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>02 Introduction to Neural Networks</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter02/02_00_Introduction</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;In 1958, Frank Rosenblatt wired up the Mark I Perceptron—a room-sized machine of potentiometers and photocells that could learn to tell squares from triangles. Sixty-five years later, the exact same computational atom—weighted sum plus bias plus nonlinearity—scaled to billions of units powers every modern neural network.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-building-blocks-of-neural-networks&quot;&gt;Key ideas: Building Blocks of Neural Networks&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;The Artificial Neuron (Affine Map + Nonlinearity)&lt;/strong&gt;: Computes \(a = \sigma(\mathbf{w}^\top \mathbf{x} + b)\), slicing input space with a hyperplane and bending the response through an activation function.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Layered Architectures (Depth vs. Width)&lt;/strong&gt;: Stacks neurons into hidden layers that progressively transform raw inputs into abstract, linearly separable latent coordinates.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Activation Functions (Breaking Linearity)&lt;/strong&gt;: Prevents multi-layer stacks from collapsing into a single linear matrix while controlling gradient flow during training.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Vectorized Forward Propagation&lt;/strong&gt;: Packs entire mini-batches into matrix multiplications \(Z^{[l]} = A^{[l-1]} W^{[l]\top} + \mathbf{b}^{[l]}\), turning loops over neurons into GPU-friendly BLAS kernels.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-one-input-vector-flowing-through-a-2-layer-neural-network&quot;&gt;Worked example: One Input Vector Flowing Through a 2-Layer Neural Network&lt;/h3&gt;

&lt;p&gt;Pass \(\mathbf{x} = \begin{bmatrix} 1 \\ -2 \end{bmatrix}\) through a tiny \(2 \to 2 \to 1\) network with ReLU hidden activation and linear output:
\(W^{[1]} = \begin{bmatrix} 1 &amp;amp; -1 \\ -2 &amp;amp; 1 \end{bmatrix}, \quad \mathbf{b}^{[1]} = \begin{bmatrix} 0 \\ 1 \end{bmatrix}, \quad W^{[2]} = \begin{bmatrix} 2 &amp;amp; -3 \end{bmatrix}, \quad b^{[2]} = 0.5\)&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hidden Layer Pre-Activation \(\mathbf{z}^{[1]} = W^{[1]}\mathbf{x} + \mathbf{b}^{[1]}\)&lt;/strong&gt;:
\(\mathbf{z}^{[1]} = \begin{bmatrix} 1(1) + (-1)(-2) + 0 \\ (-2)(1) + 1(-2) + 1 \end{bmatrix} = \begin{bmatrix} 3 \\ -3 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply ReLU Nonlinearity \(\mathbf{a}^{[1]} = \max(\mathbf{0}, \mathbf{z}^{[1]})\)&lt;/strong&gt;:
\(\mathbf{a}^{[1]} = \begin{bmatrix} \max(0, 3) \\ \max(0, -3) \end{bmatrix} = \begin{bmatrix} 3 \\ 0 \end{bmatrix}\)
Notice Neuron 2 is switched off (gating out negative half-space signals).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Output Layer Prediction \(\hat{y} = W^{[2]}\mathbf{a}^{[1]} + b^{[2]}\)&lt;/strong&gt;:
\(\hat{y} = 2(3) + (-3)(0) + 0.5 = 6.5\)
Every forward pass in deep learning—no matter how massive—is just this exact affine-then-nonlinear pattern repeated across layers.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Neural Networks are the foundation of modern deep learning. This chapter introduces the basic building blocks of neural networks, including neurons, layers, activation functions, and forward propagation. We’ll explore how these simple units combine to create powerful learning systems capable of solving complex problems.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/mnist_digits_grid.jpg&quot; alt=&quot;Handwritten digits on pixel grids&quot; /&gt;
&lt;em&gt;Figure: Handwritten digit recognition — each image is a pixel grid. (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Understanding neural networks is essential for anyone working in deep learning, as they form the basis for more advanced architectures and techniques covered in later chapters.&lt;/p&gt;

&lt;h3 id=&quot;quick-intuition-from-pixels-to-predictions&quot;&gt;Quick intuition: from pixels to predictions&lt;/h3&gt;

&lt;p&gt;For digit images (e.g. a \(28 \times 28\) grid), we often &lt;strong&gt;flatten&lt;/strong&gt; the image into a vector of \(784\) numbers and pass it through stacked neuron layers. Each layer transforms the representation; the final layer can produce \(10\) outputs for digits \(0\)–\(9\).&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter02/mnist_to_mlp_layers.jpg&quot; alt=&quot;From a 28×28 image to a multilayer network&quot; /&gt;
&lt;em&gt;Figure: Image \(28\times28\) → \(784\) inputs → hidden layers → outputs. (Illustration from an introductory neural-network video)&lt;/em&gt;&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/793200140509765&quot;&gt;Neural network intuition (Perceptron → Deep Learning)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After the neuron and activation notes, see &lt;strong&gt;02-99 Modern Applications and Updates&lt;/strong&gt; for SwiGLU, RMSNorm, and how MLP blocks are packaged in current foundation models. The LLM hub restates the same block, with FLOPs and a decoder diagram, in &lt;strong&gt;26-07&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (interview practice):&lt;/strong&gt; After activations and the MLP notes, see &lt;strong&gt;02-98 Interviews Practice&lt;/strong&gt; for original perceptron / softmax / ReLU drills; full solved Q&amp;amp;A is in &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. One neuron, then a layer, then a network, which is the order of this chapter.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=CqOfi41LfDw&quot;&gt;The Essential Main Ideas of Neural Networks&lt;/a&gt; — StatQuest with Josh Starmer, English. Labels every weight the introduction is about to define.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_99_Modern_Applications</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;In 2016, “doing deep learning” meant collecting a custom dataset and training a ResNet from random weights. By 2022–2026, the default workflow inverted: you start from a massive pretrained foundation model, evaluate zero-shot or few-shot performance, and only fine-tune—often with parameter-efficient adapters—when the data proves it necessary.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-the-foundation-model-workflow-20222026&quot;&gt;Key ideas: The Foundation-Model Workflow (2022–2026)&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Pretrain–Adapt Paradigm&lt;/strong&gt;: Shifts compute from bespoke per-task training to massive self-supervised pretraining followed by lightweight adaptation (prompting, RAG, LoRA, DPO/RLHF).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Chinchilla &amp;amp; Inference-Optimal Scaling Laws&lt;/strong&gt;: Balances model parameters \(N\) and training tokens \(D\) under a fixed compute budget \(C \approx 6ND\), revealing that many earlier models were severely undertrained relative to their size.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Open-Weight Ecosystem &amp;amp; Quantization&lt;/strong&gt;: Enables running billion-parameter models locally via 4-bit/8-bit weight quantization (AWQ, GPTQ, GGUF) and efficient KV-cache serving engines (vLLM, TensorRT-LLM).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluation-Driven Iteration&lt;/strong&gt;: Treats rigorous benchmark suites, contamination checks, and slice-level error metrics as the primary bottleneck once model capabilities outpace naive accuracy metrics.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-applying-the-chinchilla-compute-optimal-rule-c-approx-6nd&quot;&gt;Worked example: Applying the Chinchilla Compute-Optimal Rule (\(C \approx 6ND\))&lt;/h3&gt;

&lt;p&gt;Suppose your lab has a fixed pretraining compute budget of \(C = 1.2 \times 10^{21}\) FLOPs and follows the Chinchilla ratio of roughly \(D \approx 20 N\) training tokens per parameter.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Substitute \(D = 20N\) into the Transformer Training FLOP Formula \(C \approx 6ND\)&lt;/strong&gt;:
\(C \approx 6 N (20 N) = 120 N^2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Solve for Optimal Parameter Count \(N\)&lt;/strong&gt;:
\(N^2 = \frac{1.2 \times 10^{21}}{120} = 1.0 \times 10^{19} \implies N = \sqrt{10 \times 10^{18}} \approx 3.16 \times 10^9\text{ parameters (3.16B)}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Solve for Optimal Training Token Count \(D\)&lt;/strong&gt;:
\(D = 20 N \approx 20 \times (3.16 \times 10^9) = 6.32 \times 10^{10}\text{ tokens (63.2B tokens)}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sanity Check&lt;/strong&gt;:
\(6 \times (3.16 \times 10^9) \times (6.32 \times 10^{10}) \approx 1.198 \times 10^{21}\text{ FLOPs}\)
Notice that if you instead trained a 30B model on the same budget, it would only see \(D = \frac{1.2\times 10^{21}}{6 \times 3\times 10^{10}} = 6.67\text{B}\) tokens—severely undertrained and slower at inference!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-what-doing-deep-learning-means-after-foundation-models&quot;&gt;Optional: what “doing deep learning” means after foundation models&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace the introductions to deep learning, MNIST, or the course guide. It updates the &lt;em&gt;practice&lt;/em&gt; of the field after foundation models became the default starting point.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Chapter 01’s core idea is that deep models learn hierarchical features from data. From 2022 onward, most applied work starts from a &lt;strong&gt;pretrained&lt;/strong&gt; model and a serving stack, not from a blank MNIST net — but the same questions (when DL helps, what data you need, what can go wrong) still decide success.&lt;/p&gt;

&lt;h2 id=&quot;1-the-new-default-workflow&quot;&gt;1. The new default workflow&lt;/h2&gt;

&lt;p&gt;A typical 2024–2026 project looks like:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Choose a foundation model (vision, language, speech, or multimodal).&lt;/li&gt;
  &lt;li&gt;Adapt it with prompting, retrieval, or parameter-efficient fine-tuning (Chapter 15).&lt;/li&gt;
  &lt;li&gt;Evaluate on a held-out set &lt;em&gt;and&lt;/em&gt; on safety / cost constraints.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;That is still supervised or self-supervised learning. The change is the &lt;strong&gt;initialization&lt;/strong&gt; and the &lt;strong&gt;interface&lt;/strong&gt; (APIs, tokenizers, chat templates), not the definition of a neural net.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;data-science-copilots&quot;&gt;Data science copilots&lt;/h3&gt;

&lt;p&gt;Tabular and SQL workflows now wrap an LLM around a classical pipeline (pandas, scikit-learn, warehouse queries). The model does not replace the loss or the split; it writes code and explanations. Hugging Face &lt;a href=&quot;https://github.com/huggingface/transformers&quot;&gt;transformers&lt;/a&gt; plus &lt;a href=&quot;https://github.com/huggingface/datasets&quot;&gt;datasets&lt;/a&gt; is the common research glue.&lt;/p&gt;

&lt;h3 id=&quot;compute-optimal-training&quot;&gt;Compute-optimal training&lt;/h3&gt;

&lt;p&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Hoffmann et al., 2022&lt;/a&gt; showed that many GPT-3-scale models were &lt;strong&gt;undertrained&lt;/strong&gt;: for a fixed FLOP budget \(C\), the compute-optimal parameter count \(N\) and token count \(D\) scale together. Applied teams now ask “how many tokens per parameter?” before buying GPUs.&lt;/p&gt;

&lt;h3 id=&quot;open-model-ecosystem&quot;&gt;Open model ecosystem&lt;/h3&gt;

&lt;p&gt;Meta’s &lt;a href=&quot;https://arxiv.org/abs/2302.13971&quot;&gt;LLaMA&lt;/a&gt; / &lt;a href=&quot;https://arxiv.org/abs/2307.09288&quot;&gt;Llama 2&lt;/a&gt; / &lt;a href=&quot;https://ai.meta.com/blog/meta-llama-3/&quot;&gt;Llama 3&lt;/a&gt; and later open families (Mistral, Qwen, Gemma) made it normal to run a capable LM on a single workstation with &lt;a href=&quot;https://github.com/ggerganov/llama.cpp&quot;&gt;llama.cpp&lt;/a&gt; or &lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt;. The MNIST walkthrough still teaches the loop; these stacks are where the loop is deployed.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://pytorch.org/&quot;&gt;PyTorch&lt;/a&gt; 2.x with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt; as the default accelerator path.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://huggingface.co/&quot;&gt;Hugging Face Hub&lt;/a&gt; — model cards, tokenizers, and evaluation harnesses.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX&lt;/a&gt; / Flax — research training of large models at Google-scale labs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Training Compute-Optimal Large Language Models (Hoffmann et al., 2022)&lt;/a&gt; — Chinchilla: scale data with model size.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2302.13971&quot;&gt;LLaMA: Open and Efficient Foundation Language Models (Touvron et al., 2023)&lt;/a&gt; — openly described foundation LM that reset the ecosystem.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2307.09288&quot;&gt;Llama 2 (Touvron et al., 2023)&lt;/a&gt; — dialogue / RLHF-tuned open weights.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;The “What is deep learning” and MNIST lessons still define the field. This note only updates &lt;em&gt;where&lt;/em&gt; a newcomer starts in 2026: pretrained weights, hubs, and scaling-law budgeting — not a new definition of a neural network.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=LPZh9BOjkQs&quot;&gt;Large Language Models explained briefly&lt;/a&gt; — 3Blue1Brown, English. A short account of pretraining, transformers, and RLHF, which is the 2022–2026 default this note describes.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, English. The longer map of the same workflow: data, training, and what a deployed model is.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=N1fbskTpwZ0&quot;&gt;MIT 6.S191 (2024): Language Models and New Frontiers&lt;/a&gt; — Alexander Amini, English. MIT’s 2024 frontier lecture is the ‘what shipped recently’ companion to the citations in this note.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-98 Deep Learning Interviews practice track</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_98_Interviews_Practice_Track/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_98_Interviews_Practice_Track</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Walk into a senior ML interview and you will rarely be asked to recite a textbook definition verbatim. Instead, you will be handed an ambiguous failure—a training loss stuck at 2.30, a classifier with 99% accuracy that fails in production, or a latency budget of 15 ms—and asked to reason from first principles.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-structuring-deep-learning-interview-readiness&quot;&gt;Key ideas: Structuring Deep Learning Interview Readiness&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;First-Principles Foundations (Chapters 00–05)&lt;/strong&gt;: Covers calculus, linear algebra, probability, backprop, initialization, optimization, and regularization—the non-negotiable core tested in almost every ML screen.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Architecture &amp;amp; Inductive Bias Fluency (Chapters 06–14)&lt;/strong&gt;: Connects CNNs, RNNs, Attention, Transformers, and generative models to concrete trade-offs in receptive field, sequence complexity, and memory footprint.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Diagnostic &amp;amp; Debugging Reasoning&lt;/strong&gt;: Translates symptoms (NaN loss, train/val divergence, mode collapse, gradient explosion) directly into mathematical root causes and targeted fixes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Closed-Book Derivation vs. System Design Trade-Offs&lt;/strong&gt;: Separates timed whiteboard derivations (loss gradients, complexity counts) from open-ended production design (data pipelines, evaluation metrics, serving latency).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-diagnosing-a-classic-interview-failure-mode-from-two-numbers&quot;&gt;Worked example: Diagnosing a Classic Interview Failure Mode from Two Numbers&lt;/h3&gt;

&lt;p&gt;An interviewer tells you: &lt;em&gt;“We trained a 5-class classifier on 50,000 images. After 10 epochs, training cross-entropy is \(0.02\), validation cross-entropy is \(1.85\), and validation accuracy is \(61\%\). What is happening, and what exact numbers prove it?”&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compare Against Random-Guessing Baseline&lt;/strong&gt;:
For \(C = 5\) classes, uniform random guessing yields cross-entropy \(\ln(5) \approx 1.609\) and accuracy \(20\%\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Spot the Paradox&lt;/strong&gt;:
Validation accuracy is \(61\%\) (far better than \(20\%\) random), yet validation cross-entropy is \(1.85 &amp;gt; 1.609\) (worse than random guessing!).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mathematical Diagnosis (Severe Overconfidence / Miscalibration)&lt;/strong&gt;:
Cross-entropy penalizes confident wrong predictions logarithmically: if the model assigns \(p = 0.001\) to the true class on just \(25\%\) of validation samples, those errors alone contribute:
\(0.25 \times (-\ln 0.001) = 0.25 \times 6.908 = 1.727\text{ nats}\)
Meanwhile, training loss of \(0.02\) (\(\approx e^{-0.02} = 98\%\) average confidence on training labels) proves classic &lt;strong&gt;overfitting with overconfident logits&lt;/strong&gt;. Targeted fixes: temperature scaling, label smoothing, weight decay, and data augmentation.&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-deep-learning-interviews-practice-track&quot;&gt;Optional: Deep Learning Interviews practice track&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace any theory chapter. It is a map and a study plan for using one free interview book as extra drill — after you finish the matching course notes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;what-the-book-is&quot;&gt;What the book is&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Deep Learning Interviews&lt;/strong&gt; (second edition) by &lt;strong&gt;Shlomo Kashani&lt;/strong&gt; and &lt;strong&gt;Amir Ivry&lt;/strong&gt; is a free volume of fully solved interview- and exam-style problems across core AI themes. It is written for graduate students and job seekers who need to speak clearly under time pressure, and it is also useful as a research-foundation checklist.&lt;/p&gt;

&lt;p&gt;This course does &lt;strong&gt;not&lt;/strong&gt; reprint the book. Open the official sources yourself:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;PDF / abstract: &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Companion repository: &lt;a href=&quot;https://github.com/BoltzmannEntropy/interviews.ai&quot;&gt;github.com/BoltzmannEntropy/interviews.ai&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;Author site: &lt;a href=&quot;http://www.interviews.ai/&quot;&gt;interviews.ai&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Download the PDF from arXiv (or the authors’ links). Respect the authors’ terms on those pages. Do not paste long excerpts into notes, issues, or shared answer keys.&lt;/p&gt;

&lt;h2 id=&quot;how-to-use-it-with-this-course&quot;&gt;How to use it with this course&lt;/h2&gt;

&lt;p&gt;Pick one mode and stay honest about timing:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Interview drill.&lt;/strong&gt; After a chapter, attempt the original prompts in that chapter’s optional companion &lt;em&gt;out loud&lt;/em&gt;, then open the book for a harder, fully solved set on the same &lt;em&gt;theme&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Class quiz.&lt;/strong&gt; Instructors can assign 2–3 companion prompts as a short oral or written quiz. Use the book only as the instructor key / extra homework, not as a copy-paste worksheet.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Research foundation.&lt;/strong&gt; Before reading a paper that leans on information theory, autodiff, or uncertainty, skim the matching book &lt;em&gt;topic area&lt;/em&gt; (not a dumped chapter) and the course theory lesson.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Work closed-book first. Then check the course hint. Only then open the PDF for additional solved Q&amp;amp;A.&lt;/p&gt;

&lt;h2 id=&quot;study-plan-book-themes--course-chapters-0026&quot;&gt;Study plan: book themes → course chapters 00–26&lt;/h2&gt;

&lt;p&gt;The book is organized by interview themes, not by this course’s chapter numbers. Use the table as a routing sheet. Theme names below are &lt;strong&gt;high-level labels&lt;/strong&gt; only — they are not a table of contents reprint.&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Course chapter&lt;/th&gt;
      &lt;th&gt;Course topic&lt;/th&gt;
      &lt;th&gt;Book themes to study (in the PDF)&lt;/th&gt;
      &lt;th&gt;Optional companion&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;00&lt;/td&gt;
      &lt;td&gt;Mathematical prerequisites&lt;/td&gt;
      &lt;td&gt;Information theory (entropy, KL, mutual information); calculus / autodiff intuition&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;00-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;01&lt;/td&gt;
      &lt;td&gt;Introduction and course guide&lt;/td&gt;
      &lt;td&gt;How the book is meant to be used; this hub&lt;/td&gt;
      &lt;td&gt;this lesson&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;02&lt;/td&gt;
      &lt;td&gt;Neural network fundamentals&lt;/td&gt;
      &lt;td&gt;Perceptrons, activations, and the “expanded deep learning” architecture basics&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;02-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;03&lt;/td&gt;
      &lt;td&gt;Training, losses, backpropagation&lt;/td&gt;
      &lt;td&gt;Algorithmic differentiation; Hessian intuition; logistic / classification&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;03-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;04&lt;/td&gt;
      &lt;td&gt;CNNs&lt;/td&gt;
      &lt;td&gt;Convolution, CNN architectures, early feature-extraction ideas&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;04-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;05–08&lt;/td&gt;
      &lt;td&gt;RNN, LSTM, attention, Transformers&lt;/td&gt;
      &lt;td&gt;No Volume I home — stay with course notes; Volume II is planned around NLP / sequences&lt;/td&gt;
      &lt;td&gt;hub only&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;09&lt;/td&gt;
      &lt;td&gt;Regularization&lt;/td&gt;
      &lt;td&gt;Overfitting, validation, capacity control&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;09-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;10&lt;/td&gt;
      &lt;td&gt;Optimizers&lt;/td&gt;
      &lt;td&gt;Adaptive methods (Adam and relatives), hyperparameters, training dynamics&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;10-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;11–14&lt;/td&gt;
      &lt;td&gt;Generative models (incl. VAE, GAN)&lt;/td&gt;
      &lt;td&gt;No Volume I home — Volume II plan mentions GAN / VAE; use course chapters&lt;/td&gt;
      &lt;td&gt;hub only&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;15&lt;/td&gt;
      &lt;td&gt;Transfer learning&lt;/td&gt;
      &lt;td&gt;CNN feature extraction and frozen vs fine-tuned backbones&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;15-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;16–23&lt;/td&gt;
      &lt;td&gt;SSL, CV apps, NLP, speech, RL, GNN, efficiency&lt;/td&gt;
      &lt;td&gt;No Volume I home. Volume II plan mentions detection, segmentation, NLP, RL — use the matching course chapter&lt;/td&gt;
      &lt;td&gt;hub only&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;24&lt;/td&gt;
      &lt;td&gt;Interpretability&lt;/td&gt;
      &lt;td&gt;Related discussion only; Bayesian &lt;em&gt;uncertainty&lt;/em&gt; lives in 25&lt;/td&gt;
      &lt;td&gt;hub only&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;25&lt;/td&gt;
      &lt;td&gt;Advanced topics&lt;/td&gt;
      &lt;td&gt;Bayesian deep learning and probabilistic thinking&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;25-98&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;26&lt;/td&gt;
      &lt;td&gt;Large language models&lt;/td&gt;
      &lt;td&gt;No Volume I home — use this course’s LLM hub (pretraining math, prompting, alignment, serving, distillation, internals)&lt;/td&gt;
      &lt;td&gt;&lt;strong&gt;26-06&lt;/strong&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;themes-with-no-course-chapter-of-their-own&quot;&gt;Themes with no course chapter of their own&lt;/h3&gt;

&lt;p&gt;Keep these on the hub. Do &lt;strong&gt;not&lt;/strong&gt; invent a new required chapter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Ensemble methods (bagging / boosting / stacking).&lt;/strong&gt; The book treats neural-net ensembles as an interview topic. This course has no dedicated ensemble chapter. If you interview on that theme:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Bagging: average independently trained models to cut variance.&lt;/li&gt;
  &lt;li&gt;Boosting: add models that correct residual mistakes (more bias-reduction than bagging).&lt;/li&gt;
  &lt;li&gt;Stacking: a second model learns how to combine base predictors.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Discussion (original, not from the book).&lt;/strong&gt; When would you rather bag ten independently trained CNNs than train one model ten times larger? What breaks if the base models are highly correlated?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Volume II (planned).&lt;/strong&gt; The authors outline a later volume on advanced CNNs, detection, segmentation, NLP, GANs, VAEs, and reinforcement learning. Until that volume is your assigned text, use this course’s Chapters 11–21 for those topics and treat the Volume I PDF as the solved-practice source for the table above.&lt;/p&gt;

&lt;h2 id=&quot;original-warm-up-hub-only&quot;&gt;Original warm-up (hub only)&lt;/h2&gt;

&lt;p&gt;These three prompts are course-written. They are not taken from the book.&lt;/p&gt;

&lt;h3 id=&quot;h1-what-is-the-interviewer-actually-testing&quot;&gt;H1. What is the interviewer actually testing?&lt;/h3&gt;

&lt;p&gt;You are asked “why cross-entropy and not MSE for 10-way classification?” in two minutes. Name the &lt;em&gt;modeling&lt;/em&gt; reason and the &lt;em&gt;optimization&lt;/em&gt; reason, then stop.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Think likelihood of a categorical distribution, and the shape of the gradient when the prediction is confidently wrong.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Modeling: a softmax output is a discrete distribution; cross-entropy is the negative log-likelihood of that model. Optimization: MSE on probabilities often gives weak gradients when the predicted class is already peaked on the wrong label; NLL still pushes the logit of the true class up. Open the PDF later for more classification / loss interview items — do not copy them here.&lt;/p&gt;

&lt;h3 id=&quot;h2-closed-book-vs-open-book&quot;&gt;H2. Closed-book vs open-book&lt;/h3&gt;

&lt;p&gt;You may use the PDF in a take-home exam but not in a 45-minute onsite. How should your weekly practice change?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Onsite interviews reward short derivations you can write on a whiteboard (sigmoid derivative, conv output shape, Adam update in one line).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Drill the companion prompts on a timer. Use the book for depth and for checking language. If you can only solve a topic with the PDF open, that topic is not interview-ready.&lt;/p&gt;

&lt;h3 id=&quot;h3-ensemble-without-an-ensemble-chapter&quot;&gt;H3. Ensemble without an ensemble chapter&lt;/h3&gt;

&lt;p&gt;A hiring loop asks you to reduce variance of a well-tuned ResNet without changing the architecture. Give two methods that are &lt;em&gt;not&lt;/em&gt; “collect more labels.”&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; One method changes how you use existing models; one changes how you use existing data.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Snapshot / bagged fine-tunes, test-time augmentation, and dropout-as-ensemble at test time all reduce variance. A larger model is a capacity change, not a variance-reduction ensemble. Full solved ensemble problems belong in the book, not in this repo.&lt;/p&gt;

&lt;h2 id=&quot;companion-index&quot;&gt;Companion index&lt;/h2&gt;

&lt;p&gt;After the matching theory lesson, open:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;00-98&lt;/strong&gt; — information theory and calculus / autodiff&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;02-98&lt;/strong&gt; — neurons, activations, MLP structure&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;03-98&lt;/strong&gt; — autodiff, Hessian intuition, logistic classification&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;04-98&lt;/strong&gt; — CNN geometry and architectures&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;09-98&lt;/strong&gt; — overfitting and regularizers&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;10-98&lt;/strong&gt; — Adam-family optimizers&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;15-98&lt;/strong&gt; — feature extraction and transfer&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;25-98&lt;/strong&gt; — Bayesian / uncertainty themes&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;26-06&lt;/strong&gt; — LLM hub (pretraining math, serving, internals, distillation; original prompts only)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each companion has 3–6 &lt;strong&gt;original&lt;/strong&gt; prompts with short hints. They do not rewrite theory.&lt;/p&gt;

&lt;h2 id=&quot;attribution-and-license-reminder&quot;&gt;Attribution and license reminder&lt;/h2&gt;

&lt;p&gt;Kashani, S., and Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;. arXiv:2201.00650. GitHub: &lt;a href=&quot;https://github.com/BoltzmannEntropy/interviews.ai&quot;&gt;BoltzmannEntropy/interviews.ai&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The solved question bank is the authors’ work. This course only cites the title, authors, arXiv id, and theme names, then adds original practice of its own. &lt;strong&gt;Students download the book from arXiv&lt;/strong&gt; (or the official GitHub / interviews.ai links). Do not vendor a local copy of the PDF in this repository and do not paste substantial book text into pull requests.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, English. The syllabus-level picture this practice track maps interview topics onto.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, English. Use this for the modern half of the track (models that did not exist when older interview books were written).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, English. The track expects you to derive a backward pass; this is the worked derivation.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-01 Why Deep Learning?</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_01_Why_Deep_Learning/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_01_Why_Deep_Learning</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Every new deep learning engineer faces a critical architectural question on their very first production project: “Should I build a deep neural network here, or will XGBoost beat it in ten minutes?” Knowing why deep learning wins—and where it loses—is what separates an engineer from a hype follower.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-the-case-for-and-against-deep-learning&quot;&gt;Key ideas: The Case for (and Against) Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;End-to-End Representation Discovery&lt;/strong&gt;: Eliminates fragile manual feature pipelines on unstructured modalities (pixels, waveforms, raw text, graphs) where human-engineered descriptors plateau early.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Data &amp;amp; Compute Scaling Laws&lt;/strong&gt;: Classical ML error curves flatten out past moderate dataset sizes, whereas deep models continue improving predictably as data, parameters, and compute scale together.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Inductive Bias &amp;amp; Tabular Boundaries&lt;/strong&gt;: On small-to-medium structured tabular datasets with heterogeneous features, gradient-boosted decision trees (XGBoost, LightGBM) still often match or beat neural nets at a fraction of the cost.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ecosystem &amp;amp; Transfer Learning Leverage&lt;/strong&gt;: Pretrained foundation models let small teams inherit billions of tokens or images of prior representation learning via fine-tuning rather than training from scratch.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-quantifying-scaling-break-even-between-classical-ml-and-deep-learning&quot;&gt;Worked example: Quantifying Scaling Break-Even Between Classical ML and Deep Learning&lt;/h3&gt;

&lt;p&gt;Suppose on a document-classification benchmark, a TF-IDF + Logistic Regression baseline achieves error rate \(E_{\text{ML}}(N) = 0.08 + \frac{2.0}{\sqrt{N}}\) (floor of 8% due to fixed bag-of-words features), while a fine-tuned Transformer achieves \(E_{\text{DL}}(N) = 0.02 + \frac{8.0}{\sqrt{N}}\) (lower 2% floor, higher sample complexity). Find the dataset size \(N^*\) where deep learning overtakes classical ML.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Test at Small Data (\(N = 400\), so \(\sqrt{N} = 20\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Classical ML: \(E_{\text{ML}}(400) = 0.08 + \frac{2.0}{20} = 0.08 + 0.10 = 18.0\%\) error.&lt;/li&gt;
      &lt;li&gt;Deep Learning: \(E_{\text{DL}}(400) = 0.02 + \frac{8.0}{20} = 0.02 + 0.40 = 42.0\%\) error.
At \(N = 400\), classical ML crushes deep learning!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Solve for the Exact Crossover Point \(E_{\text{DL}}(N^*) = E_{\text{ML}}(N^*)\)&lt;/strong&gt;:
\(0.02 + \frac{8.0}{\sqrt{N^*}} = 0.08 + \frac{2.0}{\sqrt{N^*}} \implies \frac{6.0}{\sqrt{N^*}} = 0.06 \implies \sqrt{N^*} = 100 \implies N^* = 10{,}000\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify at Large Data (\(N = 40{,}000\), so \(\sqrt{N} = 200\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Classical ML: \(0.08 + \frac{2.0}{200} = 9.0\%\) error.&lt;/li&gt;
      &lt;li&gt;Deep Learning: \(0.02 + \frac{8.0}{200} = 6.0\%\) error.
This exact trade-off between &lt;strong&gt;approximation floor&lt;/strong&gt; (bias) and &lt;strong&gt;sample complexity&lt;/strong&gt; (variance) governs every real-world model selection decision.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Why deep learning, and when to use it:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Limitations of Traditional ML and What Makes DL Different&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;When to Use Deep Learning and the Ecosystem&lt;/strong&gt; — success stories, data/compute, workflow, tools, books, trends&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=q6kJ71tEYqM&quot;&gt;Machine Learning vs Deep Learning&lt;/a&gt; — IBM Technology, English. It states what deep learning adds beyond classical machine learning, which is this block’s question.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, English. The ‘why deep learning’ segment of the MIT lecture lists the scaling and data reasons the lessons expand.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. Shows the hierarchical features that make depth useful on images, the success case this block keeps citing.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-01-02 When to Use Deep Learning and the Ecosystem</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_01_02_When_to_Use_DL_and_Ecosystem/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_01_02_When_to_Use_DL_and_Ecosystem</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Choosing the wrong tool for a machine learning problem can cost six months of engineering time and thousands of dollars in GPU bills. Great ML practitioners don’t reach for deep learning blindly—they weigh data modality, sample size, latency, interpretability, and the modern PyTorch/JAX/Hugging Face ecosystem before writing line one.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-decision-criteria--modern-dl-ecosystem&quot;&gt;Key ideas: Decision Criteria &amp;amp; Modern DL Ecosystem&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Modality &amp;amp; Scale Matrix&lt;/strong&gt;: Deep learning dominates unstructured data (images, audio, text, video, multimodal streams) and large-scale datasets, while classical GBDTs remain formidable on small-to-medium tabular data.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Operational Constraints (Latency, Memory, Interpretability)&lt;/strong&gt;: Regulated domains (credit scoring, clinical triage) often demand calibrated probabilities, strict millisecond budgets, or auditable feature attributions that shape architecture selection.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Hardware Acceleration (GPUs, TPUs, Tensor Cores)&lt;/strong&gt;: Exploits massive matrix-multiply parallelism (GEMM) in reduced precision (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FP16&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BF16&lt;/code&gt;/&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;FP8&lt;/code&gt;), turning week-long CPU runs into minutes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Software Stack Synergy&lt;/strong&gt;: Combines PyTorch/JAX for autodiff and compilation (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;, XLA), Hugging Face for pretrained weights, and ONNX/TensorRT for low-latency production deployment.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-computing-gpu-throughput--training-cost-before-launching-a-run&quot;&gt;Worked example: Computing GPU Throughput &amp;amp; Training Cost Before Launching a Run&lt;/h3&gt;

&lt;p&gt;Suppose you want to fine-tune a vision model requiring \(C = 4 \times 10^9\) FLOPs (4 GFLOPs) per forward pass on \(N = 100{,}000\) images for \(E = 10\) epochs on a GPU delivering \(T_{\text{eff}} = 50\text{ TFLOP/s}\) (\(5 \times 10^{13}\) FLOP/s) effective &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;BF16&lt;/code&gt; throughput.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Account for Forward + Backward Compute&lt;/strong&gt;:
A standard backward pass costs roughly \(2\times\) the forward pass, so one full training step per image costs \(3C\):
\(\text{FLOPs per image} = 3 \times (4 \times 10^9) = 1.2 \times 10^{10}\text{ FLOPs}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Total Training FLOPs Across 10 Epochs&lt;/strong&gt;:
\(\text{Total FLOPs} = 10 \times 100{,}000 \times (1.2 \times 10^{10}) = 1.2 \times 10^{16}\text{ FLOPs}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Estimate Wall-Clock Training Time&lt;/strong&gt;:
\(t = \frac{1.2 \times 10^{16}}{5 \times 10^{13}\text{ FLOP/s}} = 240\text{ seconds} = 4.0\text{ minutes}\)
Running a 30-second back-of-the-envelope FLOP budget tells you immediately whether a job takes 4 minutes on one GPU or requires a multi-node cluster.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;when-to-use-deep-learning&quot;&gt;When to Use Deep Learning&lt;/h2&gt;

&lt;h3 id=&quot;deep-learning-excels-when&quot;&gt;Deep Learning Excels When:&lt;/h3&gt;

&lt;p&gt;✅ &lt;strong&gt;Large amounts of data&lt;/strong&gt; available&lt;br /&gt;
✅ &lt;strong&gt;Complex patterns&lt;/strong&gt; to learn&lt;br /&gt;
✅ &lt;strong&gt;High-dimensional inputs&lt;/strong&gt; (images, text, audio)&lt;br /&gt;
✅ &lt;strong&gt;End-to-end learning&lt;/strong&gt; desired&lt;br /&gt;
✅ &lt;strong&gt;Sufficient computational resources&lt;/strong&gt;&lt;br /&gt;
✅ &lt;strong&gt;Non-linear relationships&lt;/strong&gt; in data&lt;/p&gt;

&lt;h3 id=&quot;traditional-ml-may-be-better-when&quot;&gt;Traditional ML May Be Better When:&lt;/h3&gt;

&lt;p&gt;⚠️ Small datasets (&amp;lt; 1000 samples)&lt;br /&gt;
⚠️ Need interpretability (medical diagnosis decisions)&lt;br /&gt;
⚠️ Limited computational resources&lt;br /&gt;
⚠️ Simple, well-understood problems&lt;br /&gt;
⚠️ Fast training required&lt;br /&gt;
⚠️ Linear relationships suffice&lt;/p&gt;

&lt;h2 id=&quot;success-stories&quot;&gt;Success Stories&lt;/h2&gt;

&lt;h3 id=&quot;computer-vision-imagenet-2012&quot;&gt;Computer Vision: ImageNet (2012)&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;AlexNet&lt;/strong&gt; achieved 15.3% error rate (vs 26% for traditional methods)&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;First deep learning victory in computer vision&lt;/li&gt;
  &lt;li&gt;Sparked the deep learning revolution&lt;/li&gt;
  &lt;li&gt;8-layer CNN with 60M parameters&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;natural-language-machine-translation&quot;&gt;Natural Language: Machine Translation&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Google Neural Machine Translation (2016)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Reduced translation errors by 60%&lt;/li&gt;
  &lt;li&gt;Learned to translate better than phrase-based systems&lt;/li&gt;
  &lt;li&gt;Enabled near-human quality translation&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;games-alphago-2016&quot;&gt;Games: AlphaGo (2016)&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Defeated world champion Lee Sedol 4-1&lt;/li&gt;
  &lt;li&gt;Combined deep learning with Monte Carlo tree search&lt;/li&gt;
  &lt;li&gt;Mastered Go, considered much harder than chess&lt;/li&gt;
  &lt;li&gt;Demonstrated creative, intuitive play&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;healthcare-medical-imaging&quot;&gt;Healthcare: Medical Imaging&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Skin Cancer Detection (2017)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Deep learning matched dermatologist performance&lt;/li&gt;
  &lt;li&gt;Analyzed dermoscopic images&lt;/li&gt;
  &lt;li&gt;Potential to democratize expert-level diagnosis&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;speech-voice-assistants&quot;&gt;Speech: Voice Assistants&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Near-human accuracy in speech recognition&lt;/li&gt;
  &lt;li&gt;Enables Siri, Alexa, Google Assistant&lt;/li&gt;
  &lt;li&gt;Works across accents and languages&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;recommendation-systems-short-video-feeds-tiktok-style&quot;&gt;Recommendation systems: short-video feeds (TikTok-style)&lt;/h3&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_tiktok_title_nn.jpg&quot; alt=&quot;Recommendation algorithms and neural nets&quot; /&gt;
&lt;em&gt;Figure: Large-scale content recommendation powered by ML/DL. (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;An everyday ML/DL application: the feed automatically picks videos/products for each person. A typical stack includes:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Collaborative filtering&lt;/strong&gt; — users who engage with item A often like item B → recommend B (without “understanding” content).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_collaborative_filtering.jpg&quot; alt=&quot;Collaborative filtering: view A → suggest B&quot; /&gt;
&lt;em&gt;Figure: After someone views A, the system suggests related items (B, …). (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Content-based recommendation&lt;/strong&gt; — match item features (tags, style, price, …) to find “similar” items.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_content_based_similar.jpg&quot; alt=&quot;Content-based: item A vs B&quot; /&gt;
&lt;em&gt;Figure: Finding similar items by attributes (illustrated with product icons). (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_item_feature_tags.jpg&quot; alt=&quot;Item feature tags&quot; /&gt;
&lt;em&gt;Figure: Items represented as sets of tags/features. (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Cold start&lt;/strong&gt; — new users/items with no history → CF is weak; fall back to content, global popularity, or short surveys.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_cold_start.jpg&quot; alt=&quot;Cold start: no history yet&quot; /&gt;
&lt;em&gt;Figure: Empty state with no history — the cold-start problem. (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Ranking &amp;amp; engagement signals&lt;/strong&gt; — likes, watch time, skips… pick candidates that “fit” in milliseconds.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/recsys_engagement_candidates.jpg&quot; alt=&quot;Candidates and engagement signals&quot; /&gt;
&lt;em&gt;Figure: From many candidate videos, the system picks ones matching viewing behavior. (Illustration from a recommendation-system explainer video)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This is deep learning at billions of users: large data, realtime feedback, multi-objective tradeoffs (retention, diversity, safety). Embeddings / two-tower models appear in Chapter 18; ε-greedy exploration in Chapter 20.&lt;/p&gt;

&lt;h2 id=&quot;the-data-advantage&quot;&gt;The Data Advantage&lt;/h2&gt;

&lt;h3 id=&quot;why-more-data-helps&quot;&gt;Why More Data Helps&lt;/h3&gt;

&lt;p&gt;Traditional ML:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Performance
    |     _______________
    |    /
    |   /
    |  /
    |_/________________
         Amount of Data
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Deep Learning:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Performance
    |              /
    |            /
    |          /
    |        /
    |      /
    |    /
    |__/________________
         Amount of Data
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;the-scaling-law&quot;&gt;The Scaling Law&lt;/h3&gt;

&lt;p&gt;Empirical observation: Deep learning performance often follows:&lt;/p&gt;

\[\text{Error} \propto \frac{1}{(\text{Data size})^\alpha}\]

&lt;p&gt;where \(\alpha \approx 0.5\) for many tasks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implication&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;4× more data → 2× error reduction&lt;/li&gt;
  &lt;li&gt;100× more data → 10× error reduction&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;computational-requirements&quot;&gt;Computational Requirements&lt;/h2&gt;

&lt;h3 id=&quot;gpu-revolution&quot;&gt;GPU Revolution&lt;/h3&gt;

&lt;p&gt;Deep learning became practical due to GPUs:&lt;/p&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Operation&lt;/th&gt;
      &lt;th&gt;CPU Time&lt;/th&gt;
      &lt;th&gt;GPU Time&lt;/th&gt;
      &lt;th&gt;Speedup&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Matrix Multiply (1000×1000)&lt;/td&gt;
      &lt;td&gt;100ms&lt;/td&gt;
      &lt;td&gt;5ms&lt;/td&gt;
      &lt;td&gt;20×&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Conv2D Layer&lt;/td&gt;
      &lt;td&gt;1000ms&lt;/td&gt;
      &lt;td&gt;10ms&lt;/td&gt;
      &lt;td&gt;100×&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Full Model Training&lt;/td&gt;
      &lt;td&gt;Days/Weeks&lt;/td&gt;
      &lt;td&gt;Hours/Days&lt;/td&gt;
      &lt;td&gt;10-100×&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h3 id=&quot;modern-infrastructure&quot;&gt;Modern Infrastructure&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Cloud Computing&lt;/strong&gt;: AWS, Google Cloud, Azure&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Specialized Hardware&lt;/strong&gt;: TPUs, Neural Processing Units&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Distributed Training&lt;/strong&gt;: Multi-GPU, multi-machine&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mixed Precision&lt;/strong&gt;: FP16 training for speed&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;the-deep-learning-workflow&quot;&gt;The Deep Learning Workflow&lt;/h2&gt;

&lt;h3 id=&quot;typical-process&quot;&gt;Typical Process&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Data Collection&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Gather large dataset&lt;/li&gt;
      &lt;li&gt;Ensure quality and diversity&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Data Preparation&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Clean and preprocess&lt;/li&gt;
      &lt;li&gt;Split into train/val/test&lt;/li&gt;
      &lt;li&gt;Augment if needed&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Model Design&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Choose architecture&lt;/li&gt;
      &lt;li&gt;Define layers and connections&lt;/li&gt;
      &lt;li&gt;Set hyperparameters&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Training&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Initialize parameters&lt;/li&gt;
      &lt;li&gt;Forward pass → loss → backward pass&lt;/li&gt;
      &lt;li&gt;Update weights&lt;/li&gt;
      &lt;li&gt;Monitor metrics&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluation&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Test on held-out data&lt;/li&gt;
      &lt;li&gt;Analyze errors&lt;/li&gt;
      &lt;li&gt;Visualize predictions&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Iteration&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Improve data&lt;/li&gt;
      &lt;li&gt;Tune architecture&lt;/li&gt;
      &lt;li&gt;Adjust hyperparameters&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Deployment&lt;/strong&gt;
    &lt;ul&gt;
      &lt;li&gt;Optimize for inference&lt;/li&gt;
      &lt;li&gt;Deploy to production&lt;/li&gt;
      &lt;li&gt;Monitor performance&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;tools-and-frameworks&quot;&gt;Tools and Frameworks&lt;/h2&gt;

&lt;h3 id=&quot;deep-learning-frameworks&quot;&gt;Deep Learning Frameworks&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;PyTorch&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Dynamic computation graphs&lt;/li&gt;
  &lt;li&gt;Pythonic interface&lt;/li&gt;
  &lt;li&gt;Popular in research&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;TensorFlow/Keras&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Production-ready&lt;/li&gt;
  &lt;li&gt;Extensive ecosystem&lt;/li&gt;
  &lt;li&gt;Easy deployment&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;JAX&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Functional approach&lt;/li&gt;
  &lt;li&gt;Fast and flexible&lt;/li&gt;
  &lt;li&gt;Growing adoption&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;supporting-libraries&quot;&gt;Supporting Libraries&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;NumPy&lt;/strong&gt;: Numerical computing&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pandas&lt;/strong&gt;: Data manipulation&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matplotlib/Seaborn&lt;/strong&gt;: Visualization&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scikit-learn&lt;/strong&gt;: Preprocessing, metrics&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;recommended-books-for-this-course&quot;&gt;Recommended Books for This Course&lt;/h2&gt;

&lt;p&gt;To deepen your understanding, we recommend these essential deep learning books:&lt;/p&gt;

&lt;h3 id=&quot;1-deep-learning-by-ian-goodfellow-yoshua-bengio-and-aaron-courville&quot;&gt;1. &lt;strong&gt;Deep Learning&lt;/strong&gt; by Ian Goodfellow, Yoshua Bengio, and Aaron Courville&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;The definitive deep learning textbook&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;Comprehensive coverage of theory and mathematics&lt;/li&gt;
  &lt;li&gt;Written by pioneers in the field&lt;/li&gt;
  &lt;li&gt;Free online: &lt;a href=&quot;http://www.deeplearningbook.org/&quot;&gt;deeplearningbook.org&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use for&lt;/strong&gt;: Mathematical foundations, theoretical depth&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-hands-on-machine-learning-with-scikit-learn-keras-and-tensorflow-by-aurélien-géron&quot;&gt;2. &lt;strong&gt;Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow&lt;/strong&gt; by Aurélien Géron&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Best practical implementation guide&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;Step-by-step code examples&lt;/li&gt;
  &lt;li&gt;End-to-end ML projects&lt;/li&gt;
  &lt;li&gt;Covers Scikit-Learn, TensorFlow, and Keras&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use for&lt;/strong&gt;: Implementation, practical projects&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-understanding-deep-learning-by-simon-jd-prince&quot;&gt;3. &lt;strong&gt;Understanding Deep Learning&lt;/strong&gt; by Simon J.D. Prince&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Modern, accessible introduction&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;Clear explanations with excellent visualizations&lt;/li&gt;
  &lt;li&gt;Covers recent architectures (Transformers, etc.)&lt;/li&gt;
  &lt;li&gt;Intuitive approach to complex concepts&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use for&lt;/strong&gt;: Building intuition, visual understanding&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-mit-deep-learning-book&quot;&gt;4. &lt;strong&gt;MIT Deep Learning Book&lt;/strong&gt;&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Rigorous academic treatment&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;Strong theoretical foundations&lt;/li&gt;
  &lt;li&gt;Research-oriented perspective&lt;/li&gt;
  &lt;li&gt;Mathematical proofs and derivations&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use for&lt;/strong&gt;: Academic depth, research preparation&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;5-deep-learning-interviews-by-shlomo-kashani-and-amir-ivry&quot;&gt;5. &lt;strong&gt;Deep Learning Interviews&lt;/strong&gt; by Shlomo Kashani and Amir Ivry&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Free solved interview / exam problems&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;PDF: &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt; — GitHub: &lt;a href=&quot;https://github.com/BoltzmannEntropy/interviews.ai&quot;&gt;interviews.ai&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;This course maps book &lt;em&gt;themes&lt;/em&gt; (not reprinted questions) onto optional &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;*-98&lt;/code&gt; companions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use for&lt;/strong&gt;: Interview drill after the matching theory lesson; start at &lt;strong&gt;01-98&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;how-to-use-these-books&quot;&gt;How to Use These Books&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Beginner Path&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Start with “Understanding Deep Learning” for intuition&lt;/li&gt;
  &lt;li&gt;Follow this course for structured learning&lt;/li&gt;
  &lt;li&gt;Reference “Hands-On ML” for implementation&lt;/li&gt;
  &lt;li&gt;Dive into “Deep Learning” for theory&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Intermediate Path&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Use this course as primary guide&lt;/li&gt;
  &lt;li&gt;Reference “Hands-On ML” for practical tips&lt;/li&gt;
  &lt;li&gt;Read “Deep Learning” chapters for depth&lt;/li&gt;
  &lt;li&gt;Consult “Understanding DL” for clarifications&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Advanced Path&lt;/strong&gt;:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Use this course for comprehensive coverage&lt;/li&gt;
  &lt;li&gt;Study “Deep Learning” for rigorous theory&lt;/li&gt;
  &lt;li&gt;Implement with “Hands-On ML” techniques&lt;/li&gt;
  &lt;li&gt;Reference MIT book for research details&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;current-trends-2024-2025&quot;&gt;Current Trends (2024-2025)&lt;/h2&gt;

&lt;h3 id=&quot;large-language-models-llms&quot;&gt;Large Language Models (LLMs)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;GPT-4, Claude, Gemini&lt;/li&gt;
  &lt;li&gt;Billions to trillions of parameters&lt;/li&gt;
  &lt;li&gt;Emergent capabilities at scale&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;multimodal-models&quot;&gt;Multimodal Models&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;CLIP: Vision + Language&lt;/li&gt;
  &lt;li&gt;GPT-4V: Text + Images&lt;/li&gt;
  &lt;li&gt;Unified understanding across modalities&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;efficient-ai&quot;&gt;Efficient AI&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Model compression&lt;/li&gt;
  &lt;li&gt;Quantization&lt;/li&gt;
  &lt;li&gt;Neural architecture search&lt;/li&gt;
  &lt;li&gt;Edge deployment&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;foundation-models&quot;&gt;Foundation Models&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Pre-train on massive data&lt;/li&gt;
  &lt;li&gt;Fine-tune for specific tasks&lt;/li&gt;
  &lt;li&gt;Transfer learning at scale&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;challenges-ahead&quot;&gt;Challenges Ahead&lt;/h2&gt;

&lt;h3 id=&quot;technical-challenges&quot;&gt;Technical Challenges&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Sample efficiency (learning from less data)&lt;/li&gt;
  &lt;li&gt;Robustness (handling distribution shift)&lt;/li&gt;
  &lt;li&gt;Interpretability (understanding decisions)&lt;/li&gt;
  &lt;li&gt;Computational cost (training and inference)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;societal-challenges&quot;&gt;Societal Challenges&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Bias and fairness&lt;/li&gt;
  &lt;li&gt;Privacy concerns&lt;/li&gt;
  &lt;li&gt;Environmental impact&lt;/li&gt;
  &lt;li&gt;Job displacement&lt;/li&gt;
  &lt;li&gt;Misinformation (deepfakes)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;p&gt;Deep learning succeeds because it:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;✅ Learns features automatically&lt;/li&gt;
  &lt;li&gt;✅ Scales with data and compute&lt;/li&gt;
  &lt;li&gt;✅ Handles high-dimensional inputs&lt;/li&gt;
  &lt;li&gt;✅ Achieves state-of-the-art results&lt;/li&gt;
  &lt;li&gt;✅ Enables end-to-end learning&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Best used when:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Large datasets available&lt;/li&gt;
  &lt;li&gt;Complex patterns exist&lt;/li&gt;
  &lt;li&gt;Computational resources sufficient&lt;/li&gt;
  &lt;li&gt;High performance required&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The field continues to evolve rapidly with new architectures, techniques, and applications emerging constantly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Next&lt;/strong&gt;: We’ll dive into the fundamentals of neural networks and understand how they actually work!&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/1444915507374636&quot;&gt;Recommendation algorithms (TikTok-style)&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=qYNweeDHiyU&quot;&gt;AI, Machine Learning, Deep Learning and Generative AI Explained&lt;/a&gt; — IBM Technology, English. Decide when the problem is actually a deep-learning problem rather than a classical one.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, English. The tools segment names the frameworks and the data scale the lesson’s ecosystem section assumes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=q6kJ71tEYqM&quot;&gt;Machine Learning vs Deep Learning&lt;/a&gt; — IBM Technology, English. A short check against using a deep model when a simpler model already fits.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-01-01 Limitations of Traditional ML and What Makes DL Different</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_01_01_Limitations_and_What_Makes_DL_Different/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_01_01_Limitations_and_What_Makes_DL_Different</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;In 2010, winning a computer vision contest meant chaining SIFT keypoints, HOG histograms, Fisher vectors, and a kernel SVM—and if lighting changed slightly, the whole handcrafted pipeline shattered. Deep learning replaced that brittle relay race with a single differentiable pipeline where every stage adapts together.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-why-classical-pipelines-hit-a-ceiling&quot;&gt;Key ideas: Why Classical Pipelines Hit a Ceiling&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Manual Feature Engineering Bottleneck&lt;/strong&gt;: Hand-designed descriptors (HOG, MFCC, TF-IDF) freeze assumptions about what signal matters before the classifier ever sees the labels, discarding subtle task-relevant cues.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Fixed vs. Learned Representations&lt;/strong&gt;: Classical models optimize only the final decision boundary over static coordinates, whereas deep networks jointly warp the coordinate space itself so complex manifolds flatten into linearly separable clusters.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Curse of Dimensionality &amp;amp; Local Smoothness&lt;/strong&gt;: Kernel methods and k-NN rely on raw input-space distance, which breaks down in high-dimensional pixel space (shifting an image by 1 pixel causes huge \(L_2\) distance despite identical semantics).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Joint End-to-End Credit Assignment&lt;/strong&gt;: Backpropagating the task loss all the way to the earliest layer aligns low-level filters directly with high-level semantic accuracy.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-why-raw-pixel-distance-fails-while-learned-features-succeed&quot;&gt;Worked example: Why Raw Pixel Distance Fails While Learned Features Succeed&lt;/h3&gt;

&lt;p&gt;Consider a tiny \(1 \times 4\) grayscale image of a vertical white bar:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Image A (bar at pixel 1): \(\mathbf{a} = [1, 0, 0, 0]\)&lt;/li&gt;
  &lt;li&gt;Image B (same bar shifted 1 pixel right): \(\mathbf{b} = [0, 1, 0, 0]\)&lt;/li&gt;
  &lt;li&gt;Image C (completely blank image): \(\mathbf{c} = [0, 0, 0, 0]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Raw Euclidean Distances in Pixel Space&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Distance between two identical bars (A and B):
\(\|\mathbf{a} - \mathbf{b}\|_2 = \sqrt{(1-0)^2 + (0-1)^2 + 0 + 0} = \sqrt{2} \approx 1.414\)&lt;/li&gt;
      &lt;li&gt;Distance between a bar and an empty image (A and C):
\(\|\mathbf{a} - \mathbf{c}\|_2 = \sqrt{(1-0)^2 + 0 + 0 + 0} = 1.000\)
In raw pixel space, a shifted bar looks &lt;em&gt;farther&lt;/em&gt; from itself (\(1.414\)) than from a blank screen (\(1.000\))!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply a Learned Translation-Invariant Feature (Max-Pooled Filter \(f(\mathbf{x}) = \max_i x_i\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;\(f(\mathbf{a}) = 1\), \(f(\mathbf{b}) = 1\), \(f(\mathbf{c}) = 0\).&lt;/li&gt;
      &lt;li&gt;Now \(\lvert f(\mathbf{a}) - f(\mathbf{b})\rvert = 0\) while \(\lvert f(\mathbf{a}) - f(\mathbf{c})\rvert = 1\).
Learning invariant representations resolves the geometric failure of raw-input similarity.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;the-power-of-deep-learning&quot;&gt;The Power of Deep Learning&lt;/h2&gt;

&lt;p&gt;Deep learning has become the dominant approach in artificial intelligence because it solves fundamental limitations of traditional machine learning.&lt;/p&gt;

&lt;h2 id=&quot;limitations-of-traditional-machine-learning&quot;&gt;Limitations of Traditional Machine Learning&lt;/h2&gt;

&lt;h3 id=&quot;1-manual-feature-engineering&quot;&gt;1. Manual Feature Engineering&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Traditional Approach&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# Manual feature extraction for image classification
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;calculate_histogram&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;detect_edges&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;extract_textures&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;compute_color_moments&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;image&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Then train a classifier on these features
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train_svm&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;features&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Problems&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Requires domain expertise&lt;/li&gt;
  &lt;li&gt;Time-consuming&lt;/li&gt;
  &lt;li&gt;May miss important patterns&lt;/li&gt;
  &lt;li&gt;Not scalable across domains&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Deep Learning Solution&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;# End-to-end learning
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;build_cnn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;images&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;labels&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Learns features automatically!
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;2-fixed-representations&quot;&gt;2. Fixed Representations&lt;/h3&gt;

&lt;p&gt;Traditional ML uses handcrafted features that:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Don’t adapt to data&lt;/li&gt;
  &lt;li&gt;May not be optimal for the task&lt;/li&gt;
  &lt;li&gt;Require redesign for new problems&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Deep learning &lt;strong&gt;learns optimal representations&lt;/strong&gt; for each specific task.&lt;/p&gt;

&lt;h3 id=&quot;3-scalability-limitations&quot;&gt;3. Scalability Limitations&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Traditional ML&lt;/strong&gt;: Often plateaus with more data&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Deep Learning&lt;/strong&gt;: Performance improves with scale&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Traditional ML:  _______________  (plateaus)
                     /
Deep Learning:     /  (keeps improving)
                  /
                 |
              Performance
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h2 id=&quot;what-makes-deep-learning-different&quot;&gt;What Makes Deep Learning Different?&lt;/h2&gt;

&lt;h3 id=&quot;1-hierarchical-feature-learning&quot;&gt;1. Hierarchical Feature Learning&lt;/h3&gt;

&lt;p&gt;Deep networks learn features at multiple levels:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example: Face Recognition&lt;/strong&gt;&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Layer 1 (Low-level):    Edges, colors, simple patterns
         ↓
Layer 2 (Mid-level):    Eyes, nose, mouth parts
         ↓
Layer 3 (High-level):   Complete faces, expressions
         ↓
Output:                  Person identity
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This mirrors how humans perceive - from simple to complex concepts.&lt;/p&gt;

&lt;h3 id=&quot;2-end-to-end-learning&quot;&gt;2. End-to-End Learning&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Traditional Pipeline&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Raw Data → Preprocessing → Feature Extraction → Feature Selection → Model → Output
         (Manual)        (Manual)            (Manual)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Deep Learning&lt;/strong&gt;:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Raw Data → Neural Network → Output
         (All learned automatically)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;3-universal-function-approximators&quot;&gt;3. Universal Function Approximators&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Universal Approximation Theorem&lt;/strong&gt;: A neural network with even a single hidden layer can approximate any continuous function (given enough neurons).&lt;/p&gt;

&lt;p&gt;Deep networks can learn to approximate:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Image transformations&lt;/li&gt;
  &lt;li&gt;Language patterns&lt;/li&gt;
  &lt;li&gt;Game strategies&lt;/li&gt;
  &lt;li&gt;Physical simulations&lt;/li&gt;
  &lt;li&gt;Complex decision boundaries&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=q6kJ71tEYqM&quot;&gt;Machine Learning vs Deep Learning&lt;/a&gt; — IBM Technology, English. The boundary between feature engineering and learned representations.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=CqOfi41LfDw&quot;&gt;The Essential Main Ideas of Neural Networks&lt;/a&gt; — StatQuest with Josh Starmer, English. Shows a dataset a straight line cannot fit and a small network can, which is the limitation the lesson names.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, English. Puts that contrast in a full training story: data, compute, and depth together.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01 Introduction to Deep Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_00_Introduction</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;For decades, building an AI system meant locking domain experts in a room to hand-craft brittle rules—edge filters for vision, phonetic templates for speech, grammar trees for text. Deep learning flipped that paradigm on its head: instead of telling the machine what features to look for, we give it a differentiable hierarchy of layers and let data sculpt the features automatically.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-entering-the-deep-learning-paradigm&quot;&gt;Key ideas: Entering the Deep Learning Paradigm&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Representation Learning (Features from Data)&lt;/strong&gt;: Replaces manual feature engineering with stacked nonlinear transformations \(f = f_L \circ \dots \circ f_1\) that learn edges, textures, parts, and semantics directly from raw tensors.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;End-to-End Differentiable Training&lt;/strong&gt;: Connects raw inputs to task losses through a single computational graph so gradient signals flow backwards and adapt every intermediate representation to the final objective.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Empirical Scaling (Data, Compute, and Model Capacity)&lt;/strong&gt;: Explains why deep architectures outperform classical models once dataset size and GPU parallelism cross critical thresholds, while remaining data-hungry in tiny-data regimes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Systems &amp;amp; Workflow Discipline&lt;/strong&gt;: Pairs mathematical understanding with disciplined engineering—reproducible seeds, baseline benchmarks, clean train/val/test splits, and quantitative error analysis.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-how-two-nonlinear-layers-learn-a-representation-that-a-linear-model-cannot&quot;&gt;Worked example: How Two Nonlinear Layers Learn a Representation That a Linear Model Cannot&lt;/h3&gt;

&lt;p&gt;Consider the classic 1D non-linearly separable dataset: \(x \in \{-2, 0, +2\}\) with binary labels \(y = (1, 0, 1)\) (positive if \(\lvert x\rvert \geq 1\)). No single linear threshold \(wx + b &amp;gt; 0\) can separate \(0\) from both \(-2\) and \(+2\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Hidden Representation Layer (2 ReLU Neurons)&lt;/strong&gt;:
Define \(h_1(x) = \text{ReLU}(x - 1)\) and \(h_2(x) = \text{ReLU}(-x - 1)\).
Evaluate on all three inputs:
    &lt;ul&gt;
      &lt;li&gt;At \(x = -2\): \(h_1 = \text{ReLU}(-3) = 0\), \(h_2 = \text{ReLU}(+1) = 1 \implies \mathbf{h} = (0, 1)\).&lt;/li&gt;
      &lt;li&gt;At \(x = 0\): \(h_1 = \text{ReLU}(-1) = 0\), \(h_2 = \text{ReLU}(-1) = 0 \implies \mathbf{h} = (0, 0)\).&lt;/li&gt;
      &lt;li&gt;At \(x = +2\): \(h_1 = \text{ReLU}(+1) = 1\), \(h_2 = \text{ReLU}(-3) = 0 \implies \mathbf{h} = (1, 0)\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Output Linear Classifier on the Learned Features&lt;/strong&gt;:
Compute \(z = h_1 + h_2 - 0.5\):
    &lt;ul&gt;
      &lt;li&gt;At \(x = -2\): \(z = 0 + 1 - 0.5 = +0.5 &amp;gt; 0 \implies \hat{y} = 1\).&lt;/li&gt;
      &lt;li&gt;At \(x = 0\): \(z = 0 + 0 - 0.5 = -0.5 &amp;lt; 0 \implies \hat{y} = 0\).&lt;/li&gt;
      &lt;li&gt;At \(x = +2\): \(z = 1 + 0 - 0.5 = +0.5 &amp;gt; 0 \implies \hat{y} = 1\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Key Insight&lt;/strong&gt;:
The hidden layer folded the real line so that both outer points mapped to \(h_1 + h_2 = 1\) while the center mapped to \(0\)—making a non-linearly separable problem trivial for a linear readout head.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This chapter introduces deep learning and how to approach the course:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;What Is Deep Learning&lt;/strong&gt; — concept overview, mathematical foundation, and intuition&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;First MNIST Walkthrough&lt;/strong&gt; — code snippet, related concepts, and fundamental papers&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Course Guide and How to Succeed&lt;/strong&gt; — applications, challenges, roadmap, prerequisites, and mindset&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After the MNIST walkthrough, see &lt;strong&gt;01-99 Modern Applications and Updates&lt;/strong&gt; for foundation-model workflows, Chinchilla scaling, and the open-weight ecosystem.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (interview practice):&lt;/strong&gt; See &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt; for the study-plan map to Kashani &amp;amp; Ivry (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) and the per-chapter companions.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, English. A 2024 MIT lecture that states what deep learning is and how a first network is trained.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. The digit-recognition network in this video is the picture the ‘what is deep learning’ lesson draws.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qYNweeDHiyU&quot;&gt;AI, Machine Learning, Deep Learning and Generative AI Explained&lt;/a&gt; — IBM Technology, English. Separates AI, machine learning, deep learning, and generative models, which is the map of this chapter.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-00-03 Course Guide and How to Succeed</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_00_03_Course_Guide_and_How_to_Succeed/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_00_03_Course_Guide_and_How_to_Succeed</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Most self-learners stall in deep learning not because the math is impossible, but because they read equations passively without implementing tiny sanity checks, or they copy notebooks without understanding why a loss curve behaves the way it does. Mastering deep learning is a closed-loop craft of theory, code, and diagnostic intuition.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-how-deep-learning-mastery-compounds&quot;&gt;Key ideas: How Deep Learning Mastery Compounds&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Application Landscape (Modalities &amp;amp; Inductive Biases)&lt;/strong&gt;: Maps real-world domains—vision, NLP, speech, RL, healthcare—to the structural assumptions (spatial locality, sequence order, reward dynamics) that dictate architecture choice.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Systemic Limitations &amp;amp; Failure Modes&lt;/strong&gt;: Highlights data hunger, distribution shift, black-box interpretability, compute costs, and calibration errors so you design models with realistic guardrails from day one.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Three-Loop Study Method&lt;/strong&gt;: Combines (a) hand-verifying tiny numerical examples, (b) coding minimal from-scratch NumPy/PyTorch baselines, and (c) diagnosing real training curves (overfitting, underfitting, gradient instability).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Progressive Dependency Graph&lt;/strong&gt;: Links Chapter 00’s math to Chapters 02–03’s core neural training mechanics, which then unlock CNNs, RNNs, Transformers, and generative models without conceptual gaps.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-designing-a-sanity-check-overfit-test-before-full-training&quot;&gt;Worked example: Designing a Sanity-Check Overfit Test Before Full Training&lt;/h3&gt;

&lt;p&gt;Before launching a 12-hour GPU run on 50,000 images, senior engineers always run a 30-second &lt;strong&gt;tiny-batch overfit check&lt;/strong&gt;. Suppose you have a 10-class classifier and select \(N = 8\) training examples.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Expected Initial Loss at Random Guessing&lt;/strong&gt;:
If initial logits are near \(0\), softmax predicts \(p_c \approx \frac{1}{10} = 0.1\) for every class. The expected initial cross-entropy loss is:
\(L_{\text{init}} = -\ln\!\left(\frac{1}{10}\right) = \ln(10) \approx 2.3026\)
    &lt;ul&gt;
      &lt;li&gt;&lt;em&gt;Diagnostic check&lt;/em&gt;: If your step-0 loss is \(18.4\) or \(0.01\) instead of \(\approx 2.30\), you immediately caught a weight-scale bug or label-encoding bug before wasting compute!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Run 100 Gradient Steps on Only Those 8 Examples&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Expected target: training loss should drop smoothly from \(2.30 \to &amp;lt; 0.05\) and training accuracy should hit \(8/8 = 100\%\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Interpret Failure&lt;/strong&gt;:
If the model cannot memorize 8 examples, no amount of data or regularization will save it—you have a broken gradient flow, wrong loss function (e.g., applying &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Softmax&lt;/code&gt; before &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.CrossEntropyLoss&lt;/code&gt;), or mismatched learning rate.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;applications-of-deep-learning&quot;&gt;Applications of Deep Learning&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/1/19/Deep_Learning_Applications.png/800px-Deep_Learning_Applications.png&quot; alt=&quot;Deep Learning Applications&quot; /&gt;
&lt;em&gt;Hình ảnh: Các ứng dụng của Deep Learning trong nhiều lĩnh vực. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;computer-vision&quot;&gt;Computer Vision&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Image classification&lt;/li&gt;
  &lt;li&gt;Object detection&lt;/li&gt;
  &lt;li&gt;Semantic segmentation&lt;/li&gt;
  &lt;li&gt;Face recognition&lt;/li&gt;
  &lt;li&gt;Image generation&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;natural-language-processing&quot;&gt;Natural Language Processing&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Machine translation&lt;/li&gt;
  &lt;li&gt;Sentiment analysis&lt;/li&gt;
  &lt;li&gt;Question answering&lt;/li&gt;
  &lt;li&gt;Text generation (GPT models)&lt;/li&gt;
  &lt;li&gt;Language understanding (BERT)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;speech-and-audio&quot;&gt;Speech and Audio&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Speech recognition&lt;/li&gt;
  &lt;li&gt;Text-to-speech synthesis&lt;/li&gt;
  &lt;li&gt;Music generation&lt;/li&gt;
  &lt;li&gt;Voice cloning&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;reinforcement-learning&quot;&gt;Reinforcement Learning&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Game playing (Chess, Go, Atari)&lt;/li&gt;
  &lt;li&gt;Robotics control&lt;/li&gt;
  &lt;li&gt;Autonomous driving&lt;/li&gt;
  &lt;li&gt;Resource optimization&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;healthcare&quot;&gt;Healthcare&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Disease diagnosis from images&lt;/li&gt;
  &lt;li&gt;Drug discovery&lt;/li&gt;
  &lt;li&gt;Protein folding (AlphaFold)&lt;/li&gt;
  &lt;li&gt;Personalized medicine&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;other-domains&quot;&gt;Other Domains&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Financial prediction&lt;/li&gt;
  &lt;li&gt;Recommendation systems&lt;/li&gt;
  &lt;li&gt;Climate modeling&lt;/li&gt;
  &lt;li&gt;Scientific discovery&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;challenges-and-limitations&quot;&gt;Challenges and Limitations&lt;/h2&gt;

&lt;h3 id=&quot;current-challenges&quot;&gt;Current Challenges&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Data Requirements&lt;/strong&gt;: Need large labeled datasets&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Computational Cost&lt;/strong&gt;: Training large models is expensive&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Interpretability&lt;/strong&gt;: “Black box” nature&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Generalization&lt;/strong&gt;: Overfitting, domain shift&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Robustness&lt;/strong&gt;: Adversarial examples&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Ethics&lt;/strong&gt;: Bias, fairness, privacy concerns&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;active-research-areas&quot;&gt;Active Research Areas&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Efficient Deep Learning&lt;/strong&gt;: Model compression, quantization&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Few-Shot Learning&lt;/strong&gt;: Learning from limited data&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Transfer Learning&lt;/strong&gt;: Leveraging pre-trained models&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Explainable AI&lt;/strong&gt;: Understanding model decisions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Continual Learning&lt;/strong&gt;: Learning without forgetting&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multimodal Learning&lt;/strong&gt;: Combining vision, language, etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;what-youll-learn-in-this-course&quot;&gt;What You’ll Learn in This Course&lt;/h2&gt;

&lt;h3 id=&quot;part-i-foundations-chapters-00-03&quot;&gt;Part I: Foundations (Chapters 00-03)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Mathematical prerequisites&lt;/li&gt;
  &lt;li&gt;Neural network basics&lt;/li&gt;
  &lt;li&gt;Training techniques (backpropagation, optimization)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;part-ii-core-architectures-chapters-04-08&quot;&gt;Part II: Core Architectures (Chapters 04-08)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;CNNs for computer vision&lt;/li&gt;
  &lt;li&gt;RNNs for sequences&lt;/li&gt;
  &lt;li&gt;Attention and Transformers&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;part-iii-advanced-topics-chapters-09-16&quot;&gt;Part III: Advanced Topics (Chapters 09-16)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Regularization and optimization&lt;/li&gt;
  &lt;li&gt;Generative models (VAE, GANs)&lt;/li&gt;
  &lt;li&gt;Transfer and self-supervised learning&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;part-iv-applications-chapters-17-25&quot;&gt;Part IV: Applications (Chapters 17-25)&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Computer vision applications&lt;/li&gt;
  &lt;li&gt;Natural language processing&lt;/li&gt;
  &lt;li&gt;Reinforcement learning&lt;/li&gt;
  &lt;li&gt;Specialized topics (GNNs, efficiency, interpretability)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;prerequisites-for-this-course&quot;&gt;Prerequisites for This Course&lt;/h2&gt;

&lt;h3 id=&quot;required&quot;&gt;Required&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Programming&lt;/strong&gt;: Python basics&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mathematics&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Linear algebra (vectors, matrices)&lt;/li&gt;
      &lt;li&gt;Calculus (derivatives, chain rule)&lt;/li&gt;
      &lt;li&gt;Probability (distributions, expectation)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Machine Learning&lt;/strong&gt;: Basic understanding helpful&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;recommended&quot;&gt;Recommended&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;Experience with NumPy, basic ML algorithms&lt;/li&gt;
  &lt;li&gt;Familiarity with Python ML libraries&lt;/li&gt;
  &lt;li&gt;Understanding of optimization concepts&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;how-to-succeed-in-deep-learning&quot;&gt;How to Succeed in Deep Learning&lt;/h2&gt;

&lt;h3 id=&quot;practical-tips&quot;&gt;Practical Tips&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Implement from Scratch&lt;/strong&gt;: Understand fundamentals&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Work with Frameworks&lt;/strong&gt;: Master PyTorch or TensorFlow&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Read Papers&lt;/strong&gt;: Stay current with research&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Do Projects&lt;/strong&gt;: Apply knowledge to real problems&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Join Community&lt;/strong&gt;: Participate in discussions, competitions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Iterate and Experiment&lt;/strong&gt;: Learning by doing&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;resources-beyond-this-course&quot;&gt;Resources Beyond This Course&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Papers&lt;/strong&gt;: ArXiv.org, Papers with Code&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Courses&lt;/strong&gt;: Fast.ai, Stanford CS231n/CS224n&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Books&lt;/strong&gt;: Deep Learning (Goodfellow), Dive into Deep Learning, Deep Learning Interviews (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) — optional practice track in &lt;strong&gt;01-98&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Competitions&lt;/strong&gt;: Kaggle, AIcrowd&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Communities&lt;/strong&gt;: Reddit r/MachineLearning, Discord servers&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;the-deep-learning-mindset&quot;&gt;The Deep Learning Mindset&lt;/h2&gt;

&lt;h3 id=&quot;key-principles&quot;&gt;Key Principles&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Start Simple&lt;/strong&gt;: Begin with basic models, add complexity&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Visualize&lt;/strong&gt;: Plot loss curves, attention maps, features&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Debug Systematically&lt;/strong&gt;: Check data, architecture, training&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Use Baselines&lt;/strong&gt;: Compare against simple models&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Monitor Metrics&lt;/strong&gt;: Track training and validation performance&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Be Patient&lt;/strong&gt;: Training takes time and iteration&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;common-pitfalls-to-avoid&quot;&gt;Common Pitfalls to Avoid&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;Insufficient data preprocessing&lt;/li&gt;
  &lt;li&gt;Poor initialization&lt;/li&gt;
  &lt;li&gt;Wrong learning rate&lt;/li&gt;
  &lt;li&gt;Ignoring validation set&lt;/li&gt;
  &lt;li&gt;Overfitting to training data&lt;/li&gt;
  &lt;li&gt;Not using proper evaluation metrics&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;the-road-ahead&quot;&gt;The Road Ahead&lt;/h2&gt;

&lt;p&gt;Deep learning is a rapidly evolving field. This course provides:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Solid foundations&lt;/strong&gt; in neural networks&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Practical skills&lt;/strong&gt; for implementing models&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Understanding&lt;/strong&gt; of modern architectures&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Preparation&lt;/strong&gt; for advanced research and applications&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By the end of this course, you’ll be equipped to:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Build and train neural networks from scratch&lt;/li&gt;
  &lt;li&gt;Apply deep learning to real-world problems&lt;/li&gt;
  &lt;li&gt;Read and implement research papers&lt;/li&gt;
  &lt;li&gt;Contribute to the field’s advancement&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s begin this exciting journey into deep learning! 🚀&lt;/p&gt;

&lt;h2 id=&quot;summary&quot;&gt;Summary&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Deep Learning&lt;/strong&gt;: Neural networks with multiple layers for hierarchical learning&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Revolution&lt;/strong&gt;: Transformed AI with breakthrough applications&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Core Idea&lt;/strong&gt;: Automatic feature learning from raw data&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Key Architectures&lt;/strong&gt;: MLPs, CNNs, RNNs, Transformers&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Applications&lt;/strong&gt;: Vision, NLP, speech, games, healthcare, and more&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Course Goal&lt;/strong&gt;: Master theory and practice of deep learning&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h2&gt;

&lt;p&gt;This introductory lesson establishes the foundational understanding needed for the deep learning journey ahead:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Core Concept&lt;/strong&gt;: Deep learning uses multi-layer neural networks to automatically learn hierarchical representations from data, eliminating the need for manual feature engineering.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Mathematical Foundation&lt;/strong&gt;: Neural networks are universal function approximators that learn through gradient descent and backpropagation, with depth providing exponential efficiency for compositional functions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Practical Power&lt;/strong&gt;: From MNIST digit recognition achieving 97%+ accuracy in minutes to modern systems surpassing human performance on complex tasks, deep learning has transformed AI from research curiosity to practical tool.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Historical Context&lt;/strong&gt;: The field evolved through AI winters and revivals, with key innovations (backpropagation, CNNs, Transformers) building on each other to create today’s powerful systems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Broader Connections&lt;/strong&gt;: Deep learning connects to classical ML, transfer learning, and the interplay of architecture, data, and compute that drives modern progress.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;6. Foundational Papers&lt;/strong&gt;: Understanding the historical development through seminal papers (McCulloch-Pitts neurons, backpropagation, LeNet, AlexNet, Transformers, ResNet) provides context for current practice.&lt;/p&gt;

&lt;h2 id=&quot;whats-next&quot;&gt;What’s Next?&lt;/h2&gt;

&lt;p&gt;In the next chapter, we’ll dive into &lt;strong&gt;Neural Networks Fundamentals&lt;/strong&gt; and understand how artificial neurons work together to learn from data. You’ll learn:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The mathematical model of artificial neurons (perceptrons)&lt;/li&gt;
  &lt;li&gt;How neurons combine into networks through layers&lt;/li&gt;
  &lt;li&gt;Activation functions and their role in enabling nonlinear learning&lt;/li&gt;
  &lt;li&gt;Forward propagation: how networks make predictions&lt;/li&gt;
  &lt;li&gt;The architecture choices that define different network types&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Armed with the conceptual understanding from this introduction and the detailed mechanics from the next chapter, you’ll be ready to understand training algorithms, implement your own networks, and appreciate the sophisticated architectures that power modern AI systems.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Remember&lt;/strong&gt;: Deep learning is fundamentally about letting data reveal its own structure rather than imposing our assumptions. This paradigm shift—from hand-crafted features to learned representations—is what makes deep learning both powerful and philosophically different from traditional approaches. As you progress through this course, you’ll see this principle manifest in countless ways across different domains and architectures.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [MIT Introduction to Deep Learning (2024)&lt;/td&gt;
          &lt;td&gt;6.S191](https://www.youtube.com/watch?v=ErnWZxJovaM) — Alexander Amini, English. How a serious intro course sequences prerequisites, loss, and training, matching this guide’s roadmap.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=qYNweeDHiyU&quot;&gt;AI, Machine Learning, Deep Learning and Generative AI Explained&lt;/a&gt; — IBM Technology, English. Use this to place the applications section (vision, language, generative models) before choosing a path through the chapters.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=zjkBMFhNj_g&quot;&gt;[1hr Talk] Intro to Large Language Models&lt;/a&gt; — Andrej Karpathy, English. The later chapters point at large language models; this talk is the map of that destination.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-00-02 First MNIST Walkthrough</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_00_02_First_MNIST_Walkthrough/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_00_02_First_MNIST_Walkthrough</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;MNIST is the “Hello, World!” of deep learning, yet treating it as a black-box copy-paste script hides the most valuable skill in the field: tracking tensor shapes, parameter counts, and memory budgets at every single line of a forward and backward pass.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-anatomy-of-your-first-end-to-end-neural-pipeline&quot;&gt;Key ideas: Anatomy of Your First End-to-End Neural Pipeline&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Tensor Shape Accounting (Input to Logits)&lt;/strong&gt;: Tracks exact dimensions—from image batch \((B, 1, 28, 28)\) through flattening \((B, 784)\) to hidden layers and class logits \((B, 10)\)—eliminating 90% of beginner runtime bugs.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter &amp;amp; Capacity Budgeting&lt;/strong&gt;: Counts exact weights and biases per &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Linear(in, out)&lt;/code&gt; layer as \((\text{in} \times \text{out}) + \text{out}\), revealing where memory and overfitting risk concentrate.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Four-Step PyTorch Training Loop&lt;/strong&gt;: Separates (1) zeroing stale gradients (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;zero_grad&lt;/code&gt;), (2) forward pass &amp;amp; loss computation, (3) reverse-mode autodiff (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss.backward&lt;/code&gt;), and (4) parameter update (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;optimizer.step&lt;/code&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluation Hygiene (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;eval()&lt;/code&gt; &amp;amp; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;no_grad()&lt;/code&gt;)&lt;/strong&gt;: Switches stochastic layers (Dropout, BatchNorm) to deterministic inference mode and disables autograd graph construction to prevent memory leaks during validation.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-exact-tensor-shapes-and-parameter-count-for-a-3-layer-mnist-mlp&quot;&gt;Worked example: Exact Tensor Shapes and Parameter Count for a 3-Layer MNIST MLP&lt;/h3&gt;

&lt;p&gt;Consider the classic MNIST MLP architecture: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;784 -&amp;gt; 256 -&amp;gt; 128 -&amp;gt; 10&lt;/code&gt; trained with mini-batch size \(B = 64\) in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt; (4 bytes per number).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Trace Tensor Shapes Through One Forward Pass&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Raw batch from DataLoader: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64, 1, 28, 28)&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;After &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;view(64, -1)&lt;/code&gt; flatten: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64, 784)&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;After Layer 1 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(784, 256)&lt;/code&gt; + ReLU): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64, 256)&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;After Layer 2 (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(256, 128)&lt;/code&gt; + ReLU): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64, 128)&lt;/code&gt;&lt;/li&gt;
      &lt;li&gt;After Output Layer (&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Linear(128, 10)&lt;/code&gt;): &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(64, 10)&lt;/code&gt; (raw logits, no softmax needed before &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.CrossEntropyLoss&lt;/code&gt;).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Count Exact Trainable Parameters&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Layer 1: \(784 \times 256 + 256 = 200{,}704 + 256 = 200{,}960\)&lt;/li&gt;
      &lt;li&gt;Layer 2: \(256 \times 128 + 128 = 32{,}768 + 128 = 32{,}896\)&lt;/li&gt;
      &lt;li&gt;Layer 3: \(128 \times 10 + 10 = 1{,}280 + 10 = 1{,}290\)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Total parameters&lt;/strong&gt;: \(200{,}960 + 32{,}896 + 1{,}290 = 235{,}146\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Memory Footprint Check&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Parameters alone in &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;float32&lt;/code&gt;: \(235{,}146 \times 4\text{ bytes} = 940{,}584\text{ bytes} \approx 0.90\text{ MB}\).&lt;/li&gt;
      &lt;li&gt;Notice that &lt;strong&gt;85.5%&lt;/strong&gt; (\(200{,}960 / 235{,}146\)) of all parameters live in the very first layer because flattening a 2D image ignores spatial locality—a direct preview of why Convolutional Neural Networks (CNNs) were invented!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;4-code-snippet&quot;&gt;4. Code Snippet&lt;/h2&gt;

&lt;p&gt;Let’s implement a simple deep learning example to make concepts concrete. We’ll build a neural network to classify MNIST digits using PyTorch.&lt;/p&gt;

&lt;div class=&quot;language-python highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.nn&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.optim&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torchvision&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;
&lt;span class=&quot;kn&quot;&gt;from&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch.utils.data&lt;/span&gt; &lt;span class=&quot;kn&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;DataLoader&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Define a simple deep neural network
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleDeepNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;Module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;
    A 3-layer neural network for MNIST digit classification.
    
    Architecture:
    - Input: 784 dimensions (28x28 flattened image)
    - Hidden Layer 1: 128 neurons with ReLU activation
    - Hidden Layer 2: 64 neurons with ReLU activation  
    - Output Layer: 10 neurons (one per digit class)
    &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;SimpleDeepNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;__init__&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# First hidden layer
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;128&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    &lt;span class=&quot;c1&quot;&gt;# Second hidden layer
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fc3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Linear&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;10&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;     &lt;span class=&quot;c1&quot;&gt;# Output layer
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;relu&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ReLU&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
    &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;forward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Flatten the 28x28 images to 784-dimensional vectors
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;view&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;784&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Layer 1: Learn low-level features
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Layer 2: Learn mid-level feature combinations
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;relu&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Output layer: Classify into 10 digit classes
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;fc3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Load MNIST dataset
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Compose&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;ToTensor&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;transforms&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Normalize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.1307&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,),&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.3081&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,))&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Normalize with MNIST mean/std
&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;download&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;datasets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;MNIST&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;./data&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;transform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;64&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;True&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;DataLoader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_size&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1000&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;shuffle&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;bp&quot;&gt;False&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Initialize model, loss function, and optimizer
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;SimpleDeepNet&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;nn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;CrossEntropyLoss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Combines softmax + negative log likelihood
&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optim&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;Adam&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;parameters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(),&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lr&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mf&quot;&gt;0.001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Training loop
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Set model to training mode
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;total_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;enumerate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;# Forward pass: compute predictions
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Backward pass: compute gradients
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;zero_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Clear previous gradients
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;backward&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;        &lt;span class=&quot;c1&quot;&gt;# Backpropagation
&lt;/span&gt;        
        &lt;span class=&quot;c1&quot;&gt;# Update weights
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;step&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;c1&quot;&gt;# Track accuracy
&lt;/span&gt;        &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;total_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
        
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Batch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;batch_idx&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;
                  &lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Loss: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;loss&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;total_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Epoch &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; Training: Avg Loss=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;avg_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Accuracy=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Evaluation loop
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eval&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Set model to evaluation mode
&lt;/span&gt;    &lt;span class=&quot;n&quot;&gt;test_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    
    &lt;span class=&quot;k&quot;&gt;with&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;torch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;no_grad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Disable gradient computation for efficiency
&lt;/span&gt;        &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;test_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;output&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;argmax&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dim&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;eq&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;target&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;().&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    
    &lt;span class=&quot;n&quot;&gt;test_loss&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mf&quot;&gt;100.&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;correct&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dataset&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Test: Avg Loss=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_loss&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;, Accuracy=&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\n&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&apos;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;accuracy&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Train for multiple epochs
&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Starting training...&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt; &lt;span class=&quot;ow&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;range&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;6&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# Train for 5 epochs
&lt;/span&gt;    &lt;span class=&quot;nf&quot;&gt;train&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;train_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;optimizer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;epoch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;test_accuracy&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;test&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;model&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;test_loader&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;criterion&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sa&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Final test accuracy: &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;{&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;test_accuracy&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;%&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;Training complete! The network learned to recognize digits through:&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;1. Forward propagation (making predictions)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;2. Loss computation (measuring errors)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;3. Backpropagation (computing gradients)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;4. Weight updates (learning from mistakes)&lt;/span&gt;&lt;span class=&quot;sh&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;understanding-the-code&quot;&gt;Understanding the Code&lt;/h3&gt;

&lt;p&gt;This simple example demonstrates core deep learning principles:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Architecture Design&lt;/strong&gt;: Three layers transform 784-dimensional input to 10-dimensional output through learned representations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Automatic Feature Learning&lt;/strong&gt;: We never told the network what features to look for—it discovers useful representations automatically.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. The Training Loop&lt;/strong&gt;: The standard pattern of forward pass → compute loss → backpropagate → update weights that underlies all deep learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Nonlinearity is Crucial&lt;/strong&gt;: ReLU activation functions between layers enable learning complex, nonlinear functions. Without them, multiple layers would collapse to a single linear transformation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;5. Scalability&lt;/strong&gt;: This same code structure, with appropriate modifications, works for much larger datasets and more complex tasks—computer vision, natural language processing, etc.&lt;/p&gt;

&lt;p&gt;After just 5 epochs (5 passes through 60,000 training images), this simple network typically achieves ~97% accuracy—demonstrating deep learning’s power to learn from data.&lt;/p&gt;

&lt;h2 id=&quot;5-related-concepts&quot;&gt;5. Related Concepts&lt;/h2&gt;

&lt;p&gt;Understanding deep learning requires seeing how it connects to broader machine learning and AI concepts:&lt;/p&gt;

&lt;h3 id=&quot;supervised-vs-unsupervised-vs-reinforcement-learning&quot;&gt;Supervised vs Unsupervised vs Reinforcement Learning&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Supervised Learning&lt;/strong&gt; (what we’ve primarily discussed) learns from labeled examples: input-output pairs like (image, label) or (sentence, translation). The network learns to map inputs to correct outputs.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Unsupervised Learning&lt;/strong&gt; discovers structure in data without labels. Autoencoders learn compressed representations. Clustering groups similar examples. Generative models learn data distributions to create new samples. These techniques are crucial when labels are expensive or unavailable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reinforcement Learning&lt;/strong&gt; learns from interaction: an agent takes actions in an environment, receives rewards, and learns policies to maximize cumulative reward. This enables learning behaviors (game playing, robotics) where we can’t provide explicit correct actions for every situation, only feedback on outcomes.&lt;/p&gt;

&lt;p&gt;Deep learning has transformed all three paradigms, but the principles differ significantly. This course focuses primarily on supervised learning initially, with later chapters covering unsupervised and reinforcement learning.&lt;/p&gt;

&lt;h3 id=&quot;classical-machine-learning-vs-deep-learning&quot;&gt;Classical Machine Learning vs Deep Learning&lt;/h3&gt;

&lt;p&gt;Traditional machine learning (SVMs, decision trees, logistic regression) typically requires:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Hand-engineered features&lt;/li&gt;
  &lt;li&gt;Explicit model assumptions (linearity, independence)&lt;/li&gt;
  &lt;li&gt;Works well with moderate data (hundreds to thousands of examples)&lt;/li&gt;
  &lt;li&gt;More interpretable (feature importance, decision boundaries)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Deep learning:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Learns features automatically end-to-end&lt;/li&gt;
  &lt;li&gt;Fewer assumptions about data structure&lt;/li&gt;
  &lt;li&gt;Requires large datasets (thousands to millions of examples)&lt;/li&gt;
  &lt;li&gt;Less interpretable but more powerful for complex patterns&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Neither approach is universally superior—classical ML can be better for small datasets, tabular data, or when interpretability is critical. Deep learning excels with large datasets, high-dimensional inputs (images, text), and complex patterns.&lt;/p&gt;

&lt;h3 id=&quot;transfer-learning-and-pre-training&quot;&gt;Transfer Learning and Pre-training&lt;/h3&gt;

&lt;p&gt;One of deep learning’s most powerful techniques is &lt;strong&gt;transfer learning&lt;/strong&gt;: training a network on one task (e.g., ImageNet classification) then adapting it to related tasks (medical image analysis, wildlife detection). The network’s learned representations—edge detectors, texture patterns, shape recognizers—transfer across domains.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pre-training&lt;/strong&gt; on large general datasets, then &lt;strong&gt;fine-tuning&lt;/strong&gt; on specific tasks, has become standard practice. GPT, BERT, and other large language models are pre-trained on massive text corpora, then specialized for particular applications through fine-tuning with much less task-specific data. This dramatically reduces data requirements for new tasks.&lt;/p&gt;

&lt;h3 id=&quot;the-role-of-architecture-vs-data-vs-compute&quot;&gt;The Role of Architecture vs Data vs Compute&lt;/h3&gt;

&lt;p&gt;Deep learning’s success derives from three factors working together:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Architecture innovations&lt;/strong&gt; (CNNs, Transformers, ResNets) enable learning certain patterns efficiently. The right architecture provides appropriate inductive biases for the problem structure.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Data scale&lt;/strong&gt; provides the raw material for learning. More diverse, high-quality data enables networks to learn more robust, generalizable representations.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Computational scale&lt;/strong&gt; makes training large networks on large datasets practical. GPUs parallelize the matrix operations neural networks depend on, reducing training time from months to hours.&lt;/p&gt;

&lt;p&gt;Modern deep learning progress comes from advances in all three: better architectures (Transformers), larger datasets (web-scale text and images), and more compute (GPU clusters, TPUs). No single factor alone explains the field’s success.&lt;/p&gt;

&lt;h2 id=&quot;6-fundamental-papers&quot;&gt;6. Fundamental Papers&lt;/h2&gt;

&lt;p&gt;Understanding deep learning’s historical development through key papers provides context for current practice and future directions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://link.springer.com/article/10.1007/BF02478259&quot;&gt;“A Logical Calculus of Ideas Immanent in Nervous Activity” (1943)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Warren McCulloch and Walter Pitts&lt;br /&gt;
This foundational paper introduced the mathematical model of artificial neurons, showing that networks of simple threshold units could compute any logical function. While vastly simplified compared to biological neurons, this work established the theoretical basis for neural computation and inspired subsequent research in both neuroscience and artificial intelligence.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://www.nature.com/articles/323533a0&quot;&gt;“Learning representations by back-propagating errors” (1986)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: David Rumelhart, Geoffrey Hinton, Ronald Williams&lt;br /&gt;
Backpropagation wasn’t invented here (it was discovered independently multiple times), but this paper brought it to widespread attention and demonstrated its power for training multi-layer networks. By showing how to efficiently compute gradients through composition of functions via the chain rule, backpropagation made deep learning practical. This paper ended the first AI winter by proving that neural networks could learn complex functions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;http://yann.lecun.com/exdb/publis/pdf/lecun-01a.pdf&quot;&gt;“Gradient-Based Learning Applied to Document Recognition” (1998)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Yann LeCun, Léon Bottou, Yoshua Bengio, Patrick Haffner&lt;br /&gt;
LeNet-5, introduced in this paper, demonstrated that convolutional neural networks could achieve excellent performance on real-world tasks (check reading, digit recognition). More importantly, it established design principles—local connectivity, weight sharing, pooling—that remain central to modern computer vision. This paper showed that deep learning could move from toy problems to practical applications.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks&quot;&gt;“ImageNet Classification with Deep Convolutional Neural Networks” (2012)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Alex Krizhevsky, Ilya Sutskever, Geoffrey Hinton&lt;br /&gt;
AlexNet’s crushing victory in the 2012 ImageNet competition (15.3% error vs 26.2% for second place) sparked the modern deep learning revolution. By combining deeper architectures, ReLU activations, dropout regularization, and GPU training, it demonstrated that neural networks could scale to large, complex datasets. This success convinced the broader computer vision community to adopt deep learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1706.03762&quot;&gt;“Attention Is All You Need” (2017)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Ashish Vaswani et al. (Google)&lt;br /&gt;
The Transformer architecture introduced here has become the foundation of modern NLP and increasingly other domains. By replacing recurrence with attention mechanisms, Transformers enable full parallelization during training and better capture long-range dependencies. This paper’s influence extends far beyond its original machine translation application—BERT, GPT, and most recent large language models build on this architecture.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href=&quot;https://arxiv.org/abs/1512.03385&quot;&gt;“Deep Residual Learning for Image Recognition” (2016)&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;
&lt;em&gt;Authors&lt;/em&gt;: Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun&lt;br /&gt;
ResNet introduced skip connections that enabled training networks hundreds of layers deep by providing direct gradient pathways. Beyond winning ImageNet 2015, this work fundamentally changed how we think about deep architectures—depth is crucial, but networks need architectural innovations (skip connections, careful normalization) to train effectively. ResNet’s principles appear in most modern deep architectures.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=gBw0u_5u0qU&quot;&gt;PyTorch Course (2022), Part 4: Image Classification (MNIST)&lt;/a&gt; — Mr. P Solver, English. If you are about to run the MNIST training loop the lesson sketches.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. The handwritten-digit network is the conceptual model behind that loop.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Lecture 4&lt;/td&gt;
          &lt;td&gt;Introduction to Neural Networks](https://www.youtube.com/watch?v=d14TUNcbn1k) — Stanford University School of Engineering, English. Stanford’s neural-net lecture puts the same classifier in the language of the later math lessons.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>01-00-01 What Is Deep Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_00_01_What_Is_Deep_Learning/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter01/01_00_01_What_Is_Deep_Learning</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;When AlexNet crushed the 2012 ImageNet competition by more than 10 percentage points, it wasn’t because researchers suddenly discovered a secret equation—backpropagation was already 26 years old. What changed was realizing that compositional depth turns exponentially complex patterns into a sequence of simple, learnable geometric warps.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-what-defines-deep-learning-mathematically&quot;&gt;Key ideas: What Defines Deep Learning Mathematically&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;AI vs. Machine Learning vs. Deep Learning&lt;/strong&gt;: Nests deep learning as the subfield of representation learning that uses multi-layer parameterized compositions rather than shallow fixed-basis models (SVMs, linear regression, decision trees).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Universal Approximation Theorem (Expressive Power)&lt;/strong&gt;: Proves that even a single sufficiently wide hidden layer with a non-polynomial activation can approximate any continuous function on a compact domain—establishing &lt;em&gt;existence&lt;/em&gt;, though not &lt;em&gt;efficiency&lt;/em&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Depth Efficiency (Compositional Advantage)&lt;/strong&gt;: Shows that deep networks can represent hierarchical functions with exponentially fewer parameters than shallow networks by reusing shared intermediate sub-features across layers.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Empirical Risk Minimization (ERM)&lt;/strong&gt;: Formalizes learning as minimizing \(\hat{R}(\theta) = \frac{1}{N}\sum_{i=1}^N \mathcal{L}(f_\theta(x_i), y_i) + \lambda \Omega(\theta)\) over parameters \(\theta\) via stochastic gradient optimization.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-counting-linear-regions-to-see-why-depth-beats-width&quot;&gt;Worked example: Counting Linear Regions to See Why Depth Beats Width&lt;/h3&gt;

&lt;p&gt;A ReLU network partitions its input space into piecewise linear regions. With a budget of \(K = 6\) hidden ReLU neurons on a 1D input \(x \in \mathbb{R}\), compare a &lt;strong&gt;shallow&lt;/strong&gt; (1 layer of 6 neurons) vs. a &lt;strong&gt;deep&lt;/strong&gt; (3 layers of 2 neurons each) network.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Shallow Network (1 Layer, Width \(n = 6\))&lt;/strong&gt;:
Each 1D ReLU neuron introduces at most \(1\) hinge (breakpoint) on the real line. Six hinges divide \(\mathbb{R}\) into at most:
\(R_{\text{shallow}} = 6 + 1 = 7\text{ linear regions}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Deep Network (3 Layers, Width \(n = 2\) per Layer)&lt;/strong&gt;:
A 2-neuron layer can fold the real line in half (creating a sawtooth map like \(g(x) = \text{ReLU}(2x) - \text{ReLU}(4x - 2)\), which doubles the number of pieces at every layer!). Composing \(L = 3\) such layers multiplies the region count:
\(R_{\text{deep}} = 2^3 = 8\text{ linear regions}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Scaling to \(K = 20\) Neurons (Width 20 vs. 10 Layers of Width 2)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Shallow: \(R_{\text{shallow}} = 20 + 1 = 21\) regions.&lt;/li&gt;
      &lt;li&gt;Deep: \(R_{\text{deep}} = 2^{10} = 1{,}024\) regions—nearly \(50\times\) more expressive pieces using the exact same number of neurons! That exponential factor \(2^L\) vs. linear \(n\) is the mathematical heartbeat of &lt;em&gt;deep&lt;/em&gt; learning.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;introduction-to-deep-learning&quot;&gt;Introduction to Deep Learning&lt;/h1&gt;

&lt;h2 id=&quot;1-concept-overview&quot;&gt;1. Concept Overview&lt;/h2&gt;

&lt;p&gt;&lt;img src=&quot;https://upload.wikimedia.org/wikipedia/commons/thumb/3/32/AI-ML-DL.svg/800px-AI-ML-DL.svg.png&quot; alt=&quot;Deep Learning Hierarchy&quot; /&gt;
&lt;em&gt;Hình ảnh: Mối quan hệ giữa AI, Machine Learning và Deep Learning. Nguồn: Wikimedia Commons&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Deep Learning represents one of the most transformative technological advances of the 21st century. At its core, &lt;strong&gt;deep learning&lt;/strong&gt; is a subset of machine learning that uses artificial neural networks with multiple layers—hence “deep”—to automatically learn hierarchical representations of data. What makes deep learning revolutionary is not just that it works, but how fundamentally it changes our approach to building intelligent systems.&lt;/p&gt;

&lt;p&gt;To truly understand deep learning’s significance, we must appreciate what preceded it. Traditional machine learning required human experts to manually engineer features—the relevant patterns or characteristics that algorithms would use to make decisions. For image recognition, this meant designing edge detectors, texture analyzers, and shape descriptors by hand. For speech recognition, it meant crafting phoneme representations and acoustic models based on linguistic theory. This feature engineering was both an art and a science, requiring deep domain expertise and often years of iterative refinement.&lt;/p&gt;

&lt;p&gt;Deep learning eliminates this bottleneck through &lt;strong&gt;representation learning&lt;/strong&gt;—the ability to automatically discover the representations needed for detection or classification directly from raw data. A deep neural network learns features at multiple levels of abstraction: in computer vision, the first layer might learn to detect edges, the second layer combines edges into simple shapes, the third layer assembles shapes into object parts, and deeper layers recognize complete objects. Critically, the network discovers these hierarchical features on its own, without human guidance beyond providing the training data and the learning objective.&lt;/p&gt;

&lt;p&gt;This automatic feature learning has profound implications. It means deep learning can tackle problems where we don’t know how to manually engineer good features. It means the same basic architecture—with appropriate modifications—can excel at diverse tasks: recognizing faces, translating languages, generating images, playing games, or folding proteins. It means that as we collect more data and apply more computation, performance continues to improve, rather than plateauing as it often does with carefully hand-tuned classical systems.&lt;/p&gt;

&lt;h3 id=&quot;key-characteristics-of-deep-learning&quot;&gt;Key Characteristics of Deep Learning&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;1. Hierarchical Feature Learning&lt;/strong&gt;: Deep networks learn features at multiple levels of abstraction. Low-level layers capture simple patterns (edges, colors, basic phonemes), while higher layers combine these into complex concepts (objects, faces, semantic meanings). This hierarchy mirrors how we believe biological vision and cognition work—building understanding layer by layer from simple to complex.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. End-to-End Learning&lt;/strong&gt;: Rather than building modular pipelines where each component is optimized separately, deep learning enables end-to-end optimization where the entire system learns jointly. For machine translation, instead of separate modules for parsing, alignment, and generation, a single neural network learns to map source language to target language directly, with all components optimized together toward the final translation quality.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Scalability with Data and Computation&lt;/strong&gt;: Traditional machine learning often exhibits diminishing returns—adding more data beyond a certain point provides little benefit. Deep learning’s performance continues to improve with more data and more computation, a scaling property that has driven the revolution in large language models and computer vision systems. This scalability is both a strength (enabling superhuman performance on many tasks) and a challenge (requiring massive datasets and computational resources).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;4. Distributed Representations&lt;/strong&gt;: Deep networks learn to represent concepts as patterns of activation across many neurons, rather than having dedicated neurons for each concept. This enables generalization: knowledge about “dogs” can inform understanding of “wolves” because they share many representational features. It also provides robustness: if some neurons fail or are dropped out during training, the distributed representation still functions.&lt;/p&gt;

&lt;h3 id=&quot;why-deep-learning-matters&quot;&gt;Why Deep Learning Matters&lt;/h3&gt;

&lt;p&gt;The impact of deep learning extends far beyond academic curiosity. It has fundamentally changed multiple industries and aspects of daily life:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Computer Vision&lt;/strong&gt;: From barely functional digit recognition in the 1990s to systems that surpass human performance on many visual tasks, recognize thousands of object categories, generate photorealistic images, and enable autonomous vehicles.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Natural Language Processing&lt;/strong&gt;: From rigid rule-based systems to neural language models that can write essays, answer questions, translate between languages with near-human quality, and engage in coherent dialogue.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Healthcare&lt;/strong&gt;: From slow, error-prone manual diagnosis to AI systems that detect diseases from medical images with expert-level accuracy, predict patient outcomes, accelerate drug discovery, and personalize treatment plans.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Scientific Discovery&lt;/strong&gt;: From traditional hypothesis-driven research to AI systems that discover novel materials, predict protein structures (AlphaFold solving a 50-year grand challenge), generate hypotheses from literature, and design experiments.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Perhaps most importantly, deep learning has democratized AI. Open-source frameworks like PyTorch and TensorFlow, pre-trained models available freely, and educational resources have made powerful AI accessible to anyone with a laptop and curiosity. This democratization accelerates innovation as millions of researchers and developers worldwide contribute to advancing the field.&lt;/p&gt;

&lt;h2 id=&quot;2-mathematical-foundation&quot;&gt;2. Mathematical Foundation&lt;/h2&gt;

&lt;p&gt;At its mathematical core, deep learning is about &lt;strong&gt;function approximation&lt;/strong&gt;. Given training data \(\{(\mathbf{x}_1, y_1), (\mathbf{x}_2, y_2), \ldots, (\mathbf{x}_n, y_n)\}\) where \(\mathbf{x}_i\) are inputs (images, text, sensor readings) and \(y_i\) are desired outputs (labels, translations, actions), we want to find a function \(f_\theta\) parameterized by \(\theta\) that accurately maps inputs to outputs.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_function_approx_title.jpg&quot; alt=&quot;Neural net = function approximator&quot; /&gt;
&lt;em&gt;Figure: The neural “black box” is really fitting a curve \(y = f(x)\) from data. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_overview_network_vs_curve.jpg&quot; alt=&quot;Overview: network vs target curve&quot; /&gt;
&lt;em&gt;Figure: The same network, given different \(x\), traces points on a complex curve. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Linear → nonlinear intuition.&lt;/strong&gt; Linear regression \(f(x)=xw+b\) only draws straight lines; for wavy data it is &lt;strong&gt;not enough&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_linear_regression_formula.jpg&quot; alt=&quot;Linear regression formula&quot; /&gt;
&lt;em&gt;Figure: A linear neuron is an extension of \(f(x)=xw+b\). (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_linear_fails_nonlinear.jpg&quot; alt=&quot;Linear model fails on nonlinear data&quot; /&gt;
&lt;em&gt;Figure: Linear models are limited — they cannot fit complex curves. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;With nonlinear activations (e.g. sigmoid-like), a network can fit soft shapes:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_sigmoid_curve_fit.jpg&quot; alt=&quot;Sigmoid-like curve fit&quot; /&gt;
&lt;em&gt;Figure: An example “soft” function a model can approximate. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;h3 id=&quot;the-universal-approximation-theorem&quot;&gt;The Universal Approximation Theorem&lt;/h3&gt;

&lt;p&gt;A fundamental theoretical result states that a neural network with even a single hidden layer containing sufficiently many neurons can approximate any continuous function to arbitrary accuracy. Mathematically, for any continuous function \(g: \mathbb{R}^n \to \mathbb{R}^m\) and any \(\epsilon &amp;gt; 0\), there exists a neural network \(f_\theta\) such that:&lt;/p&gt;

\[\|f_\theta(\mathbf{x}) - g(\mathbf{x})\| &amp;lt; \epsilon \quad \text{for all } \mathbf{x}\]

&lt;p&gt;This is remarkable: neural networks are &lt;strong&gt;universal function approximators&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/deep-learning-self-learning/img/chapter_img/chapter01/nn_conclusion_universal_approx.jpg&quot; alt=&quot;Conclusion: universal function approximator&quot; /&gt;
&lt;em&gt;Figure: Core takeaway — neural nets are universal function approximators. (Illustration from a video on the nature of neural nets)&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;However, this theorem has important caveats. It guarantees existence but not learnability—finding the parameters \(\theta\) through gradient descent is not guaranteed. It requires potentially exponentially many neurons in the hidden layer, which is impractical. And it applies to shallow networks, but doesn’t explain why deep networks work better in practice.&lt;/p&gt;

&lt;h3 id=&quot;why-depth-matters&quot;&gt;Why Depth Matters&lt;/h3&gt;

&lt;p&gt;While shallow networks are theoretically sufficient, &lt;strong&gt;deep networks&lt;/strong&gt; are exponentially more efficient for many real-world functions. Consider representing a function with \(k\) levels of composition: \(f = f_k \circ f_{k-1} \circ \cdots \circ f_1\). A shallow network might need exponentially many neurons to represent this, while a deep network with \(k\) layers can represent it naturally with polynomial complexity.&lt;/p&gt;

&lt;p&gt;The mathematical intuition is that many functions in nature exhibit compositional structure. To recognize a face, we first detect edges, then combine edges into facial features (eyes, nose, mouth), then combine features into a face representation. This hierarchical composition is naturally expressed as successive transformations through layers:&lt;/p&gt;

&lt;p&gt;\(\mathbf{h}^{(1)} = \sigma(\mathbf{W}^{(1)}\mathbf{x} + \mathbf{b}^{(1)})\)
\(\mathbf{h}^{(2)} = \sigma(\mathbf{W}^{(2)}\mathbf{h}^{(1)} + \mathbf{b}^{(2)})\)
\(\vdots\)
\(\mathbf{y} = \mathbf{W}^{(L)}\mathbf{h}^{(L-1)} + \mathbf{b}^{(L)}\)&lt;/p&gt;

&lt;p&gt;where \(\sigma\) is a nonlinear activation function (ReLU, sigmoid, tanh), \(\mathbf{W}^{(l)}\) are weight matrices, and \(\mathbf{b}^{(l)}\) are bias vectors at layer \(l\).&lt;/p&gt;

&lt;h3 id=&quot;the-learning-objective&quot;&gt;The Learning Objective&lt;/h3&gt;

&lt;p&gt;Training a neural network means finding parameters \(\theta = \{\mathbf{W}^{(1)}, \mathbf{b}^{(1)}, \ldots, \mathbf{W}^{(L)}, \mathbf{b}^{(L)}\}\) that minimize a loss function \(\mathcal{L}(\theta)\) measuring prediction error:&lt;/p&gt;

\[\theta^* = \arg\min_\theta \frac{1}{n}\sum_{i=1}^n \mathcal{L}(f_\theta(\mathbf{x}_i), y_i)\]

&lt;p&gt;For classification, we typically use cross-entropy loss:
\(\mathcal{L}(\hat{\mathbf{y}}, \mathbf{y}) = -\sum_j y_j \log \hat{y}_j\)&lt;/p&gt;

&lt;p&gt;For regression, mean squared error:
\(\mathcal{L}(\hat{y}, y) = \frac{1}{2}(y - \hat{y})^2\)&lt;/p&gt;

&lt;p&gt;We optimize this via &lt;strong&gt;gradient descent&lt;/strong&gt;: iteratively updating parameters in the direction that decreases loss:&lt;/p&gt;

\[\theta \leftarrow \theta - \eta \nabla_\theta \mathcal{L}(\theta)\]

&lt;p&gt;where \(\eta\) is the learning rate. Computing gradients efficiently through backpropagation—applying the chain rule layer by layer—is what makes training deep networks practical.&lt;/p&gt;

&lt;h3 id=&quot;why-it-works-the-bias-variance-tradeoff&quot;&gt;Why It Works: The Bias-Variance Tradeoff&lt;/h3&gt;

&lt;p&gt;Deep learning’s success can be understood through the classical bias-variance tradeoff. High bias (underfitting) means the model can’t capture the data’s complexity. High variance (overfitting) means the model fits noise rather than true patterns. Deep networks have enormous capacity (low bias) but are surprisingly resistant to overfitting when properly regularized, achieving low variance despite having millions of parameters—often more parameters than training examples!&lt;/p&gt;

&lt;p&gt;This seems to violate classical statistical learning theory, which suggests models should be simpler than the data. Recent theoretical work on “double descent” and “implicit regularization” shows that overparameterized networks trained with gradient descent implicitly prefer simpler functions, providing a form of automatic regularization that classical theory didn’t account for.&lt;/p&gt;

&lt;h2 id=&quot;3-example--intuition&quot;&gt;3. Example / Intuition&lt;/h2&gt;

&lt;p&gt;To develop intuition for how deep learning works, let’s walk through a concrete example: teaching a network to recognize handwritten digits.&lt;/p&gt;

&lt;h3 id=&quot;the-problem-mnist-digit-recognition&quot;&gt;The Problem: MNIST Digit Recognition&lt;/h3&gt;

&lt;p&gt;Imagine you have 28×28 pixel grayscale images of handwritten digits (0-9), and you want a system that can correctly identify which digit is in each image. Each image is just a 784-dimensional vector (28×28 = 784 pixels, each with intensity 0-255).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Traditional Approach&lt;/strong&gt;: You might manually design features:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Count loops (0, 6, 8, 9 have loops; 1, 7 don’t)&lt;/li&gt;
  &lt;li&gt;Detect vertical/horizontal strokes&lt;/li&gt;
  &lt;li&gt;Measure height-to-width ratios&lt;/li&gt;
  &lt;li&gt;Identify endpoints and intersections&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This requires deep expertise and doesn’t generalize well (what about cursive? different fonts?).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Deep Learning Approach&lt;/strong&gt;: Feed the 784 pixel values directly into a neural network:&lt;/p&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Input (784 pixels) → Hidden Layer 1 (128 neurons) → Hidden Layer 2 (64 neurons) → Output (10 classes)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The network automatically learns:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Layer 1&lt;/strong&gt; discovers edge detectors—neurons that activate for vertical lines, horizontal lines, curves at different positions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Layer 2&lt;/strong&gt; combines edges into stroke patterns—long vertical strokes (for 1, 7), circular shapes (for 0, 6, 8, 9), specific curve combinations&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Output layer&lt;/strong&gt; combines these patterns to recognize complete digits&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;how-learning-happens-an-intuitive-example&quot;&gt;How Learning Happens: An Intuitive Example&lt;/h3&gt;

&lt;p&gt;Initially, weights are random. When shown a “3”:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Forward pass&lt;/strong&gt;: Network makes a random prediction, say 70% confident it’s a “7”&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute error&lt;/strong&gt;: True label is “3”, prediction was “7”—big error!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Backward pass (backpropagation)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Output layer: “I should have activated neuron 3 more and neuron 7 less”&lt;/li&gt;
      &lt;li&gt;Hidden layers: “Which of my activations contributed to the wrong prediction? Adjust weights to fix this”&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Update weights&lt;/strong&gt;: Slightly modify all weights to reduce this particular error&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Repeat&lt;/strong&gt;: After seeing thousands of “3”s with various handwriting styles, the network learns the essential features of “3”-ness&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The magic is that this simple process—forward pass, compute error, backpropagate, update—when repeated millions of times, discovers the hierarchical features needed for recognition.&lt;/p&gt;

&lt;h3 id=&quot;why-hierarchical-learning-matters&quot;&gt;Why Hierarchical Learning Matters&lt;/h3&gt;

&lt;p&gt;Consider recognizing a face:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Low-level features&lt;/strong&gt; (Layer 1): Edge detectors at various orientations, color blobs&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mid-level features&lt;/strong&gt; (Layer 2-3): Combine edges into simple shapes—curves, corners, textures&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;High-level features&lt;/strong&gt; (Layer 4-5): Combine shapes into facial features—eyes (pair of dark circles with highlights), nose (triangular region with shadows), mouth (horizontal dark region, possibly with teeth)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Complete concept&lt;/strong&gt; (Output): Combine facial features into specific face identities&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Each layer learns increasingly abstract representations, naturally capturing the compositional nature of visual recognition. The network discovers that eyes, noses, and mouths are reusable components that appear in all faces, just as strokes and curves are reusable components in all digits.&lt;/p&gt;

&lt;p&gt;This hierarchical, distributed representation also explains deep learning’s sample efficiency. Once the network learns “edge detector” and “circle detector” neurons from seeing digits, these same neurons help recognize letters, faces, and objects—transfer learning happens naturally through shared low-level features.&lt;/p&gt;

&lt;!-- video-references --&gt;

&lt;h2 id=&quot;video-references&quot;&gt;Video references&lt;/h2&gt;

&lt;p&gt;Some figures in this lesson are screenshots from the following videos (Machine Learning Thực Chiến). URLs kept for attribution and further viewing:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.facebook.com/reel/720970114372332&quot;&gt;Neural nets as function approximators&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [But what is a neural network?&lt;/td&gt;
          &lt;td&gt;Deep learning chapter 1](https://www.youtube.com/watch?v=aircAruvnKk) — 3Blue1Brown, English. Layered neurons as a function approximator are the definition this lesson builds.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=CqOfi41LfDw&quot;&gt;The Essential Main Ideas of Neural Networks&lt;/a&gt; — StatQuest with Josh Starmer, English. A slower pass over the same nodes, weights, and squiggle-fitting idea, with every quantity labeled.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00 Introduction</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_Introduction/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_Introduction</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Imagine staring at a modern 70-billion-parameter language model generating fluent code and wondering whether deep learning is software engineering or applied mathematics. Underneath PyTorch’s clean abstractions, every single forward pass, loss spike, and gradient update is governed by four classical pillars of mathematics working in concert—and the moment a model diverges at step 4,000, it is those four pillars that tell you why.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-the-mathematical-architecture-of-deep-learning&quot;&gt;Key ideas: The Mathematical Architecture of Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Multivariable Calculus (The Engine of Credit Assignment)&lt;/strong&gt;: Measures how infinitesimal perturbations to millions of weights alter a scalar loss, providing the chain rule and local curvature estimates that make gradient-based optimization possible.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Linear Algebra (The Language of Representation)&lt;/strong&gt;: Encodes batches of data, layer weights, and attention scores as vectors and matrices, turning neural computation into structured compositions of linear maps and spectral decompositions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Real Analysis &amp;amp; Set Theory (The Guarantee of Stability)&lt;/strong&gt;: Supplies the topological and metric foundations—compactness, continuity, and Lipschitz bounds—that determine whether a loss minimum exists and whether an iterative optimizer can converge to it.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Probability &amp;amp; Information Theory (The Bridge to Uncertainty)&lt;/strong&gt;: Casts learning as density estimation and risk minimization, explaining why cross-entropy trains classifiers, why weight decay acts as a Gaussian prior, and how generative models sample new data.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-watching-all-four-pillars-fire-in-one-training-step&quot;&gt;Worked example: Watching All Four Pillars Fire in One Training Step&lt;/h3&gt;

&lt;p&gt;Suppose we train a tiny one-parameter linear model \(\hat{y} = w x\) on a single noisy observation \((x, y) = (2, 5)\) under Gaussian noise, starting at \(w_0 = 1.0\) with learning rate \(\eta = 0.1\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Set Theory &amp;amp; Domain Check&lt;/strong&gt;: Our parameter space is \(\Theta = \mathbb{R}\) and our input-output pair lies in \(\mathbb{R} \times \mathbb{R}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Linear Algebra (Forward Pass)&lt;/strong&gt;: Treat \(x\) and \(w_0\) as \(1 \times 1\) tensors:
\(\hat{y}_0 = w_0 x = 1.0 \times 2 = 2.0\)
The residual error is \(e_0 = \hat{y}_0 - y = 2.0 - 5.0 = -3.0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Probability (Maximum Likelihood Loss)&lt;/strong&gt;: Under a unit-variance Gaussian likelihood \(y \mid x \sim \mathcal{N}(wx, 1)\), minimizing negative log-likelihood is equivalent to minimizing half the squared error:
\(L(w) = \frac{1}{2}(wx - y)^2 \implies L(1.0) = \frac{1}{2}(-3.0)^2 = 4.5\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Calculus (Gradient &amp;amp; Update)&lt;/strong&gt;: Differentiate \(L(w)\) via the chain rule:
\(\frac{dL}{dw} = (wx - y) \cdot x = (-3.0)(2) = -6.0\)
Applying one step of gradient descent yields:
\(w_1 = w_0 - \eta \frac{dL}{dw} = 1.0 - 0.1(-6.0) = 1.6\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verification of Descent&lt;/strong&gt;: Re-evaluate the loss at \(w_1 = 1.6\):
\(\hat{y}_1 = 1.6 \times 2 = 3.2, \quad L(1.6) = \frac{1}{2}(3.2 - 5.0)^2 = \frac{1}{2}(-1.8)^2 = 1.62 &amp;lt; 4.5\)
In five arithmetic lines, all four pillars of Chapter 00 cooperated to cut the loss by 64%.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Deep Learning is at the heart of data science. Whether you’re training a neural network, minimizing errors in regression models, or efficiently allocating resources in recommendation systems, you’re essentially solving problems that involve finding the “best” solution from a vast set of possibilities. But to do this effectively, you need to speak the language of mathematics. We’ll revisit key ideas from linear algebra, set theory, and calculus, ensuring you’re equipped to handle gradients, matrices, constraints, and uncertainties that arise in deep-learning tasks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (2022–2026):&lt;/strong&gt; After the core math notes, see &lt;strong&gt;00-99 Modern Applications and Updates&lt;/strong&gt; for autodiff compilers (JAX, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt;) and how gradients, matrices, and likelihoods show up in scientific ML and scaling-law training.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Optional (interview practice):&lt;/strong&gt; After the probability and calculus notes, see &lt;strong&gt;00-98 Interviews Practice&lt;/strong&gt; for original prompts on entropy / KL and autodiff; the full solved bank is the free &lt;em&gt;Deep Learning Interviews&lt;/em&gt; PDF (&lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;).&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=gq0m_2Glz0g&quot;&gt;MaDL - Introduction&lt;/a&gt; — Tübingen Machine Learning, English. It is a guided tour of the linear algebra, calculus, and probability this chapter assumes before any network.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Vectors&lt;/td&gt;
          &lt;td&gt;Chapter 1, Essence of linear algebra](https://www.youtube.com/watch?v=fNk_zzaMoSs) — 3Blue1Brown, English. The vector picture here is the one later lessons use for weights, activations, and data points.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=pA83XtLeVig&quot;&gt;L01.4 Probability Axioms&lt;/a&gt; — MIT OpenCourseWare, English. The three probability axioms are the rules the probability half of this chapter never leaves.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-99 Modern Applications and Updates (2022–2026)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_99_Modern_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_99_Modern_Applications</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;It is tempting to assume that modern foundation-model frameworks have abstracted math away into &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;loss.backward()&lt;/code&gt;. In reality, the biggest breakthroughs of 2022–2026—Physics-Informed Neural Networks, LoRA low-rank matrices, FlashAttention, and flow-matching diffusion—are pure applied calculus, linear algebra, and probability written in Triton and JAX.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-classical-math-inside-20222026-ai-stacks&quot;&gt;Key ideas: Classical Math Inside 2022–2026 AI Stacks&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Automatic Differentiation &amp;amp; Scientific ML (PINNs)&lt;/strong&gt;: Uses higher-order derivatives (\(\frac{\partial^2 u}{\partial x^2}\)) computed directly through autodiff graphs to enforce partial differential equations as soft loss penalties.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Low-Rank Linear Algebra (LoRA &amp;amp; Quantized Matrices)&lt;/strong&gt;: Exploits the insight that fine-tuning weight updates \(\Delta W \in \mathbb{R}^{d \times d}\) live in a tiny subspace of rank \(r \ll d\), factoring \(\Delta W = BA\) to cut trainable parameters by \(100\times\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Probability &amp;amp; Score Matching (Diffusion &amp;amp; Flow Matching)&lt;/strong&gt;: Trains generative models to estimate the score function \(\nabla_{\mathbf{x}} \log p_t(\mathbf{x})\) or velocity field transporting Gaussian noise smoothly into complex data distributions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Differentiable Programming Beyond Neural Nets&lt;/strong&gt;: Extends reverse-mode gradients through physics simulators, ray tracers, and convex optimization layers to solve inverse problems end-to-end.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-parameter--flop-savings-of-low-rank-adaptation-lora&quot;&gt;Worked example: Parameter &amp;amp; FLOP Savings of Low-Rank Adaptation (LoRA)&lt;/h3&gt;

&lt;p&gt;Consider a Transformer projection matrix \(W_0 \in \mathbb{R}^{4096 \times 4096}\) adapted via LoRA with rank \(r = 16\): \(W = W_0 + BA\) where \(B \in \mathbb{R}^{4096 \times 16}\) and \(A \in \mathbb{R}^{16 \times 4096}\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Full Fine-Tuning Parameter Count&lt;/strong&gt;:
\(\text{Params}_{\text{full}} = 4096 \times 4096 = 16{,}777{,}216\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;LoRA Trainable Parameter Count&lt;/strong&gt;:
\(\text{Params}_{\text{LoRA}} = (4096 \times 16) + (16 \times 4096) = 65{,}536 + 65{,}536 = 131{,}072\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compression Ratio&lt;/strong&gt;:
\(\frac{\text{Params}_{\text{LoRA}}}{\text{Params}_{\text{full}}} = \frac{131{,}072}{16{,}777{,}216} = \frac{1}{128} \approx 0.781\%\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify Associative Matrix Order (Avoid Forming \(BA\) Explicitly!)&lt;/strong&gt;:
For a single token vector \(\mathbf{x} \in \mathbb{R}^{4096}\), computing \(B(A\mathbf{x})\) takes \(2 \times 4096 \times 16 = 131{,}072\) multiply-adds instead of \(16.78\text{M}\)—a \(128\times\) speedup derived purely from matrix multiplication associativity!&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-calculus-linear-algebra-and-probability-in-20222026-stacks&quot;&gt;Optional: calculus, linear algebra, and probability in 2022–2026 stacks&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace the core notes on calculus, linear algebra, or probability. It shows how those same objects appear in current scientific and production software.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The chapter’s core idea is that gradients, matrices, and distributions are the language of learning. Between 2022 and 2026 that language became &lt;em&gt;executable&lt;/em&gt;: compilers turn a math graph into fused GPU kernels, and scientific codes share the same autodiff used by deep learning.&lt;/p&gt;

&lt;h2 id=&quot;1-why-the-math-chapter-still-matters&quot;&gt;1. Why the math chapter still matters&lt;/h2&gt;

&lt;p&gt;Automatic differentiation is the industrial form of the chain rule from the calculus notes. If \(f = g \circ h\), then&lt;/p&gt;

\[Df(\mathbf{x}) = Dg(h(\mathbf{x})) \cdot Dh(\mathbf{x}).\]

&lt;p&gt;Reverse-mode autodiff (what PyTorch and JAX implement) evaluates this product from the output backward, which is exactly backpropagation for a scalar loss. The new work is not a different derivative: it is &lt;em&gt;how&lt;/em&gt; the product is scheduled, fused, and checked.&lt;/p&gt;

&lt;h2 id=&quot;2-concrete-applications&quot;&gt;2. Concrete applications&lt;/h2&gt;

&lt;h3 id=&quot;scientific-machine-learning-and-pinns&quot;&gt;Scientific machine learning and PINNs&lt;/h3&gt;

&lt;p&gt;Physics-informed neural networks still minimize a residual that mixes data loss with PDE residuals. The residual of a differential operator \(\mathcal{N}\) is&lt;/p&gt;

\[\mathcal{L}_{\text{PDE}} = \mathbb{E}_{\mathbf{x}}\big\|\mathcal{N}[\hat{u}](\mathbf{x})\big\|^2,\]

&lt;p&gt;where derivatives of the network \(\hat{u}\) come from autodiff, not finite differences. NVIDIA’s &lt;a href=&quot;https://docs.nvidia.com/deeplearning/modulus/index.html&quot;&gt;Modulus&lt;/a&gt; and the JAX ecosystem (&lt;a href=&quot;https://github.com/google/jax-cfd&quot;&gt;JAX-CFD&lt;/a&gt;, &lt;a href=&quot;https://github.com/jax-md/jax-md&quot;&gt;JAX-MD&lt;/a&gt;) made this pattern routine after 2022.&lt;/p&gt;

&lt;h3 id=&quot;differentiable-programming-beyond-neural-nets&quot;&gt;Differentiable programming beyond neural nets&lt;/h3&gt;

&lt;p&gt;JAX’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vmap&lt;/code&gt;, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt; treat a simulation step as a function whose Jacobian can be composed. That is linear algebra (Jacobian–vector and vector–Jacobian products) plus the Taylor viewpoint: a single Newton–Schulz or conjugate-gradient iteration is just another differentiable block.&lt;/p&gt;

&lt;h3 id=&quot;probability-in-foundation-model-training&quot;&gt;Probability in foundation-model training&lt;/h3&gt;

&lt;p&gt;Scaling-law papers treat training as a statistical experiment: loss \(L\) versus compute, tokens, and parameters. &lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Hoffmann et al., 2022&lt;/a&gt; (Chinchilla) fitted power laws of the form&lt;/p&gt;

\[L(N, D) \approx E + \frac{A}{N^{\alpha}} + \frac{B}{D^{\beta}},\]

&lt;p&gt;which is the same likelihood / expectation language as the probability notes, applied to LLM training budgets.&lt;/p&gt;

&lt;h2 id=&quot;3-widely-used-software&quot;&gt;3. Widely used software&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX&lt;/a&gt; — composable &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;grad&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vmap&lt;/code&gt; / &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jit&lt;/code&gt; (Google).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://pytorch.org/get-started/pytorch-2.0/&quot;&gt;PyTorch 2&lt;/a&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;torch.compile&lt;/code&gt; — graph capture of the same autograd tape (&lt;a href=&quot;https://arxiv.org/abs/2404.14294&quot;&gt;Ansel et al., 2024&lt;/a&gt;).&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/tinygrad/tinygrad&quot;&gt;tinygrad&lt;/a&gt; and &lt;a href=&quot;https://github.com/ml-explore/mlx&quot;&gt;MLX&lt;/a&gt; — small autodiff engines that make the calculus explicit.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;4-citations-20222026&quot;&gt;4. Citations (2022–2026)&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2203.15556&quot;&gt;Training Compute-Optimal Large Language Models (Hoffmann et al., 2022)&lt;/a&gt; — Chinchilla scaling laws: allocate tokens and parameters jointly.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://arxiv.org/abs/2404.14294&quot;&gt;PyTorch 2: Faster Machine Learning Through Dynamic Python Bytecode Transformation and Graph Compilation (Ansel et al., 2024)&lt;/a&gt; — compiler for the autograd graph.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://github.com/google/jax&quot;&gt;JAX: composable transformations of Python+NumPy programs&lt;/a&gt; — the standard research stack for autodiff + SIMD batching.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;5-how-this-complements-the-core-notes&quot;&gt;5. How this complements the core notes&lt;/h2&gt;

&lt;p&gt;Keep using the calculus and linear-algebra lessons to compute \(\nabla f\) and matrix factorizations by hand. This optional note only shows where those objects now live in compilers and scientific ML — it does not replace the derivations.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Backpropagation calculus&lt;/td&gt;
          &lt;td&gt;Deep Learning Chapter 4](https://www.youtube.com/watch?v=tIeHLnjs5U8) — 3Blue1Brown, English. Reverse-mode autodiff is the chain rule this note says PyTorch and JAX still implement.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=VMj-3S1tku0&quot;&gt;The spelled-out intro to neural networks and backpropagation: building micrograd&lt;/a&gt; — Andrej Karpathy, English. Builds that reverse-mode product in code, which is the executable form of the calculus chapter.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Visualizing the chain rule and product rule&lt;/td&gt;
          &lt;td&gt;Chapter 4, Essence of calculus](https://www.youtube.com/watch?v=YG15m2VwSjA) — 3Blue1Brown, English. The one-variable chain rule being differentiated here is the identity the note writes as Df = Dg · Dh.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-98 Interviews Practice (information theory and calculus)</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_98_Interviews_Practice/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_98_Interviews_Practice</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;In technical ML interviews, interviewers rarely ask you to integrate a textbook formula—they ask a deceptively short question like “Why does reverse-mode autodiff beat forward-mode for neural networks?” to see whether your calculus and information theory are operational rather than memorized.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-core-interview-themes-in-math-for-deep-learning&quot;&gt;Key ideas: Core Interview Themes in Math for Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Information Theory (Entropy, Cross-Entropy, and KL Divergence)&lt;/strong&gt;: Connects classification loss directly to coding theory via the exact decomposition \(H(p, q) = H(p) + D_{\text{KL}}(p \| q)\), proving that cross-entropy is minimized iff \(q = p\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mutual Information &amp;amp; Data Processing Inequality&lt;/strong&gt;: Quantifies shared information \(I(X; Y) = H(Y) - H(Y\mid X)\) and explains why deterministic post-processing can never create information that wasn’t already present.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Automatic Differentiation Modes (Forward vs. Reverse)&lt;/strong&gt;: Compares Jacobian-vector products (cost proportional to input dimension \(n\)) against vector-Jacobian products (cost proportional to output dimension \(m\)), explaining why scalar-loss networks (\(m = 1, n = 10^9\)) rely on reverse mode.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Second-Order Geometry (Hessian Eigenvalues &amp;amp; Conditioning)&lt;/strong&gt;: Uses the Hessian spectrum to diagnose local minima, saddle points, and ill-conditioned ravines during live whiteboard debugging.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-verifying-hp-q--hp--d_textklp--q-in-bits&quot;&gt;Worked example: Verifying \(H(p, q) = H(p) + D_{\text{KL}}(p \| q)\) in Bits&lt;/h3&gt;

&lt;p&gt;Suppose the true binary label distribution is \(p = (0.75, 0.25)\) and a classifier predicts \(q = (0.50, 0.50)\). Compute all three quantities in base-2 logarithms (bits), noting \(\log_2(0.75) \approx -0.4150\), \(\log_2(0.25) = -2\), \(\log_2(0.50) = -1\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;True Entropy \(H(p)\)&lt;/strong&gt;:
\(H(p) = -\big(0.75\log_2 0.75 + 0.25\log_2 0.25\big) = -\big(0.75(-0.4150) + 0.25(-2)\big) = 0.3113 + 0.5000 = 0.8113\text{ bits}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cross-Entropy \(H(p, q)\)&lt;/strong&gt;:
\(H(p, q) = -\big(0.75\log_2 0.50 + 0.25\log_2 0.50\big) = -\big(0.75(-1) + 0.25(-1)\big) = 1.0000\text{ bit}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;KL Divergence \(D_{\text{KL}}(p \| q)\)&lt;/strong&gt;:
\(D_{\text{KL}}(p \| q) = 0.75\log_2\!\left(\frac{0.75}{0.50}\right) + 0.25\log_2\!\left(\frac{0.25}{0.50}\right) = 0.75(0.5850) + 0.25(-1) = 0.4387 - 0.2500 = 0.1887\text{ bits}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Identity Verification&lt;/strong&gt;:
\(H(p) + D_{\text{KL}}(p \| q) = 0.8113 + 0.1887 = 1.0000 = H(p, q)\)
Because \(H(p) = 0.8113\) is fixed by the dataset, minimizing cross-entropy loss is mathematically identical to driving \(D_{\text{KL}}(p \| q) \to 0\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h1 id=&quot;optional-interview-practice--information-theory-and-calculus&quot;&gt;Optional: interview practice — information theory and calculus&lt;/h1&gt;

&lt;blockquote&gt;
  &lt;p&gt;This lesson is &lt;strong&gt;optional&lt;/strong&gt;. It does &lt;strong&gt;not&lt;/strong&gt; replace the calculus, linear-algebra, or probability notes. After those lessons, use this drill, then open &lt;em&gt;Deep Learning Interviews&lt;/em&gt; (Kashani &amp;amp; Ivry, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;) for a larger solved set on the same themes.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Book themes for this chapter (study in the PDF, not here):&lt;/strong&gt; information theory — entropy, KL divergence, mutual information — and calculus / automatic-differentiation intuition.&lt;/p&gt;

&lt;p&gt;Hub: &lt;strong&gt;01-98 Deep Learning Interviews practice track&lt;/strong&gt;.&lt;/p&gt;

&lt;h2 id=&quot;practice-prompts-original&quot;&gt;Practice prompts (original)&lt;/h2&gt;

&lt;h3 id=&quot;q1-cross-entropy-split&quot;&gt;Q1. Cross-entropy split&lt;/h3&gt;

&lt;p&gt;Let \(p\) be a one-hot label over \(K\) classes and \(q\) a softmax prediction. Show&lt;/p&gt;

\[\mathrm{CE}(p,q) = H(p) + D_{\mathrm{KL}}(p\|q)\]

&lt;p&gt;and explain why \(H(p) = 0\) in the usual supervised setting.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Expand \(D_{\mathrm{KL}}(p\|q) = \sum_k p_k \log(p_k/q_k)\) and use \(0\log 0 := 0\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; \(\mathrm{CE}(p,q) = -\sum_k p_k\log q_k\). The KL term adds \(H(p) = -\sum_k p_k\log p_k\), which is zero when \(p\) is a point mass. Training therefore minimizes KL to the empirical one-hot, even if we implement CE. For non-one-hot targets (label smoothing), \(H(p)\) is a positive constant you can ignore for gradient steps but should not ignore when reading reported CE numbers.&lt;/p&gt;

&lt;h3 id=&quot;q2-mutual-information-after-a-perfect-classifier&quot;&gt;Q2. Mutual information after a perfect classifier&lt;/h3&gt;

&lt;p&gt;Let \(Y\) be a balanced binary label and \(\hat Y\) the model’s hard prediction. What happens to \(I(Y;\hat Y)\) if the classifier is perfect? If it always outputs the majority class?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; \(I(Y;\hat Y) = H(Y) - H(Y\mid\hat Y)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Perfect prediction makes \(H(Y\mid\hat Y) = 0\), so \(I(Y;\hat Y) = H(Y) = 1\) bit when \(Y\) is fair. A constant predictor is independent of \(Y\), so mutual information is \(0\). Accuracy can look “high” on an imbalanced set while \(I(Y;\hat Y)\) stays near zero — a useful interview contrast.&lt;/p&gt;

&lt;h3 id=&quot;q3-one-chain-rule-gradient&quot;&gt;Q3. One chain-rule gradient&lt;/h3&gt;

&lt;p&gt;Let \(f(\mathbf{w}) = \sigma(\mathbf{w}^\top\mathbf{x})\) with \(\sigma(z) = (1+e^{-z})^{-1}\) and \(\mathbf{x}\) fixed. Write \(\nabla_{\mathbf{w}} f\) in a form you could implement in one line.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; \(\sigma&apos;(z) = \sigma(z)\bigl(1-\sigma(z)\bigr)\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; \(\nabla_{\mathbf{w}} f = \sigma(\mathbf{w}^\top\mathbf{x})\bigl(1-\sigma(\mathbf{w}^\top\mathbf{x})\bigr)\,\mathbf{x}\). This is the same local factor that appears in logistic regression (Chapter 03). Reverse-mode autodiff evaluates it from the scalar \(f\) backward; you do not form the Jacobian of \(\mathbf{w}\) explicitly.&lt;/p&gt;

&lt;h3 id=&quot;q4-why-reverse-mode-wins-for-a-scalar-loss&quot;&gt;Q4. Why reverse mode wins for a scalar loss&lt;/h3&gt;

&lt;p&gt;A network maps \(\mathbb{R}^n\to\mathbb{R}\) (one loss). Why is reverse-mode autodiff roughly “one forward + one backward,” almost independent of \(n\), while forward mode scales with \(n\)?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; Forward mode seeds one input direction at a time; reverse mode seeds the scalar output once.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; Forward mode computes a Jacobian–vector product \(J\mathbf{v}\). Getting every partial of a scalar needs \(n\) such products (the standard basis). Reverse mode computes a vector–Jacobian product \(\mathbf{u}^\top J\); with \(\mathbf{u}=1\) you obtain the full gradient in one sweep. That is why deep-learning frameworks implement reverse mode (backprop). Forward mode still wins when there are many outputs and few inputs.&lt;/p&gt;

&lt;h3 id=&quot;q5-hessian-as-local-curvature&quot;&gt;Q5. Hessian as local curvature&lt;/h3&gt;

&lt;p&gt;For \(f(\mathbf{x}) = \tfrac12\mathbf{x}^\top A\mathbf{x}\) with \(A\) symmetric positive definite, what is \(\nabla^2 f\)? How does a large condition number \(\kappa(A)\) show up in gradient descent?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hint.&lt;/strong&gt; The Taylor picture in the calculus notes: the Hessian is the quadratic term.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Discussion.&lt;/strong&gt; \(\nabla^2 f = A\). Gradient descent zig-zags along the narrow valley when \(\kappa(A)=\lambda_{\max}/\lambda_{\min}\) is large: steps that are safe on the sharp axis are tiny on the flat axis. Interviewers often want this geometric sentence before they ask about Adam or Newton.&lt;/p&gt;

&lt;h2 id=&quot;attribution&quot;&gt;Attribution&lt;/h2&gt;

&lt;p&gt;Kashani, S., and Ivry, A. &lt;em&gt;Deep Learning Interviews&lt;/em&gt;, &lt;a href=&quot;https://arxiv.org/abs/2201.00650&quot;&gt;arXiv:2201.00650&lt;/a&gt;. Download the PDF from arXiv for the full solved Q&amp;amp;A. This page is original course practice, not a reprint.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pXh53lqPkHs&quot;&gt;MaDL - Information and Entropy&lt;/a&gt; — Tübingen Machine Learning, English. Entropy is the information-theory prompt this practice set asks you to compute.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=vPvnpC0PNVQ&quot;&gt;MaDL - Kullback-Leibler Divergence&lt;/a&gt; — Tübingen Machine Learning, English. KL divergence is the second information-theory object in these prompts.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[The paradox of the derivative&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of calculus](https://www.youtube.com/watch?v=9vKqVkMQHKk) — 3Blue1Brown, English. The calculus prompts are about the derivative; this is the picture to redraw before answering.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04 Probability and Statistics</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_Probability_and_Statistics/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_Probability_and_Statistics</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Real-world data is never clean: sensors jitter, human annotators disagree, and the same prompt admits dozens of valid continuations. Probability theory is what lets neural networks stop chasing impossible deterministic perfection and instead learn calibrated distributions over what is likely.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-probability--statistics-in-deep-learning&quot;&gt;Key ideas: Probability &amp;amp; Statistics in Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Axiomatic Probability &amp;amp; Conditioning (Belief Updating)&lt;/strong&gt;: Provides the formal rules—sum rule, product rule, and Bayes’ theorem—that govern how evidence updates uncertainty across latent and observed variables.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Random Variables &amp;amp; Expectation (Risk Minimization)&lt;/strong&gt;: Frames training as minimizing expected loss \(\mathbb{E}_{(x,y)\sim p_{\text{data}}}[\ell(f_\theta(x), y)]\), approximated in practice by empirical mini-batch averages.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parametric Distributions (Modeling Outputs &amp;amp; Noise)&lt;/strong&gt;: Links every standard neural loss directly to a likelihood assumption—Gaussian for MSE, Bernoulli for binary cross-entropy, and Categorical for softmax cross-entropy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Statistical Estimation (MLE, MAP, and Generalization)&lt;/strong&gt;: Connects maximum likelihood to cross-entropy minimization and shows how placing a prior on weights (MAP estimation) mathematically yields \(L_2\) (Gaussian prior) and \(L_1\) (Laplace prior) regularization.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-empirical-risk-vs-expected-risk-on-a-mini-batch&quot;&gt;Worked example: Empirical Risk vs. Expected Risk on a Mini-Batch&lt;/h3&gt;

&lt;p&gt;Suppose a binary classifier assigns predicted probability \(\hat{p}(y=1\mid x)\) on a mini-batch of \(N = 4\) examples with ground-truth labels and predictions:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\((y_1, \hat{p}_1) = (1, 0.8)\), \((y_2, \hat{p}_2) = (1, 0.5)\), \((y_3, \hat{p}_3) = (0, 0.2)\), \((y_4, \hat{p}_4) = (0, 0.5)\).&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Likelihood of Each Sample Under a Bernoulli Model&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Sample 1 (\(y=1\)): \(P(y_1 \mid x_1) = 0.8\)&lt;/li&gt;
      &lt;li&gt;Sample 2 (\(y=1\)): \(P(y_2 \mid x_2) = 0.5\)&lt;/li&gt;
      &lt;li&gt;Sample 3 (\(y=0\)): \(P(y_3 \mid x_3) = 1 - 0.2 = 0.8\)&lt;/li&gt;
      &lt;li&gt;Sample 4 (\(y=0\)): \(P(y_4 \mid x_4) = 1 - 0.5 = 0.5\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Joint Mini-Batch Likelihood (Assuming i.i.d. Samples)&lt;/strong&gt;:
\(\mathcal{L}(\theta) = 0.8 \times 0.5 \times 0.8 \times 0.5 = 0.16\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convert to Average Negative Log-Likelihood (Empirical Binary Cross-Entropy)&lt;/strong&gt;:
Using \(\ln(0.8) \approx -0.2231\) and \(\ln(0.5) \approx -0.6931\):
\(\hat{R}(\theta) = -\frac{1}{4}\ln(0.16) = -\frac{1}{4}\big[2(-0.2231) + 2(-0.6931)\big] = \frac{1.8324}{4} = 0.4581\text{ nats}\)
Maximizing the joint probability \(0.16\) is algebraically identical to minimizing the average cross-entropy loss \(0.4581\)—and taking logarithms prevents underflow when \(N = 10^6\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;probability-and-statistics-for-deep-learning&quot;&gt;Probability and Statistics for Deep Learning&lt;/h2&gt;

&lt;p&gt;Probability and statistics form a crucial foundation for understanding many deep-learning problems, especially in machine learning and data science. This section introduces the essential probabilistic concepts that frequently appear in convex deep-learning, from maximum likelihood estimation to Bayesian deep-learning.&lt;/p&gt;

&lt;h3 id=&quot;why-probability-matters-in-deep-learning&quot;&gt;Why Probability Matters in Deep Learning&lt;/h3&gt;

&lt;p&gt;Many deep-learning problems arise from statistical modeling:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Maximum Likelihood Estimation (MLE)&lt;/strong&gt;: Finding parameters that maximize the likelihood of observed data&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayesian Deep Learning&lt;/strong&gt;: Using probabilistic models to guide the search for optimal solutions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Stochastic Deep Learning&lt;/strong&gt;: Dealing with uncertainty and randomness in objective functions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Regularization&lt;/strong&gt;: Adding probabilistic priors to prevent overfitting&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Risk Minimization&lt;/strong&gt;: Optimizing expected loss over probability distributions&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;key-topics-covered&quot;&gt;Key Topics Covered&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Basic Probability Theory&lt;/strong&gt;: Sample spaces, events, and probability axioms&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Common Probability Distributions&lt;/strong&gt;: Normal, exponential, and other distributions crucial for deep-learning&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Expectation and Variance&lt;/strong&gt;: Computing and optimizing expected values&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayes’ Theorem&lt;/strong&gt;: Foundation for Bayesian deep-learning and inference&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Statistical Estimation&lt;/strong&gt;: Connecting probability theory to deep-learning problems&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;connection-to-deep-learning&quot;&gt;Connection to Deep Learning&lt;/h3&gt;

&lt;p&gt;Understanding probability helps you:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Formulate Problems&lt;/strong&gt;: Convert real-world uncertainty into mathematical deep-learning problems&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Choose Objective Functions&lt;/strong&gt;: Select appropriate loss functions based on probabilistic assumptions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Interpret Results&lt;/strong&gt;: Understand confidence intervals and statistical significance of solutions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Handle Noise&lt;/strong&gt;: Deal with measurement errors and stochastic processes&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Design Algorithms&lt;/strong&gt;: Develop robust deep-learning methods that work under uncertainty&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This foundation will be essential as we explore how probabilistic models lead to convex deep-learning problems in machine learning, statistics, and engineering applications.&lt;/p&gt;

&lt;div style=&quot;background: #e8f4fd; padding: 15px; border-left: 4px solid #2196F3; margin: 20px 0;&quot;&gt;
&lt;strong&gt;💡 Learning Path:&lt;/strong&gt; Start with basic probability concepts, then explore how they connect to deep-learning through maximum likelihood estimation and Bayesian methods. Each lesson builds toward understanding how uncertainty and randomness create deep-learning problems.
&lt;/div&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pA83XtLeVig&quot;&gt;L01.4 Probability Axioms&lt;/a&gt; — MIT OpenCourseWare, English. The axioms are the floor under every distribution in this block.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=bvBukLjHZh8&quot;&gt;MaDL - Random Variables and Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, English. Random variables and distributions, in the notation used for deep learning.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NbzVwvE_syQ&quot;&gt;MaDL - Common Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, English. The named families (Bernoulli through Gaussian) that the distribution lessons specialize.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-02 Common Probability Distributions</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_02_Common_Probability_Distributions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_02_Common_Probability_Distributions</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Every time you choose a loss function, initialize a layer, or design a generative decoder, you are implicitly picking a probability distribution. Knowing the canonical distribution families turns ad-hoc hyperparameter guessing into principled statistical modeling.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-the-distribution-toolkit-of-deep-learning&quot;&gt;Key ideas: The Distribution Toolkit of Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Discrete Families (Bernoulli, Binomial, Categorical, Poisson)&lt;/strong&gt;: Model binary labels, dropout masks, multi-class token predictions, and event counts.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Continuous Families (Uniform, Gaussian, Exponential, Beta)&lt;/strong&gt;: Model weight initializations, continuous regression noise, latent spaces in VAEs/diffusion models, and calibrated probabilities on \([0, 1]\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multivariate Families (Multivariate Normal &amp;amp; Covariance Geometry)&lt;/strong&gt;: Capture feature correlations across dimensions, underpinning PCA, Mahalanobis outlier detection, and Gaussian diffusion transitions.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Distribution-to-Loss Duality&lt;/strong&gt;: Every standard deep learning loss is the negative log-likelihood (NLL) of a specific distribution—matching your model’s output distribution to the data geometry prevents severe bias.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-matching-a-distribution-to-its-exact-neural-loss&quot;&gt;Worked example: Matching a Distribution to Its Exact Neural Loss&lt;/h3&gt;

&lt;p&gt;Suppose a network predicts a scalar mean \(\mu_\theta(x) = 3.0\) for a continuous target \(y = 5.0\) under a Gaussian model \(y \mid x \sim \mathcal{N}(\mu_\theta(x), \sigma^2)\) with fixed \(\sigma = 2.0\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Write the Gaussian Density at \(y = 5.0\)&lt;/strong&gt;:
\(p(y \mid x) = \frac{1}{\sqrt{2\pi}\sigma}\exp\!\left(-\frac{(y - \mu_\theta(x))^2}{2\sigma^2}\right)\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Take the Negative Log-Likelihood&lt;/strong&gt;:
\(-\ln p(y \mid x) = \ln(\sqrt{2\pi}\sigma) + \frac{(y - \mu_\theta(x))^2}{2\sigma^2}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Substitute Numbers (\(\sigma = 2.0, \mu_\theta = 3.0, y = 5.0\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Constant term (independent of \(\theta\)): \(\ln(2\sqrt{2\pi}) \approx \ln(5.0133) \approx 1.6121\).&lt;/li&gt;
      &lt;li&gt;Data-fit term: \(\frac{(5.0 - 3.0)^2}{2(2.0)^2} = \frac{4.0}{8.0} = 0.5000\).&lt;/li&gt;
      &lt;li&gt;Total NLL: \(1.6121 + 0.5000 = 2.1121\text{ nats}\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Key Insight&lt;/strong&gt;:
Because \(\ln(\sqrt{2\pi}\sigma)\) and \(\frac{1}{2\sigma^2}\) are constants with respect to \(\theta\), minimizing Gaussian NLL produces the exact same optimal weights as minimizing Mean Squared Error \((y - \mu_\theta(x))^2\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson surveys probability distributions used throughout deep learning:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Discrete Distributions&lt;/strong&gt; — Bernoulli, Binomial, Categorical, Poisson (with interactive demos)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Continuous Distributions&lt;/strong&gt; — Uniform, Gaussian, Exponential, Laplace, and related densitites&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multivariate Distributions and Deep Learning&lt;/strong&gt; — multivariate Gaussians and modeling applications&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Work through each section in order; demos are included where they support the material.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=oI3hZJqXJuc&quot;&gt;The Main Ideas behind Probability Distributions&lt;/a&gt; — StatQuest with Josh Starmer, English. What a distribution is, before the discrete, continuous, and multivariate lessons.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NbzVwvE_syQ&quot;&gt;MaDL - Common Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, English. Names the families this block then splits into their own lessons.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=rzFX5NWojp0&quot;&gt;The Normal Distribution, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. The Gaussian is the continuous case the next lessons keep returning to.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-02-03 Multivariate Distributions and Deep Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_02_03_Multivariate_and_DL_Applications/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_02_03_Multivariate_and_DL_Applications</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Individual pixels in a face image are never independent—knowing a pixel on the left cheek strongly constrains its neighbors. Multivariate distributions capture those cross-feature correlations through covariance matrices, powering everything from Batch Normalization and PCA whitening to Variational Autoencoders and Diffusion Models.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-multivariate-probability-in-deep-learning&quot;&gt;Key ideas: Multivariate Probability in Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Multivariate Normal Distribution (\(\mathcal{N}(\boldsymbol{\mu}, \Sigma)\))&lt;/strong&gt;: Encodes both the center \(\boldsymbol{\mu}\) and the ellipsoidal correlation geometry \(\Sigma\); diagonal \(\Sigma\) implies axis-aligned independence, while off-diagonal entries tilt the contours.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Mahalanobis Distance (Covariance-Aware Distance)&lt;/strong&gt;: Measures how far a point lies from a distribution via \(d_M(\mathbf{x}) = \sqrt{(\mathbf{x} - \boldsymbol{\mu})^\top \Sigma^{-1} (\mathbf{x} - \boldsymbol{\mu})}\), normalizing away scale and correlation for out-of-distribution (OOD) detection.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Reparameterization Trick (Differentiable Sampling)&lt;/strong&gt;: Expresses \(\mathbf{z} \sim \mathcal{N}(\boldsymbol{\mu}, \text{diag}(\boldsymbol{\sigma}^2))\) as \(\mathbf{z} = \boldsymbol{\mu} + \boldsymbol{\sigma} \odot \boldsymbol{\epsilon}\) with \(\boldsymbol{\epsilon} \sim \mathcal{N}(\mathbf{0}, I)\), allowing gradients to flow smoothly through stochastic latent layers.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;MAP Estimation &amp;amp; Bayesian Regularization&lt;/strong&gt;: Shows that adding \(\frac{\lambda}{2}\|\mathbf{w}\|_2^2\) to a loss is mathematically equivalent to placing an isotropic multivariate Gaussian prior \(\mathcal{N}(\mathbf{0}, \tau^2 I)\) over the network weights.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-computing-mahalanobis-distance-and-a-vae-reparameterized-sample&quot;&gt;Worked example: Computing Mahalanobis Distance and a VAE Reparameterized Sample&lt;/h3&gt;

&lt;p&gt;Consider a 2D latent distribution \(\mathcal{N}(\boldsymbol{\mu}, \Sigma)\) with \(\boldsymbol{\mu} = \begin{bmatrix} 1 \\ 2 \end{bmatrix}\) and \(\Sigma = \begin{bmatrix} 4 &amp;amp; 2 \\ 2 &amp;amp; 2 \end{bmatrix}\), and a test embedding \(\mathbf{x} = \begin{bmatrix} 3 \\ 4 \end{bmatrix}\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Center the Observation&lt;/strong&gt;:
\(\mathbf{d} = \mathbf{x} - \boldsymbol{\mu} = \begin{bmatrix} 3 - 1 \\ 4 - 2 \end{bmatrix} = \begin{bmatrix} 2 \\ 2 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Invert the \(2 \times 2\) Covariance Matrix \(\Sigma\)&lt;/strong&gt;:
\(\det(\Sigma) = (4)(2) - (2)(2) = 8 - 4 = 4\)
\(\Sigma^{-1} = \frac{1}{4}\begin{bmatrix} 2 &amp;amp; -2 \\ -2 &amp;amp; 4 \end{bmatrix} = \begin{bmatrix} 0.5 &amp;amp; -0.5 \\ -0.5 &amp;amp; 1.0 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Squared Mahalanobis Distance&lt;/strong&gt;:
\(\Sigma^{-1}\mathbf{d} = \begin{bmatrix} 0.5(2) - 0.5(2) \\ -0.5(2) + 1.0(2) \end{bmatrix} = \begin{bmatrix} 0 \\ 1 \end{bmatrix}\)
\(d_M^2(\mathbf{x}) = \mathbf{d}^\top \Sigma^{-1} \mathbf{d} = \begin{bmatrix} 2 &amp;amp; 2 \end{bmatrix}\begin{bmatrix} 0 \\ 1 \end{bmatrix} = 2 \implies d_M(\mathbf{x}) = \sqrt{2} \approx 1.414\)
Compare with Euclidean distance \(\|\mathbf{d}\|_2 = \sqrt{2^2 + 2^2} = \sqrt{8} \approx 2.828\): because the two coordinates are positively correlated (\(\Sigma_{12} = 2 &amp;gt; 0\)), moving diagonally along \((2, 2)\) is actually twice as plausible in Mahalanobis units!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;3-multivariate-distributions&quot;&gt;3. Multivariate Distributions&lt;/h3&gt;

&lt;h4 id=&quot;multivariate-normal-distribution&quot;&gt;Multivariate Normal Distribution&lt;/h4&gt;

&lt;p&gt;Extension of the normal distribution to multiple dimensions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parameters&lt;/strong&gt;: \(\boldsymbol{\mu} \in \mathbb{R}^d\) (mean vector), \(\boldsymbol{\Sigma} \in \mathbb{R}^{d \times d}\) (covariance matrix, positive definite)&lt;/p&gt;

&lt;table&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;strong&gt;PDF&lt;/strong&gt;: $$f(\mathbf{x}) = \frac{1}{(2\pi)^{d/2}&lt;/td&gt;
      &lt;td&gt;\boldsymbol{\Sigma}&lt;/td&gt;
      &lt;td&gt;^{1/2}} \exp\left(-\frac{1}{2}(\mathbf{x}-\boldsymbol{\mu})^T\boldsymbol{\Sigma}^{-1}(\mathbf{x}-\boldsymbol{\mu})\right)$$&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;p&gt;&lt;strong&gt;Properties&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Marginal distributions are normal&lt;/li&gt;
  &lt;li&gt;Linear combinations are normal&lt;/li&gt;
  &lt;li&gt;Conditional distributions are normal&lt;/li&gt;
&lt;/ul&gt;

&lt;div id=&quot;multivariate-demo&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f0f8ff;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Multivariate Normal Distribution&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;multivariateCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;2D Visualization:&lt;/strong&gt; Contour plot of bivariate normal distribution. Samples shown as dots.
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Parameters&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;mu1-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;μ₁: &lt;span id=&quot;mu1-value&quot;&gt;0.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;mu1-slider&quot; min=&quot;-2&quot; max=&quot;2&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;mu2-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;μ₂: &lt;span id=&quot;mu2-value&quot;&gt;0.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;mu2-slider&quot; min=&quot;-2&quot; max=&quot;2&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;sigma1-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;σ₁: &lt;span id=&quot;sigma1-value&quot;&gt;1.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;sigma1-slider&quot; min=&quot;0.5&quot; max=&quot;2&quot; step=&quot;0.1&quot; value=&quot;1.0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;sigma2-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;σ₂: &lt;span id=&quot;sigma2-value&quot;&gt;1.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;sigma2-slider&quot; min=&quot;0.5&quot; max=&quot;2&quot; step=&quot;0.1&quot; value=&quot;1.0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;rho-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;ρ (correlation): &lt;span id=&quot;rho-value&quot;&gt;0.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;rho-slider&quot; min=&quot;-0.9&quot; max=&quot;0.9&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;button id=&quot;generate-samples&quot; style=&quot;width: 100%; padding: 10px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer; margin-bottom: 15px;&quot;&gt;Generate Samples&lt;/button&gt;
                
                &lt;div id=&quot;multivariate-stats&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Covariance Matrix:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;Σ₁₁: &lt;span id=&quot;cov11&quot;&gt;1.000&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Σ₁₂: &lt;span id=&quot;cov12&quot;&gt;0.000&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Σ₂₂: &lt;span id=&quot;cov22&quot;&gt;1.000&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Det(Σ): &lt;span id=&quot;det-cov&quot;&gt;1.000&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;4-applications-in-deep-learning&quot;&gt;4. Applications in Deep Learning&lt;/h3&gt;

&lt;h4 id=&quot;maximum-likelihood-estimation&quot;&gt;Maximum Likelihood Estimation&lt;/h4&gt;
&lt;p&gt;Many deep-learning problems involve finding parameters that maximize the likelihood of observed data under a specific distribution:&lt;/p&gt;

\[\hat{\theta} = \arg\max_\theta \prod_{i=1}^n f(x_i; \theta)\]

&lt;h4 id=&quot;bayesian-deep-learning&quot;&gt;Bayesian Deep Learning&lt;/h4&gt;
&lt;p&gt;Prior distributions encode beliefs about parameters before seeing data:&lt;/p&gt;

\[p(\theta|data) \propto p(data|\theta) \cdot p(\theta)\]

&lt;h4 id=&quot;regularization&quot;&gt;Regularization&lt;/h4&gt;
&lt;p&gt;Distributions can be used as priors to regularize deep-learning problems:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;L2 regularization ↔ Gaussian prior&lt;/li&gt;
  &lt;li&gt;L1 regularization ↔ Laplace prior&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;stochastic-deep-learning&quot;&gt;Stochastic Deep Learning&lt;/h4&gt;
&lt;p&gt;Distributions model noise and uncertainty in objective functions and constraints.&lt;/p&gt;

&lt;h3 id=&quot;key-insights-for-deep-learning&quot;&gt;Key Insights for Deep Learning&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Model Selection&lt;/strong&gt;: Choose distributions that match your data’s characteristics&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parameter Estimation&lt;/strong&gt;: Use MLE or Bayesian methods to estimate distribution parameters&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Uncertainty Quantification&lt;/strong&gt;: Distributions provide natural ways to quantify uncertainty&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Regularization&lt;/strong&gt;: Prior distributions can prevent overfitting&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Computational Efficiency&lt;/strong&gt;: Some distributions have closed-form solutions for common operations&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Understanding these distributions and their properties is crucial for formulating and solving deep-learning problems in machine learning, statistics, and engineering applications.&lt;/p&gt;

&lt;script&gt;
class MultivariateDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;multivariateCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.params = { mu1: 0, mu2: 0, sigma1: 1, sigma2: 1, rho: 0 };
        this.samples = [];
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const sliders = [&apos;mu1&apos;, &apos;mu2&apos;, &apos;sigma1&apos;, &apos;sigma2&apos;, &apos;rho&apos;];
        
        sliders.forEach(slider =&gt; {
            const element = document.getElementById(slider + &apos;-slider&apos;);
            element.addEventListener(&apos;input&apos;, (e) =&gt; {
                this.params[slider] = parseFloat(e.target.value);
                document.getElementById(slider + &apos;-value&apos;).textContent = this.params[slider].toFixed(1);
                this.updateStats();
                this.draw();
            });
        });
        
        document.getElementById(&apos;generate-samples&apos;).addEventListener(&apos;click&apos;, () =&gt; {
            this.generateSamples();
            this.draw();
        });
        
        this.updateStats();
    }
    
    updateStats() {
        const cov11 = this.params.sigma1 * this.params.sigma1;
        const cov12 = this.params.rho * this.params.sigma1 * this.params.sigma2;
        const cov22 = this.params.sigma2 * this.params.sigma2;
        const det = cov11 * cov22 - cov12 * cov12;
        
        document.getElementById(&apos;cov11&apos;).textContent = cov11.toFixed(3);
        document.getElementById(&apos;cov12&apos;).textContent = cov12.toFixed(3);
        document.getElementById(&apos;cov22&apos;).textContent = cov22.toFixed(3);
        document.getElementById(&apos;det-cov&apos;).textContent = det.toFixed(3);
    }
    
    generateSamples() {
        this.samples = [];
        const n = 100;
        
        for (let i = 0; i &lt; n; i++) {
            // Box-Muller transform
            const u1 = Math.random();
            const u2 = Math.random();
            const z1 = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
            const z2 = Math.sqrt(-2 * Math.log(u1)) * Math.sin(2 * Math.PI * u2);
            
            // Transform to correlated normal
            const x1 = this.params.mu1 + this.params.sigma1 * z1;
            const x2 = this.params.mu2 + this.params.sigma2 * (this.params.rho * z1 + Math.sqrt(1 - this.params.rho * this.params.rho) * z2);
            
            this.samples.push([x1, x2]);
        }
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        const marginX = 50;
        const marginY = 50;
        const plotWidth = this.width - 2 * marginX;
        const plotHeight = this.height - 2 * marginY;
        
        // Draw axes
        this.ctx.strokeStyle = &apos;#ddd&apos;;
        this.ctx.lineWidth = 1;
        this.ctx.beginPath();
        this.ctx.moveTo(marginX, this.height - marginY);
        this.ctx.lineTo(this.width - marginX, this.height - marginY);
        this.ctx.moveTo(marginX, marginY);
        this.ctx.lineTo(marginX, this.height - marginY);
        this.ctx.stroke();
        
        // Draw contour ellipses
        const levels = [0.5, 1, 1.5, 2];
        const colors = [&apos;#ff9999&apos;, &apos;#ff6666&apos;, &apos;#ff3333&apos;, &apos;#ff0000&apos;];
        
        levels.forEach((level, idx) =&gt; {
            this.ctx.strokeStyle = colors[idx];
            this.ctx.lineWidth = 1;
            this.ctx.beginPath();
            
            const a = level * this.params.sigma1;
            const b = level * this.params.sigma2;
            const angle = 0.5 * Math.atan2(2 * this.params.rho * this.params.sigma1 * this.params.sigma2,
                                          this.params.sigma1 * this.params.sigma1 - this.params.sigma2 * this.params.sigma2);
            
            for (let i = 0; i &lt;= 100; i++) {
                const t = 2 * Math.PI * i / 100;
                const x = a * Math.cos(t) * Math.cos(angle) - b * Math.sin(t) * Math.sin(angle) + this.params.mu1;
                const y = a * Math.cos(t) * Math.sin(angle) + b * Math.sin(t) * Math.cos(angle) + this.params.mu2;
                
                const plotX = marginX + (x + 4) / 8 * plotWidth;
                const plotY = this.height - marginY - (y + 4) / 8 * plotHeight;
                
                if (i === 0) {
                    this.ctx.moveTo(plotX, plotY);
                } else {
                    this.ctx.lineTo(plotX, plotY);
                }
            }
            this.ctx.stroke();
        });
        
        // Draw samples
        if (this.samples.length &gt; 0) {
            this.ctx.fillStyle = &apos;#2196f3&apos;;
            this.samples.forEach(([x1, x2]) =&gt; {
                const plotX = marginX + (x1 + 4) / 8 * plotWidth;
                const plotY = this.height - marginY - (x2 + 4) / 8 * plotHeight;
                
                if (plotX &gt;= marginX &amp;&amp; plotX &lt;= this.width - marginX &amp;&amp;
                    plotY &gt;= marginY &amp;&amp; plotY &lt;= this.height - marginY) {
                    this.ctx.beginPath();
                    this.ctx.arc(plotX, plotY, 2, 0, 2 * Math.PI);
                    this.ctx.fill();
                }
            });
        }
        
        // Draw mean point
        const meanX = marginX + (this.params.mu1 + 4) / 8 * plotWidth;
        const meanY = this.height - marginY - (this.params.mu2 + 4) / 8 * plotHeight;
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.beginPath();
        this.ctx.arc(meanX, meanY, 4, 0, 2 * Math.PI);
        this.ctx.fill();
        
        // Labels
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;12px Arial&apos;;
        this.ctx.textAlign = &apos;center&apos;;
        this.ctx.fillText(&apos;X₁&apos;, this.width / 2, this.height - 10);
        
        this.ctx.save();
        this.ctx.translate(15, this.height / 2);
        this.ctx.rotate(-Math.PI / 2);
        this.ctx.fillText(&apos;X₂&apos;, 0, 0);
        this.ctx.restore();
    }
}

// Initialize when DOM is loaded

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new MultivariateDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=UVvuwv-ne1I&quot;&gt;Multivariate Normal (Gaussian) Distribution Explained&lt;/a&gt; — DataMListic, English. The multivariate Gaussian is the joint distribution this lesson builds.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kmRm3XIND8M&quot;&gt;MaDL - Expectation, Variance and Covariance&lt;/a&gt; — Tübingen Machine Learning, English. Covariance is the matrix inside that Gaussian, and the lesson’s link to features that move together.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NbzVwvE_syQ&quot;&gt;MaDL - Common Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, English. Shows where the multivariate families sit relative to the one-dimensional distributions of the previous lesson.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-02-02 Continuous Distributions</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_02_02_Continuous_Distributions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_02_02_Continuous_Distributions</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Why do we initialize weights from a Uniform or Normal distribution, model latent codes in VAEs as standard Gaussians, and sample Mixup interpolation weights from a Beta distribution? Each continuous density has a distinct tail behavior and support that shapes optimization.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-continuous-densities-in-deep-learning&quot;&gt;Key ideas: Continuous Densities in Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Uniform Distribution (\(\mathcal{U}(a, b)\))&lt;/strong&gt;: Assigns flat density \(\frac{1}{b-a}\) across a bounded interval with variance \(\frac{(b-a)^2}{12}\), widely used in Glorot/He uniform weight initialization and hyperparameter random search.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Normal / Gaussian Distribution (\(\mathcal{N}(\mu, \sigma^2)\))&lt;/strong&gt;: The maximum-entropy distribution for fixed mean and variance; central to weight decay, Gaussian noise injection, diffusion forward processes, and Central Limit Theorem behavior in wide layers.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exponential Distribution (\(\text{Exp}(\lambda)\))&lt;/strong&gt;: Memoryless distribution on \([0, \infty)\) modeling waiting times and inter-arrival intervals, closely linked to Laplace priors (two-sided exponential) that induce \(L_1\) sparsity.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Beta Distribution (\(\text{Beta}(\alpha, \beta)\))&lt;/strong&gt;: Flexible distribution supported strictly on \([0, 1]\), ideal for modeling uncertain probabilities, Bayesian coin priors, and Mixup data augmentation coefficients \(\lambda \sim \text{Beta}(\alpha, \alpha)\).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-matching-uniform-and-normal-initialization-variances&quot;&gt;Worked example: Matching Uniform and Normal Initialization Variances&lt;/h3&gt;

&lt;p&gt;Suppose Xavier initialization for a layer with \(n_{\text{in}} = 100, n_{\text{out}} = 200\) calls for weight variance \(\sigma^2 = \frac{2}{n_{\text{in}} + n_{\text{out}}}\). Let us compute both the Normal and Uniform bounds by hand.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Target Variance&lt;/strong&gt;:
\(\sigma^2 = \frac{2}{100 + 200} = \frac{2}{300} = \frac{1}{150} \approx 0.006667\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xavier Normal Distribution \(\mathcal{N}(0, \sigma^2)\)&lt;/strong&gt;:
\(\sigma = \sqrt{\frac{1}{150}} \approx 0.08165\)
So we sample \(w_{ij} \sim \mathcal{N}(0, 0.08165^2)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Xavier Uniform Distribution \(\mathcal{U}(-a, a)\)&lt;/strong&gt;:
A symmetric uniform distribution on \([-a, a]\) has variance:
\(\text{Var}(W) = \frac{(a - (-a))^2}{12} = \frac{4a^2}{12} = \frac{a^2}{3}\)
Equate this to \(\sigma^2 = \frac{1}{150}\):
\(\frac{a^2}{3} = \frac{1}{150} \implies a^2 = \frac{3}{150} = \frac{1}{50} = 0.02 \implies a = \sqrt{0.02} \approx 0.14142\)
Notice why PyTorch’s &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;xavier_uniform_&lt;/code&gt; uses \(\sqrt{\frac{6}{n_{\text{in}} + n_{\text{out}}}}\) while &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;xavier_normal_&lt;/code&gt; uses \(\sqrt{\frac{2}{n_{\text{in}} + n_{\text{out}}}}\): the factor of \(\sqrt{3}\) comes directly from \(\text{Var}(\mathcal{U}(-a,a)) = a^2/3\)!&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;2-continuous-distributions&quot;&gt;2. Continuous Distributions&lt;/h3&gt;

&lt;h4 id=&quot;uniform-distribution&quot;&gt;Uniform Distribution&lt;/h4&gt;

&lt;p&gt;All values in an interval are equally likely.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parameters&lt;/strong&gt;: \(a, b \in \mathbb{R}\) with \(a &amp;lt; b\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PDF&lt;/strong&gt;: \(f(x) = \frac{1}{b-a}\) for \(x \in [a,b]\), 0 otherwise&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mean&lt;/strong&gt;: \(\mathbb{E}[X] = \frac{a+b}{2}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variance&lt;/strong&gt;: \(\text{Var}(X) = \frac{(b-a)^2}{12}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Applications&lt;/strong&gt;: Random sampling, initialization in algorithms&lt;/p&gt;

&lt;h4 id=&quot;normal-gaussian-distribution&quot;&gt;Normal (Gaussian) Distribution&lt;/h4&gt;

&lt;p&gt;The most important distribution in statistics and deep-learning.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parameters&lt;/strong&gt;: \(\mu \in \mathbb{R}\) (mean), \(\sigma^2 &amp;gt; 0\) (variance)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PDF&lt;/strong&gt;: \(f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mean&lt;/strong&gt;: \(\mathbb{E}[X] = \mu\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variance&lt;/strong&gt;: \(\text{Var}(X) = \sigma^2\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Properties&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Symmetric around \(\mu\)&lt;/li&gt;
  &lt;li&gt;68-95-99.7 rule&lt;/li&gt;
  &lt;li&gt;Central Limit Theorem&lt;/li&gt;
  &lt;li&gt;Maximum entropy for given mean and variance&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;exponential-distribution&quot;&gt;Exponential Distribution&lt;/h4&gt;

&lt;p&gt;Models waiting times between events in a Poisson process.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parameters&lt;/strong&gt;: \(\lambda &amp;gt; 0\) (rate parameter)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PDF&lt;/strong&gt;: \(f(x) = \lambda e^{-\lambda x}\) for \(x \geq 0\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mean&lt;/strong&gt;: \(\mathbb{E}[X] = \frac{1}{\lambda}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variance&lt;/strong&gt;: \(\text{Var}(X) = \frac{1}{\lambda^2}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Properties&lt;/strong&gt;: Memoryless property&lt;/p&gt;

&lt;h4 id=&quot;beta-distribution&quot;&gt;Beta Distribution&lt;/h4&gt;

&lt;p&gt;Flexible distribution on \([0,1]\), often used for modeling probabilities.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parameters&lt;/strong&gt;: \(\alpha, \beta &amp;gt; 0\) (shape parameters)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PDF&lt;/strong&gt;: \(f(x) = \frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)} x^{\alpha-1}(1-x)^{\beta-1}\) for \(x \in [0,1]\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mean&lt;/strong&gt;: \(\mathbb{E}[X] = \frac{\alpha}{\alpha+\beta}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variance&lt;/strong&gt;: \(\text{Var}(X) = \frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}\)&lt;/p&gt;

&lt;div id=&quot;continuous-distributions-demo&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f9f9f9;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Interactive Continuous Distributions&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;continuousCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;Visualization:&lt;/strong&gt; Probability density functions of continuous distributions.
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Distribution Type&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;continuous-dist&quot; value=&quot;uniform&quot; checked=&quot;&quot; /&gt; Uniform
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;continuous-dist&quot; value=&quot;normal&quot; /&gt; Normal
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;continuous-dist&quot; value=&quot;exponential&quot; /&gt; Exponential
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;continuous-dist&quot; value=&quot;beta&quot; /&gt; Beta
                    &lt;/label&gt;
                &lt;/div&gt;
                
                &lt;div id=&quot;continuous-params&quot;&gt;
                    &lt;div id=&quot;uniform-params&quot;&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;a-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;a: &lt;span id=&quot;a-value&quot;&gt;0&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;a-slider&quot; min=&quot;-2&quot; max=&quot;2&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;b-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;b: &lt;span id=&quot;b-value&quot;&gt;1&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;b-slider&quot; min=&quot;0.5&quot; max=&quot;4&quot; step=&quot;0.1&quot; value=&quot;1&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                    
                    &lt;div id=&quot;normal-params&quot; style=&quot;display: none;&quot;&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;mu-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;μ: &lt;span id=&quot;mu-value&quot;&gt;0&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;mu-slider&quot; min=&quot;-3&quot; max=&quot;3&quot; step=&quot;0.1&quot; value=&quot;0&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;sigma-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;σ: &lt;span id=&quot;sigma-value&quot;&gt;1.0&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;sigma-slider&quot; min=&quot;0.5&quot; max=&quot;3&quot; step=&quot;0.1&quot; value=&quot;1.0&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                    
                    &lt;div id=&quot;exponential-params&quot; style=&quot;display: none;&quot;&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;exp-lambda-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;λ: &lt;span id=&quot;exp-lambda-value&quot;&gt;1.0&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;exp-lambda-slider&quot; min=&quot;0.2&quot; max=&quot;3&quot; step=&quot;0.1&quot; value=&quot;1.0&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                    
                    &lt;div id=&quot;beta-params&quot; style=&quot;display: none;&quot;&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;alpha-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;α: &lt;span id=&quot;alpha-value&quot;&gt;2&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;alpha-slider&quot; min=&quot;0.5&quot; max=&quot;5&quot; step=&quot;0.1&quot; value=&quot;2&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                        &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                            &lt;label for=&quot;beta-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;β: &lt;span id=&quot;beta-value&quot;&gt;2&lt;/span&gt;&lt;/label&gt;
                            &lt;input type=&quot;range&quot; id=&quot;beta-slider&quot; min=&quot;0.5&quot; max=&quot;5&quot; step=&quot;0.1&quot; value=&quot;2&quot; style=&quot;width: 100%;&quot; /&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                
                &lt;div id=&quot;continuous-stats&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Statistics:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;Mean: &lt;span id=&quot;continuous-mean&quot;&gt;0.500&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Variance: &lt;span id=&quot;continuous-variance&quot;&gt;0.083&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Support: &lt;span id=&quot;continuous-support&quot;&gt;[0, 1]&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
class ContinuousDistributionsDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;continuousCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.distType = &apos;uniform&apos;;
        this.params = { a: 0, b: 1, mu: 0, sigma: 1, lambda: 1, alpha: 2, beta: 2 };
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const radios = document.querySelectorAll(&apos;input[name=&quot;continuous-dist&quot;]&apos;);
        
        radios.forEach(radio =&gt; {
            radio.addEventListener(&apos;change&apos;, (e) =&gt; {
                this.distType = e.target.value;
                this.updateParameterVisibility();
                this.updateStats();
                this.draw();
            });
        });
        
        // Setup all sliders
        const sliders = [&apos;a&apos;, &apos;b&apos;, &apos;mu&apos;, &apos;sigma&apos;, &apos;exp-lambda&apos;, &apos;alpha&apos;, &apos;beta&apos;];
        sliders.forEach(slider =&gt; {
            const element = document.getElementById(slider + &apos;-slider&apos;);
            if (element) {
                element.addEventListener(&apos;input&apos;, (e) =&gt; {
                    const value = parseFloat(e.target.value);
                    const param = slider === &apos;exp-lambda&apos; ? &apos;lambda&apos; : slider;
                    this.params[param] = value;
                    
                    const valueSpan = document.getElementById(slider + &apos;-value&apos;);
                    if (valueSpan) {
                        valueSpan.textContent = value.toFixed(1);
                    }
                    
                    this.updateStats();
                    this.draw();
                });
            }
        });
        
        this.updateParameterVisibility();
        this.updateStats();
    }
    
    updateParameterVisibility() {
        document.getElementById(&apos;uniform-params&apos;).style.display = 
            this.distType === &apos;uniform&apos; ? &apos;block&apos; : &apos;none&apos;;
        document.getElementById(&apos;normal-params&apos;).style.display = 
            this.distType === &apos;normal&apos; ? &apos;block&apos; : &apos;none&apos;;
        document.getElementById(&apos;exponential-params&apos;).style.display = 
            this.distType === &apos;exponential&apos; ? &apos;block&apos; : &apos;none&apos;;
        document.getElementById(&apos;beta-params&apos;).style.display = 
            this.distType === &apos;beta&apos; ? &apos;block&apos; : &apos;none&apos;;
    }
    
    updateStats() {
        let mean, variance, support;
        
        switch(this.distType) {
            case &apos;uniform&apos;:
                mean = (this.params.a + this.params.b) / 2;
                variance = Math.pow(this.params.b - this.params.a, 2) / 12;
                support = `[${this.params.a}, ${this.params.b}]`;
                break;
            case &apos;normal&apos;:
                mean = this.params.mu;
                variance = this.params.sigma * this.params.sigma;
                support = &apos;(-∞, ∞)&apos;;
                break;
            case &apos;exponential&apos;:
                mean = 1 / this.params.lambda;
                variance = 1 / (this.params.lambda * this.params.lambda);
                support = &apos;[0, ∞)&apos;;
                break;
            case &apos;beta&apos;:
                mean = this.params.alpha / (this.params.alpha + this.params.beta);
                variance = (this.params.alpha * this.params.beta) / 
                          (Math.pow(this.params.alpha + this.params.beta, 2) * 
                           (this.params.alpha + this.params.beta + 1));
                support = &apos;[0, 1]&apos;;
                break;
        }
        
        document.getElementById(&apos;continuous-mean&apos;).textContent = mean.toFixed(3);
        document.getElementById(&apos;continuous-variance&apos;).textContent = variance.toFixed(3);
        document.getElementById(&apos;continuous-support&apos;).textContent = support;
    }
    
    gamma(z) {
        // Stirling&apos;s approximation for gamma function
        if (z &lt; 0.5) return Math.PI / (Math.sin(Math.PI * z) * this.gamma(1 - z));
        z -= 1;
        let x = 0.99999999999980993;
        const p = [676.5203681218851, -1259.1392167224028, 771.32342877765313,
                  -176.61502916214059, 12.507343278686905, -0.13857109526572012,
                  9.9843695780195716e-6, 1.5056327351493116e-7];
        for (let i = 0; i &lt; p.length; i++) {
            x += p[i] / (z + i + 1);
        }
        const t = z + p.length - 0.5;
        return Math.sqrt(2 * Math.PI) * Math.pow(t, z + 0.5) * Math.exp(-t) * x;
    }
    
    getPDF(x) {
        switch(this.distType) {
            case &apos;uniform&apos;:
                return (x &gt;= this.params.a &amp;&amp; x &lt;= this.params.b) ? 
                       1 / (this.params.b - this.params.a) : 0;
            case &apos;normal&apos;:
                return Math.exp(-0.5 * Math.pow((x - this.params.mu) / this.params.sigma, 2)) / 
                       (this.params.sigma * Math.sqrt(2 * Math.PI));
            case &apos;exponential&apos;:
                return x &gt;= 0 ? this.params.lambda * Math.exp(-this.params.lambda * x) : 0;
            case &apos;beta&apos;:
                if (x &lt; 0 || x &gt; 1) return 0;
                const B = this.gamma(this.params.alpha) * this.gamma(this.params.beta) / 
                         this.gamma(this.params.alpha + this.params.beta);
                return Math.pow(x, this.params.alpha - 1) * Math.pow(1 - x, this.params.beta - 1) / B;
        }
    }
    
    getRange() {
        switch(this.distType) {
            case &apos;uniform&apos;: return [this.params.a - 0.5, this.params.b + 0.5];
            case &apos;normal&apos;: return [this.params.mu - 4 * this.params.sigma, this.params.mu + 4 * this.params.sigma];
            case &apos;exponential&apos;: return [0, 5 / this.params.lambda];
            case &apos;beta&apos;: return [0, 1];
        }
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        const marginX = 50;
        const marginY = 50;
        const plotWidth = this.width - 2 * marginX;
        const plotHeight = this.height - 2 * marginY;
        
        // Draw axes
        this.ctx.strokeStyle = &apos;#ddd&apos;;
        this.ctx.lineWidth = 1;
        this.ctx.beginPath();
        this.ctx.moveTo(marginX, this.height - marginY);
        this.ctx.lineTo(this.width - marginX, this.height - marginY);
        this.ctx.moveTo(marginX, marginY);
        this.ctx.lineTo(marginX, this.height - marginY);
        this.ctx.stroke();
        
        const [minX, maxX] = this.getRange();
        
        // Find max PDF for scaling
        let maxPDF = 0;
        for (let i = 0; i &lt;= 200; i++) {
            const x = minX + (maxX - minX) * i / 200;
            maxPDF = Math.max(maxPDF, this.getPDF(x));
        }
        
        // Draw PDF curve
        this.ctx.strokeStyle = &apos;#2196f3&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        
        for (let i = 0; i &lt;= 200; i++) {
            const x = minX + (maxX - minX) * i / 200;
            const pdf = this.getPDF(x);
            const plotX = marginX + (x - minX) / (maxX - minX) * plotWidth;
            const plotY = this.height - marginY - (pdf / maxPDF) * plotHeight * 0.8;
            
            if (i === 0) {
                this.ctx.moveTo(plotX, plotY);
            } else {
                this.ctx.lineTo(plotX, plotY);
            }
        }
        this.ctx.stroke();
        
        // Labels
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;12px Arial&apos;;
        this.ctx.textAlign = &apos;center&apos;;
        this.ctx.fillText(&apos;x&apos;, this.width / 2, this.height - 10);
        
        this.ctx.save();
        this.ctx.translate(15, this.height / 2);
        this.ctx.rotate(-Math.PI / 2);
        this.ctx.fillText(&apos;f(x)&apos;, 0, 0);
        this.ctx.restore();
    }
}

// Multivariate Normal Demo

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new ContinuousDistributionsDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=rzFX5NWojp0&quot;&gt;The Normal Distribution, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. The normal density is the continuous distribution this lesson centers on.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=oI3hZJqXJuc&quot;&gt;The Main Ideas behind Probability Distributions&lt;/a&gt; — StatQuest with Josh Starmer, English. Density versus mass is the distinction you need before any continuous formula.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=NbzVwvE_syQ&quot;&gt;MaDL - Common Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, English. Places the Gaussian among the other continuous families (exponential and others) the lesson lists.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-02-01 Discrete Distributions</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_02_01_Discrete_Distributions/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_02_01_Discrete_Distributions</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;When inverted dropout randomly zeros out neurons during training, it flips independent Bernoulli coins; when you count how many neurons survived across a layer, you get a Binomial variable; and when a server counts incoming inference requests per second, you get a Poisson distribution.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-discrete-distributions-in-neural-systems&quot;&gt;Key ideas: Discrete Distributions in Neural Systems&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Bernoulli Distribution (\(\text{Bern}(p)\))&lt;/strong&gt;: Models a single binary trial—binary classification targets, dropout keep-masks \(m_i \sim \text{Bern}(p)\), and pixel binarization—with mean \(p\) and variance \(p(1-p)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Binomial Distribution (\(\text{Bin}(n, p)\))&lt;/strong&gt;: Counts the number of successes in \(n\) independent Bernoulli trials, governing the distribution of active neurons in a dropout layer and exact confidence intervals for test-set accuracy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Categorical Distribution (\(\text{Cat}(\mathbf{p})\))&lt;/strong&gt;: Generalizes Bernoulli to \(K\) mutually exclusive classes, serving as the output distribution of every softmax classifier and autoregressive language model.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Poisson Distribution (\(\text{Pois}(\lambda)\))&lt;/strong&gt;: Models rare event counts per unit time or space (clicks, spikes in neuromorphic nets, arrivals) where mean equals variance (\(\lambda\)).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-exact-dropout-survival-probabilities-and-inverted-scaling&quot;&gt;Worked example: Exact Dropout Survival Probabilities and Inverted Scaling&lt;/h3&gt;

&lt;p&gt;Consider a tiny hidden layer with \(n = 4\) neurons, each with activation \(h_i = 2.0\), where dropout keeps each neuron independently with probability \(p = 0.5\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Distribution of Surviving Neurons \(K \sim \text{Bin}(4, 0.5)\)&lt;/strong&gt;:
\(P(K = k) = \binom{4}{k}(0.5)^k(0.5)^{4-k} = \frac{\binom{4}{k}}{16}\)
    &lt;ul&gt;
      &lt;li&gt;\(P(K = 0) = \frac{1}{16} = 0.0625\) (entire layer drops out!)&lt;/li&gt;
      &lt;li&gt;
\[P(K = 1) = \frac{4}{16} = 0.2500\]
      &lt;/li&gt;
      &lt;li&gt;
\[P(K = 2) = \frac{6}{16} = 0.3750\]
      &lt;/li&gt;
      &lt;li&gt;
\[P(K = 3) = \frac{4}{16} = 0.2500\]
      &lt;/li&gt;
      &lt;li&gt;\(P(K = 4) = \frac{1}{16} = 0.0625\)
Check sum: \((1 + 4 + 6 + 4 + 1)/16 = 16/16 = 1.0\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Expected Sum Without Inverted Scaling&lt;/strong&gt;:
With \(m_i \sim \text{Bern}(0.5)\), \(\mathbb{E}\!\left[\sum_{i=1}^4 m_i h_i\right] = 4 \times (0.5 \times 2.0) = 4.0\), which is only half of the test-time sum \(\sum_{i=1}^4 h_i = 8.0\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Fix via Inverted Dropout (Divide by \(p = 0.5\) During Training)&lt;/strong&gt;:
Define \(\tilde{h}_i = \frac{m_i}{p} h_i = 2 m_i h_i\). Now:
\(\mathbb{E}\!\left[\sum_{i=1}^4 \tilde{h}_i\right] = 4 \times 2 \times 0.5 \times 2.0 = 8.0\)
Training and inference expectations match identically with zero extra work at test time.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;common-probability-distributions&quot;&gt;Common Probability Distributions&lt;/h2&gt;

&lt;p&gt;Understanding key probability distributions is essential for deep-learning problems in machine learning and statistics. These distributions frequently appear as assumptions in models, priors in Bayesian methods, and error models in regression.&lt;/p&gt;

&lt;h3 id=&quot;1-discrete-distributions&quot;&gt;1. Discrete Distributions&lt;/h3&gt;

&lt;h4 id=&quot;bernoulli-distribution&quot;&gt;Bernoulli Distribution&lt;/h4&gt;

&lt;p&gt;Models a single trial with two outcomes (success/failure).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parameters&lt;/strong&gt;: \(p \in [0,1]\) (probability of success)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PMF&lt;/strong&gt;: \(P(X = k) = p^k (1-p)^{1-k}\) for \(k \in \{0,1\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mean&lt;/strong&gt;: \(\mathbb{E}[X] = p\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variance&lt;/strong&gt;: \(\text{Var}(X) = p(1-p)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Applications&lt;/strong&gt;: Binary classification, coin flips, A/B testing&lt;/p&gt;

&lt;h4 id=&quot;binomial-distribution&quot;&gt;Binomial Distribution&lt;/h4&gt;

&lt;p&gt;Models the number of successes in \(n\) independent Bernoulli trials.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parameters&lt;/strong&gt;: \(n \in \mathbb{N}\) (trials), \(p \in [0,1]\) (success probability)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PMF&lt;/strong&gt;: \(P(X = k) = \binom{n}{k} p^k (1-p)^{n-k}\) for \(k = 0,1,\ldots,n\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mean&lt;/strong&gt;: \(\mathbb{E}[X] = np\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variance&lt;/strong&gt;: \(\text{Var}(X) = np(1-p)\)&lt;/p&gt;

&lt;h4 id=&quot;poisson-distribution&quot;&gt;Poisson Distribution&lt;/h4&gt;

&lt;p&gt;Models the number of events in a fixed interval when events occur independently at a constant rate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Parameters&lt;/strong&gt;: \(\lambda &amp;gt; 0\) (rate parameter)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PMF&lt;/strong&gt;: \(P(X = k) = \frac{\lambda^k e^{-\lambda}}{k!}\) for \(k = 0,1,2,\ldots\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Mean&lt;/strong&gt;: \(\mathbb{E}[X] = \lambda\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Variance&lt;/strong&gt;: \(\text{Var}(X) = \lambda\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Applications&lt;/strong&gt;: Count data, rare events, queueing theory&lt;/p&gt;

&lt;div id=&quot;discrete-distributions-demo&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f9f9f9;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Interactive Discrete Distributions&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;discreteCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;Visualization:&lt;/strong&gt; Probability mass functions of discrete distributions.
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Distribution Type&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;discrete-dist&quot; value=&quot;bernoulli&quot; checked=&quot;&quot; /&gt; Bernoulli
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;discrete-dist&quot; value=&quot;binomial&quot; /&gt; Binomial
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;discrete-dist&quot; value=&quot;poisson&quot; /&gt; Poisson
                    &lt;/label&gt;
                &lt;/div&gt;
                
                &lt;div id=&quot;discrete-params&quot;&gt;
                    &lt;div id=&quot;p-param&quot; style=&quot;margin-bottom: 15px;&quot;&gt;
                        &lt;label for=&quot;p-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;p: &lt;span id=&quot;p-value&quot;&gt;0.5&lt;/span&gt;&lt;/label&gt;
                        &lt;input type=&quot;range&quot; id=&quot;p-slider&quot; min=&quot;0.1&quot; max=&quot;0.9&quot; step=&quot;0.05&quot; value=&quot;0.5&quot; style=&quot;width: 100%;&quot; /&gt;
                    &lt;/div&gt;
                    
                    &lt;div id=&quot;n-param&quot; style=&quot;margin-bottom: 15px; display: none;&quot;&gt;
                        &lt;label for=&quot;n-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;n: &lt;span id=&quot;n-value&quot;&gt;10&lt;/span&gt;&lt;/label&gt;
                        &lt;input type=&quot;range&quot; id=&quot;n-slider&quot; min=&quot;5&quot; max=&quot;50&quot; step=&quot;1&quot; value=&quot;10&quot; style=&quot;width: 100%;&quot; /&gt;
                    &lt;/div&gt;
                    
                    &lt;div id=&quot;lambda-param&quot; style=&quot;margin-bottom: 15px; display: none;&quot;&gt;
                        &lt;label for=&quot;lambda-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;λ: &lt;span id=&quot;lambda-value&quot;&gt;3.0&lt;/span&gt;&lt;/label&gt;
                        &lt;input type=&quot;range&quot; id=&quot;lambda-slider&quot; min=&quot;0.5&quot; max=&quot;10&quot; step=&quot;0.5&quot; value=&quot;3.0&quot; style=&quot;width: 100%;&quot; /&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
                
                &lt;div id=&quot;discrete-stats&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Statistics:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;Mean: &lt;span id=&quot;discrete-mean&quot;&gt;0.500&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Variance: &lt;span id=&quot;discrete-variance&quot;&gt;0.250&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Mode: &lt;span id=&quot;discrete-mode&quot;&gt;0 or 1&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
class DiscreteDistributionsDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;discreteCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.distType = &apos;bernoulli&apos;;
        this.params = { p: 0.5, n: 10, lambda: 3.0 };
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const radios = document.querySelectorAll(&apos;input[name=&quot;discrete-dist&quot;]&apos;);
        const pSlider = document.getElementById(&apos;p-slider&apos;);
        const nSlider = document.getElementById(&apos;n-slider&apos;);
        const lambdaSlider = document.getElementById(&apos;lambda-slider&apos;);
        
        radios.forEach(radio =&gt; {
            radio.addEventListener(&apos;change&apos;, (e) =&gt; {
                this.distType = e.target.value;
                this.updateParameterVisibility();
                this.updateStats();
                this.draw();
            });
        });
        
        pSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.params.p = parseFloat(e.target.value);
            document.getElementById(&apos;p-value&apos;).textContent = this.params.p.toFixed(1);
            this.updateStats();
            this.draw();
        });
        
        nSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.params.n = parseInt(e.target.value);
            document.getElementById(&apos;n-value&apos;).textContent = this.params.n;
            this.updateStats();
            this.draw();
        });
        
        lambdaSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.params.lambda = parseFloat(e.target.value);
            document.getElementById(&apos;lambda-value&apos;).textContent = this.params.lambda.toFixed(1);
            this.updateStats();
            this.draw();
        });
        
        this.updateParameterVisibility();
        this.updateStats();
    }
    
    updateParameterVisibility() {
        document.getElementById(&apos;p-param&apos;).style.display = 
            (this.distType === &apos;bernoulli&apos; || this.distType === &apos;binomial&apos;) ? &apos;block&apos; : &apos;none&apos;;
        document.getElementById(&apos;n-param&apos;).style.display = 
            this.distType === &apos;binomial&apos; ? &apos;block&apos; : &apos;none&apos;;
        document.getElementById(&apos;lambda-param&apos;).style.display = 
            this.distType === &apos;poisson&apos; ? &apos;block&apos; : &apos;none&apos;;
    }
    
    updateStats() {
        let mean, variance, mode;
        
        switch(this.distType) {
            case &apos;bernoulli&apos;:
                mean = this.params.p;
                variance = this.params.p * (1 - this.params.p);
                mode = this.params.p &gt; 0.5 ? &apos;1&apos; : (this.params.p &lt; 0.5 ? &apos;0&apos; : &apos;0 or 1&apos;);
                break;
            case &apos;binomial&apos;:
                mean = this.params.n * this.params.p;
                variance = this.params.n * this.params.p * (1 - this.params.p);
                mode = Math.floor((this.params.n + 1) * this.params.p).toString();
                break;
            case &apos;poisson&apos;:
                mean = this.params.lambda;
                variance = this.params.lambda;
                mode = Math.floor(this.params.lambda).toString();
                break;
        }
        
        document.getElementById(&apos;discrete-mean&apos;).textContent = mean.toFixed(3);
        document.getElementById(&apos;discrete-variance&apos;).textContent = variance.toFixed(3);
        document.getElementById(&apos;discrete-mode&apos;).textContent = mode;
    }
    
    factorial(n) {
        if (n &lt;= 1) return 1;
        return n * this.factorial(n - 1);
    }
    
    binomialCoeff(n, k) {
        if (k &gt; n) return 0;
        return this.factorial(n) / (this.factorial(k) * this.factorial(n - k));
    }
    
    getProbability(k) {
        switch(this.distType) {
            case &apos;bernoulli&apos;:
                return k === 0 ? (1 - this.params.p) : (k === 1 ? this.params.p : 0);
            case &apos;binomial&apos;:
                if (k &lt; 0 || k &gt; this.params.n) return 0;
                return this.binomialCoeff(this.params.n, k) * 
                       Math.pow(this.params.p, k) * 
                       Math.pow(1 - this.params.p, this.params.n - k);
            case &apos;poisson&apos;:
                if (k &lt; 0) return 0;
                return Math.pow(this.params.lambda, k) * Math.exp(-this.params.lambda) / this.factorial(k);
        }
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        const marginX = 50;
        const marginY = 50;
        const plotWidth = this.width - 2 * marginX;
        const plotHeight = this.height - 2 * marginY;
        
        // Draw axes
        this.ctx.strokeStyle = &apos;#ddd&apos;;
        this.ctx.lineWidth = 1;
        this.ctx.beginPath();
        this.ctx.moveTo(marginX, this.height - marginY);
        this.ctx.lineTo(this.width - marginX, this.height - marginY);
        this.ctx.moveTo(marginX, marginY);
        this.ctx.lineTo(marginX, this.height - marginY);
        this.ctx.stroke();
        
        // Determine range
        let maxK;
        switch(this.distType) {
            case &apos;bernoulli&apos;: maxK = 1; break;
            case &apos;binomial&apos;: maxK = this.params.n; break;
            case &apos;poisson&apos;: maxK = Math.min(20, this.params.lambda + 3 * Math.sqrt(this.params.lambda)); break;
        }
        
        // Find max probability for scaling
        let maxProb = 0;
        for (let k = 0; k &lt;= maxK; k++) {
            maxProb = Math.max(maxProb, this.getProbability(k));
        }
        
        // Draw bars
        this.ctx.fillStyle = &apos;#2196f3&apos;;
        const barWidth = plotWidth / (maxK + 2);
        
        for (let k = 0; k &lt;= maxK; k++) {
            const prob = this.getProbability(k);
            const x = marginX + (k + 0.5) * barWidth;
            const height = (prob / maxProb) * plotHeight * 0.8;
            const y = this.height - marginY - height;
            
            this.ctx.fillRect(x - barWidth * 0.3, y, barWidth * 0.6, height);
            
            // Label
            this.ctx.fillStyle = &apos;#000&apos;;
            this.ctx.font = &apos;10px Arial&apos;;
            this.ctx.textAlign = &apos;center&apos;;
            this.ctx.fillText(k.toString(), x, this.height - marginY + 15);
            this.ctx.fillText(prob.toFixed(3), x, y - 5);
            this.ctx.fillStyle = &apos;#2196f3&apos;;
        }
        
        // Labels
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;12px Arial&apos;;
        this.ctx.textAlign = &apos;center&apos;;
        this.ctx.fillText(&apos;k&apos;, this.width / 2, this.height - 10);
        
        this.ctx.save();
        this.ctx.translate(15, this.height / 2);
        this.ctx.rotate(-Math.PI / 2);
        this.ctx.fillText(&apos;P(X = k)&apos;, 0, 0);
        this.ctx.restore();
    }
}

// Continuous Distributions Demo

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new DiscreteDistributionsDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=J8jNoF-K8E8&quot;&gt;The Binomial Distribution and Test, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Bernoulli trials and the binomial distribution are the main discrete models in the lesson.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Binomial distributions&lt;/td&gt;
          &lt;td&gt;Probabilities of probabilities, part 1](https://www.youtube.com/watch?v=8idr1WZ1A7Q) — 3Blue1Brown, English. A geometric view of the same binomial probabilities, useful when the count of successes is the random variable.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=jmqZG6roVqU&quot;&gt;An Introduction to the Poisson Distribution&lt;/a&gt; — jbstatistics, English. The Poisson distribution is the other discrete family the lesson typically sets next to the binomial.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-01 Basic Probability Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_01_Basic_Probability_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_01_Basic_Probability_Theory</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Before you can understand why a language model predicts the next token conditioned on 100,000 previous tokens, or why variational autoencoders work, you need the bedrock laws of probability: sample spaces, Kolmogorov’s axioms, Bayes’ theorem, and random variables.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-three-building-blocks-of-probability-theory&quot;&gt;Key ideas: Three Building Blocks of Probability Theory&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sample Spaces &amp;amp; Kolmogorov Axioms&lt;/strong&gt;: Establishes the minimal rules—non-negativity, unit total mass, and countable additivity—from which every probability identity follows without contradiction.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conditional Probability &amp;amp; Independence&lt;/strong&gt;: Formalizes how observing context \(B\) reshapes the probability of \(A\) via \(P(A\mid B) = P(A \cap B)/P(B)\), and defines conditional independence—the structural assumption powering autoregressive factorization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Random Variables &amp;amp; Moments&lt;/strong&gt;: Maps abstract outcomes to real numbers so we can compute means (expected values), variances (spread), and covariances (linear co-movement) across activations and gradients.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-autoregressive-chain-rule-on-a-3-token-sequence&quot;&gt;Worked example: Autoregressive Chain Rule on a 3-Token Sequence&lt;/h3&gt;

&lt;p&gt;Consider a tiny vocabulary \(\{\text{The}, \text{cat}, \text{slept}\}\) where a language model assigns:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[P(w_1 = \text{The}) = 0.40\]
  &lt;/li&gt;
  &lt;li&gt;
\[P(w_2 = \text{cat} \mid w_1 = \text{The}) = 0.25\]
  &lt;/li&gt;
  &lt;li&gt;
\[P(w_3 = \text{slept} \mid w_1 = \text{The}, w_2 = \text{cat}) = 0.50\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Apply the Chain Rule of Probability&lt;/strong&gt;:
\(P(w_1, w_2, w_3) = P(w_1)\,P(w_2 \mid w_1)\,P(w_3 \mid w_1, w_2)\)
\(P(\text{&quot;The cat slept&quot;}) = 0.40 \times 0.25 \times 0.50 = 0.05\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convert to Log-Probability and Perplexity&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Log-probability: \(\ln(0.05) = \ln(0.40) + \ln(0.25) + \ln(0.50) \approx -0.9163 - 1.3863 - 0.6931 = -2.9957\).&lt;/li&gt;
      &lt;li&gt;Average negative log-likelihood per token: \(\text{NLL} = \frac{2.9957}{3} \approx 0.9986\).&lt;/li&gt;
      &lt;li&gt;Perplexity: \(\text{PPL} = e^{0.9986} = (0.05)^{-1/3} = 20^{1/3} \approx 2.714\).
A single identity from basic probability—the chain rule—is literally the training and evaluation backbone of every modern LLM.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers basic probability theory for deep learning, split into focused sections:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sample Spaces and Probability Axioms&lt;/strong&gt; — sample spaces, events, Kolmogorov axioms, and basic rules&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conditional Probability and Independence&lt;/strong&gt; — conditioning, Bayes-related intuition, and independence&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Random Variables and Deep Learning&lt;/strong&gt; — random variables, MLE connection, and key takeaways&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Interactive demos are included in each section.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pA83XtLeVig&quot;&gt;L01.4 Probability Axioms&lt;/a&gt; — MIT OpenCourseWare, English. The axiom lesson this overview introduces.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=_IgyaD7vOOA&quot;&gt;Conditional Probabilities, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Conditional probability is the second lesson in the block.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=bvBukLjHZh8&quot;&gt;MaDL - Random Variables and Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, English. Random variables are the third lesson, tied to how a network sees data.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-01-03 Random Variables and Deep Learning</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_01_03_Random_Variables_and_Deep_Learning/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_01_03_Random_Variables_and_Deep_Learning</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Every weight initialization, every dropout mask, every mini-batch gradient, and every latent vector in a VAE is a random variable. Understanding expectation, variance, and linearity of expectation lets you predict whether activations will blow up across 100 layers before you even run a single epoch.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-random-variables-and-moment-propagation&quot;&gt;Key ideas: Random Variables and Moment Propagation&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Discrete vs. Continuous Random Variables&lt;/strong&gt;: Describes quantities via probability mass functions (PMFs) for discrete tokens/masks and probability density functions (PDFs) for continuous weights/activations.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Linearity of Expectation (Always Holds)&lt;/strong&gt;: Even when variables are correlated, \(\mathbb{E}[aX + bY] = a\mathbb{E}[X] + b\mathbb{E}[Y]\), which guarantees that mini-batch SGD gradients are unbiased estimators of the full-dataset gradient.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Variance Scaling (The Key to Initialization)&lt;/strong&gt;: For independent variables, \(\text{Var}(aX + bY) = a^2\text{Var}(X) + b^2\text{Var}(Y)\); this quadratic scaling by \(a^2\) is the exact derivation behind Xavier/Glorot and He initialization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Law of the Unconscious Statistician (LOTUS)&lt;/strong&gt;: Computes \(\mathbb{E}[g(X)]\) directly from the distribution of \(X\) without deriving the distribution of \(g(X)\), enabling Monte Carlo gradient estimation in stochastic networks.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-deriving-variance-preservation-for-a-linear-layer&quot;&gt;Worked example: Deriving Variance Preservation for a Linear Layer&lt;/h3&gt;

&lt;p&gt;Consider a single neuron computing \(z = \sum_{i=1}^{n} w_i x_i\) with \(n = 100\) inputs, where inputs \(x_i\) and weights \(w_i\) are mutually independent with mean \(0\), input variance \(\text{Var}(x_i) = 1\), and weight variance \(\text{Var}(w_i) = \sigma_w^2\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Mean of Each Product \(w_i x_i\)&lt;/strong&gt;:
By independence, \(\mathbb{E}[w_i x_i] = \mathbb{E}[w_i]\mathbb{E}[x_i] = 0 \times 0 = 0\).
By linearity of expectation, \(\mathbb{E}[z] = \sum_{i=1}^{100} 0 = 0\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Variance of Each Product \(w_i x_i\)&lt;/strong&gt;:
Since both means are zero:
\(\text{Var}(w_i x_i) = \mathbb{E}[(w_i x_i)^2] - 0^2 = \mathbb{E}[w_i^2]\mathbb{E}[x_i^2] = \text{Var}(w_i)\text{Var}(x_i) = \sigma_w^2 \cdot 1 = \sigma_w^2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sum Variances Across All \(n = 100\) Independent Terms&lt;/strong&gt;:
\(\text{Var}(z) = \sum_{i=1}^{100} \text{Var}(w_i x_i) = 100\,\sigma_w^2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Solve for Signal-Preserving Weight Scale&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;If you naively initialize \(\sigma_w = 1\), then \(\text{Var}(z) = 100\) after just one layer (and \(100^{10} = 10^{20}\) after 10 layers!).&lt;/li&gt;
      &lt;li&gt;Setting \(\text{Var}(z) = 1\) requires \(100\,\sigma_w^2 = 1 \implies \sigma_w = \frac{1}{\sqrt{100}} = 0.1\). That exact calculation is Xavier/LeCun initialization!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;6-random-variables&quot;&gt;6. Random Variables&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;random variable&lt;/strong&gt; X is a function that assigns a real number to each outcome in the sample space:
\(X: \Omega \rightarrow \mathbb{R}\)&lt;/p&gt;

&lt;h4 id=&quot;types-of-random-variables&quot;&gt;Types of Random Variables:&lt;/h4&gt;

&lt;p&gt;&lt;strong&gt;Discrete&lt;/strong&gt;: Takes countable values (e.g., number of heads in coin flips)&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Probability Mass Function (PMF): \(P(X = x)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Continuous&lt;/strong&gt;: Takes uncountable values (e.g., height, weight)&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Probability Density Function (PDF): \(f_X(x)\)&lt;/li&gt;
  &lt;li&gt;
\[P(a \leq X \leq b) = \int_a^b f_X(x) dx\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;7-connection-to-deep-learning&quot;&gt;7. Connection to Deep Learning&lt;/h3&gt;

&lt;p&gt;Probability theory connects to deep-learning in several ways:&lt;/p&gt;

&lt;h4 id=&quot;maximum-likelihood-estimation&quot;&gt;Maximum Likelihood Estimation&lt;/h4&gt;
&lt;p&gt;Find parameters θ that maximize the likelihood:
\(\hat{\theta} = \arg\max_\theta P(\text{data}|\theta)\)&lt;/p&gt;

&lt;h4 id=&quot;expected-value-deep-learning&quot;&gt;Expected Value Deep Learning&lt;/h4&gt;
&lt;p&gt;Minimize expected loss:
\(\min_\theta \mathbb{E}[L(Y, f(X; \theta))]\)&lt;/p&gt;

&lt;h4 id=&quot;bayesian-deep-learning&quot;&gt;Bayesian Deep Learning&lt;/h4&gt;
&lt;p&gt;Use probability distributions to model uncertainty in objective functions and guide search for optimal solutions.&lt;/p&gt;

&lt;div id=&quot;deep-learning-connection&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f0f8ff;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Probability in Deep Learning Example&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;deep-learningCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;MLE Example:&lt;/strong&gt; Finding the parameter μ that maximizes likelihood of observed data from Normal(μ, 1).
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;MLE Demo&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;true-mu-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;True μ: &lt;span id=&quot;true-mu-value&quot;&gt;2.0&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;true-mu-slider&quot; min=&quot;-2&quot; max=&quot;4&quot; step=&quot;0.1&quot; value=&quot;2.0&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;sample-size-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;Sample Size: &lt;span id=&quot;sample-size-value&quot;&gt;20&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;sample-size-slider&quot; min=&quot;5&quot; max=&quot;100&quot; step=&quot;5&quot; value=&quot;20&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;button id=&quot;generate-mle-data&quot; style=&quot;width: 100%; padding: 10px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer; margin-bottom: 15px;&quot;&gt;Generate Data &amp;amp; Find MLE&lt;/button&gt;
                
                &lt;div id=&quot;mle-results&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Results:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;True μ: &lt;span id=&quot;display-true-mu&quot;&gt;2.000&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Sample mean: &lt;span id=&quot;sample-mean&quot;&gt;--&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;MLE estimate: &lt;span id=&quot;mle-estimate&quot;&gt;--&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Error: &lt;span id=&quot;mle-error&quot;&gt;--&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;key-takeaways&quot;&gt;Key Takeaways&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Foundation&lt;/strong&gt;: Probability axioms provide the mathematical foundation for reasoning about uncertainty&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conditional Probability&lt;/strong&gt;: Essential for updating beliefs with new information&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Independence&lt;/strong&gt;: Simplifies calculations and modeling assumptions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Random Variables&lt;/strong&gt;: Bridge between abstract probability and concrete applications&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Deep Learning Connection&lt;/strong&gt;: Many deep-learning problems arise from probabilistic modeling&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Understanding these basics prepares you for more advanced topics like Bayesian inference, maximum likelihood estimation, and stochastic deep-learning that are central to modern machine learning and data science.&lt;/p&gt;

&lt;script&gt;
// MLE Deep Learning Demo
class MLEDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;deep-learningCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.trueMu = 2.0;
        this.sampleSize = 20;
        this.data = [];
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const trueMuSlider = document.getElementById(&apos;true-mu-slider&apos;);
        const sampleSizeSlider = document.getElementById(&apos;sample-size-slider&apos;);
        const generateBtn = document.getElementById(&apos;generate-mle-data&apos;);
        
        trueMuSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.trueMu = parseFloat(e.target.value);
            document.getElementById(&apos;true-mu-value&apos;).textContent = this.trueMu.toFixed(1);
            document.getElementById(&apos;display-true-mu&apos;).textContent = this.trueMu.toFixed(3);
        });
        
        sampleSizeSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.sampleSize = parseInt(e.target.value);
            document.getElementById(&apos;sample-size-value&apos;).textContent = this.sampleSize;
        });
        
        generateBtn.addEventListener(&apos;click&apos;, () =&gt; this.generateDataAndFindMLE());
    }
    
    generateDataAndFindMLE() {
        // Generate data from Normal(trueMu, 1)
        this.data = [];
        for (let i = 0; i &lt; this.sampleSize; i++) {
            // Box-Muller transform for normal distribution
            const u1 = Math.random();
            const u2 = Math.random();
            const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
            this.data.push(this.trueMu + z); // Normal(trueMu, 1)
        }
        
        // Calculate MLE (sample mean for normal distribution)
        const sampleMean = this.data.reduce((sum, x) =&gt; sum + x, 0) / this.data.length;
        const error = Math.abs(sampleMean - this.trueMu);
        
        // Update display
        document.getElementById(&apos;sample-mean&apos;).textContent = sampleMean.toFixed(3);
        document.getElementById(&apos;mle-estimate&apos;).textContent = sampleMean.toFixed(3);
        document.getElementById(&apos;mle-error&apos;).textContent = error.toFixed(3);
        
        this.draw();
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        if (this.data.length === 0) {
            this.ctx.fillStyle = &apos;#666&apos;;
            this.ctx.font = &apos;16px Arial&apos;;
            this.ctx.textAlign = &apos;center&apos;;
            this.ctx.fillText(&apos;Click &quot;Generate Data &amp; Find MLE&quot; to start&apos;, this.width / 2, this.height / 2);
            return;
        }
        
        // Draw axes
        this.ctx.strokeStyle = &apos;#ddd&apos;;
        this.ctx.lineWidth = 1;
        const marginX = 50;
        const marginY = 50;
        const plotWidth = this.width - 2 * marginX;
        const plotHeight = this.height - 2 * marginY;
        
        // X-axis
        this.ctx.beginPath();
        this.ctx.moveTo(marginX, this.height - marginY);
        this.ctx.lineTo(this.width - marginX, this.height - marginY);
        this.ctx.stroke();
        
        // Y-axis
        this.ctx.beginPath();
        this.ctx.moveTo(marginX, marginY);
        this.ctx.lineTo(marginX, this.height - marginY);
        this.ctx.stroke();
        
        // Find data range
        const minX = Math.min(...this.data) - 1;
        const maxX = Math.max(...this.data) + 1;
        
        // Draw likelihood function
        this.ctx.strokeStyle = &apos;#2196f3&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        
        for (let i = 0; i &lt;= 100; i++) {
            const mu = minX + (maxX - minX) * i / 100;
            let logLikelihood = 0;
            
            // Calculate log-likelihood
            for (const x of this.data) {
                logLikelihood -= 0.5 * Math.log(2 * Math.PI);
                logLikelihood -= 0.5 * (x - mu) * (x - mu);
            }
            
            const x = marginX + (mu - minX) / (maxX - minX) * plotWidth;
            const y = this.height - marginY - (logLikelihood - (-this.data.length * 2)) / (this.data.length) * plotHeight * 0.8;
            
            if (i === 0) {
                this.ctx.moveTo(x, y);
            } else {
                this.ctx.lineTo(x, y);
            }
        }
        this.ctx.stroke();
        
        // Mark MLE
        const sampleMean = this.data.reduce((sum, x) =&gt; sum + x, 0) / this.data.length;
        const mleX = marginX + (sampleMean - minX) / (maxX - minX) * plotWidth;
        
        this.ctx.strokeStyle = &apos;#f44336&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        this.ctx.moveTo(mleX, marginY);
        this.ctx.lineTo(mleX, this.height - marginY);
        this.ctx.stroke();
        
        // Mark true value
        const trueX = marginX + (this.trueMu - minX) / (maxX - minX) * plotWidth;
        this.ctx.strokeStyle = &apos;#4caf50&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.setLineDash([5, 5]);
        this.ctx.beginPath();
        this.ctx.moveTo(trueX, marginY);
        this.ctx.lineTo(trueX, this.height - marginY);
        this.ctx.stroke();
        this.ctx.setLineDash([]);
        
        // Draw data points
        this.ctx.fillStyle = &apos;#666&apos;;
        for (const x of this.data) {
            const pointX = marginX + (x - minX) / (maxX - minX) * plotWidth;
            this.ctx.beginPath();
            this.ctx.arc(pointX, this.height - marginY + 10, 2, 0, 2 * Math.PI);
            this.ctx.fill();
        }
        
        // Labels
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;12px Arial&apos;;
        this.ctx.textAlign = &apos;center&apos;;
        this.ctx.fillText(&apos;μ&apos;, this.width / 2, this.height - 10);
        
        this.ctx.save();
        this.ctx.translate(15, this.height / 2);
        this.ctx.rotate(-Math.PI / 2);
        this.ctx.fillText(&apos;Log-Likelihood&apos;, 0, 0);
        this.ctx.restore();
        
        // Legend
        this.ctx.textAlign = &apos;left&apos;;
        this.ctx.fillText(&apos;— Likelihood&apos;, 10, 20);
        this.ctx.fillStyle = &apos;#f44336&apos;;
        this.ctx.fillText(&apos;— MLE&apos;, 10, 35);
        this.ctx.fillStyle = &apos;#4caf50&apos;;
        this.ctx.fillText(&apos;--- True μ&apos;, 10, 50);
    }
}

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new MLEDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=bvBukLjHZh8&quot;&gt;MaDL - Random Variables and Probability Distributions&lt;/a&gt; — Tübingen Machine Learning, English. A random variable is a function on the sample space, which is how the lesson treats data and predictions.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=lHCpYeFvTs0&quot;&gt;Random Variables and Probability Distributions&lt;/a&gt; — Dr Nic’s Maths and Stats, English. A short concrete pass over discrete and continuous random variables before the distribution catalog.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=kmRm3XIND8M&quot;&gt;MaDL - Expectation, Variance and Covariance&lt;/a&gt; — Tübingen Machine Learning, English. Expectation and variance are the summaries the lesson uses when a network’s output is random.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-01-02 Conditional Probability and Independence</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_01_02_Conditional_Probability_and_Independence/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_01_02_Conditional_Probability_and_Independence</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;A medical AI boasts 95% sensitivity and 95% specificity on a rare cancer affecting 1% of patients—yet when it flags a patient positive, the patient still has an 84% chance of being completely healthy. Without conditional probability and Bayes’ theorem, even experienced engineers misread classifier outputs.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-conditioning-bayes-rule-and-independence&quot;&gt;Key ideas: Conditioning, Bayes’ Rule, and Independence&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Conditional Probability (Restricting the Universe)&lt;/strong&gt;: Computes \(P(A\mid B) = P(A \cap B)/P(B)\) by shrinking the sample space to outcomes where \(B\) occurred and renormalizing probabilities to sum to 1.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bayes’ Theorem (Inverting Evidence)&lt;/strong&gt;: Relates posterior \(P(y\mid x)\) to likelihood \(P(x\mid y)\) and prior \(P(y)\) via \(P(y\mid x) = \frac{P(x\mid y)P(y)}{P(x)}\), explaining why base rates (class imbalance) dominate precision.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Statistical Independence vs. Mutual Exclusivity&lt;/strong&gt;: Two events with nonzero probability are independent iff \(P(A\cap B) = P(A)P(B)\); mutually exclusive events (\(P(A\cap B)=0\)) are actually &lt;em&gt;maximally dependent&lt;/em&gt; because one rules out the other.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Conditional Independence (Graphical Models &amp;amp; Naive Bayes)&lt;/strong&gt;: Allows high-dimensional joint distributions to factorize cleanly once a latent cause or context variable is observed.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-the-base-rate-trap-in-imbalanced-classification&quot;&gt;Worked example: The Base-Rate Trap in Imbalanced Classification&lt;/h3&gt;

&lt;p&gt;A fraud detector evaluates transactions where only \(P(F) = 0.01\) (1%) are fraudulent. The model has:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;True Positive Rate (sensitivity): \(P(+\mid F) = 0.95\)&lt;/li&gt;
  &lt;li&gt;False Positive Rate: \(P(+\mid F^c) = 0.05\) (95% specificity)&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Joint Probabilities&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;True positive mass: \(P(+ \cap F) = P(+\mid F)P(F) = 0.95 \times 0.01 = 0.0095\)&lt;/li&gt;
      &lt;li&gt;False positive mass: \(P(+ \cap F^c) = P(+\mid F^c)P(F^c) = 0.05 \times 0.99 = 0.0495\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Total Flag Rate via Law of Total Probability&lt;/strong&gt;:
\(P(+) = P(+ \cap F) + P(+ \cap F^c) = 0.0095 + 0.0495 = 0.0590\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply Bayes’ Theorem for Precision \(P(F \mid +)\)&lt;/strong&gt;:
\(P(F \mid +) = \frac{P(+ \cap F)}{P(+)} = \frac{0.0095}{0.0590} = \frac{95}{590} \approx 0.1610 \quad (16.1\%)\)
Even with 95% accuracy on both classes, 83.9% of alerts are false alarms! This is why imbalanced deep learning tasks require threshold tuning, focal loss, or precision–recall curves rather than raw accuracy.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;4-conditional-probability&quot;&gt;4. Conditional Probability&lt;/h3&gt;

&lt;p&gt;The probability of event A given that event B has occurred:&lt;/p&gt;

\[P(A|B) = \frac{P(A \cap B)}{P(B)}, \quad P(B) &amp;gt; 0\]

&lt;p&gt;&lt;strong&gt;Interpretation&lt;/strong&gt;: Conditional probability updates our belief about A when we have information about B.&lt;/p&gt;

&lt;div id=&quot;conditional-prob-demo&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f9f9f9;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Conditional Probability Visualization&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;conditionalCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;Venn Diagram:&lt;/strong&gt; Blue circle is event A, red circle is event B. Purple intersection shows A ∩ B.
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Adjust Probabilities&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;prob-a-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;P(A): &lt;span id=&quot;prob-a-value&quot;&gt;0.4&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;prob-a-slider&quot; min=&quot;0.1&quot; max=&quot;0.9&quot; step=&quot;0.05&quot; value=&quot;0.4&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;prob-b-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;P(B): &lt;span id=&quot;prob-b-value&quot;&gt;0.5&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;prob-b-slider&quot; min=&quot;0.1&quot; max=&quot;0.9&quot; step=&quot;0.05&quot; value=&quot;0.5&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label for=&quot;overlap-slider&quot; style=&quot;display: block; margin-bottom: 5px; font-weight: bold;&quot;&gt;Overlap: &lt;span id=&quot;overlap-value&quot;&gt;0.2&lt;/span&gt;&lt;/label&gt;
                    &lt;input type=&quot;range&quot; id=&quot;overlap-slider&quot; min=&quot;0&quot; max=&quot;0.4&quot; step=&quot;0.05&quot; value=&quot;0.2&quot; style=&quot;width: 100%;&quot; /&gt;
                &lt;/div&gt;
                
                &lt;div id=&quot;conditional-results&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Probabilities:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;P(A) = &lt;span id=&quot;display-prob-a&quot;&gt;0.400&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(B) = &lt;span id=&quot;display-prob-b&quot;&gt;0.500&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(A ∩ B) = &lt;span id=&quot;display-prob-ab&quot;&gt;0.200&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(A ∪ B) = &lt;span id=&quot;display-prob-union&quot;&gt;0.700&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;&lt;strong&gt;Conditional:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;P(A|B) = &lt;span id=&quot;display-prob-a-given-b&quot;&gt;0.400&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(B|A) = &lt;span id=&quot;display-prob-b-given-a&quot;&gt;0.500&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;5-independence&quot;&gt;5. Independence&lt;/h3&gt;

&lt;p&gt;Two events A and B are &lt;strong&gt;independent&lt;/strong&gt; if:
\(P(A \cap B) = P(A) \cdot P(B)\)&lt;/p&gt;

&lt;p&gt;Equivalently:
\(P(A|B) = P(A) \quad \text{and} \quad P(B|A) = P(B)\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Interpretation&lt;/strong&gt;: Knowledge about one event doesn’t change the probability of the other.&lt;/p&gt;

&lt;script&gt;
// Conditional Probability Visualization
class ConditionalProbDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;conditionalCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.probA = 0.4;
        this.probB = 0.5;
        this.overlap = 0.2;
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const probASlider = document.getElementById(&apos;prob-a-slider&apos;);
        const probBSlider = document.getElementById(&apos;prob-b-slider&apos;);
        const overlapSlider = document.getElementById(&apos;overlap-slider&apos;);
        
        probASlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.probA = parseFloat(e.target.value);
            document.getElementById(&apos;prob-a-value&apos;).textContent = this.probA.toFixed(1);
            this.updateCalculations();
            this.draw();
        });
        
        probBSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.probB = parseFloat(e.target.value);
            document.getElementById(&apos;prob-b-value&apos;).textContent = this.probB.toFixed(1);
            this.updateCalculations();
            this.draw();
        });
        
        overlapSlider.addEventListener(&apos;input&apos;, (e) =&gt; {
            this.overlap = parseFloat(e.target.value);
            document.getElementById(&apos;overlap-value&apos;).textContent = this.overlap.toFixed(1);
            // Ensure overlap doesn&apos;t exceed min(probA, probB)
            const maxOverlap = Math.min(this.probA, this.probB);
            if (this.overlap &gt; maxOverlap) {
                this.overlap = maxOverlap;
                overlapSlider.value = this.overlap;
                document.getElementById(&apos;overlap-value&apos;).textContent = this.overlap.toFixed(1);
            }
            this.updateCalculations();
            this.draw();
        });
        
        this.updateCalculations();
    }
    
    updateCalculations() {
        const probUnion = this.probA + this.probB - this.overlap;
        const probAGivenB = this.probB &gt; 0 ? this.overlap / this.probB : 0;
        const probBGivenA = this.probA &gt; 0 ? this.overlap / this.probA : 0;
        
        document.getElementById(&apos;display-prob-a&apos;).textContent = this.probA.toFixed(3);
        document.getElementById(&apos;display-prob-b&apos;).textContent = this.probB.toFixed(3);
        document.getElementById(&apos;display-prob-ab&apos;).textContent = this.overlap.toFixed(3);
        document.getElementById(&apos;display-prob-union&apos;).textContent = probUnion.toFixed(3);
        document.getElementById(&apos;display-prob-a-given-b&apos;).textContent = probAGivenB.toFixed(3);
        document.getElementById(&apos;display-prob-b-given-a&apos;).textContent = probBGivenA.toFixed(3);
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        // Draw universe rectangle
        this.ctx.strokeStyle = &apos;#000&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(50, 50, 300, 200);
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;14px Arial&apos;;
        this.ctx.fillText(&apos;Ω (Sample Space)&apos;, 55, 45);
        
        // Calculate circle parameters
        const centerAX = 150;
        const centerAY = 150;
        const centerBX = 250;
        const centerBY = 150;
        
        // Calculate radii based on probabilities (area proportional to probability)
        const radiusA = Math.sqrt(this.probA * 10000 / Math.PI);
        const radiusB = Math.sqrt(this.probB * 10000 / Math.PI);
        
        // Draw circle A
        this.ctx.globalAlpha = 0.3;
        this.ctx.fillStyle = &apos;#2196f3&apos;;
        this.ctx.beginPath();
        this.ctx.arc(centerAX, centerAY, radiusA, 0, 2 * Math.PI);
        this.ctx.fill();
        
        // Draw circle B
        this.ctx.fillStyle = &apos;#f44336&apos;;
        this.ctx.beginPath();
        this.ctx.arc(centerBX, centerBY, radiusB, 0, 2 * Math.PI);
        this.ctx.fill();
        
        // Draw intersection (approximate)
        if (this.overlap &gt; 0) {
            this.ctx.fillStyle = &apos;#9c27b0&apos;;
            const overlapRadius = Math.sqrt(this.overlap * 5000 / Math.PI);
            this.ctx.beginPath();
            this.ctx.arc((centerAX + centerBX) / 2, (centerAY + centerBY) / 2, overlapRadius, 0, 2 * Math.PI);
            this.ctx.fill();
        }
        
        this.ctx.globalAlpha = 1.0;
        
        // Draw circle outlines
        this.ctx.strokeStyle = &apos;#2196f3&apos;;
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        this.ctx.arc(centerAX, centerAY, radiusA, 0, 2 * Math.PI);
        this.ctx.stroke();
        
        this.ctx.strokeStyle = &apos;#f44336&apos;;
        this.ctx.beginPath();
        this.ctx.arc(centerBX, centerBY, radiusB, 0, 2 * Math.PI);
        this.ctx.stroke();
        
        // Labels
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;16px Arial&apos;;
        this.ctx.fillText(&apos;A&apos;, centerAX - 40, centerAY);
        this.ctx.fillText(&apos;B&apos;, centerBX + 30, centerBY);
        
        if (this.overlap &gt; 0) {
            this.ctx.fillText(&apos;A∩B&apos;, (centerAX + centerBX) / 2 - 15, (centerAY + centerBY) / 2 + 5);
        }
    }
}

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new ConditionalProbDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=_IgyaD7vOOA&quot;&gt;Conditional Probabilities, Clearly Explained!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. P(A&lt;/td&gt;
          &lt;td&gt;B) is the whole lesson’s first definition.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=2nDYX8IKrwo&quot;&gt;Independence in Probability&lt;/a&gt; — Steve Brunton, English. Independence is the second claim: the conditional probability collapses to the marginal.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=9wCnvr7Xw4E&quot;&gt;Bayes’ Theorem, Clearly Explained!!!!&lt;/a&gt; — StatQuest with Josh Starmer, English. Bayes’ theorem is the rearrangement of the definition the lesson uses to swap condition and claim.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-04-01-01 Sample Spaces and Probability Axioms</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_01_01_Sample_Spaces_and_Axioms/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_04_01_01_Sample_Spaces_and_Axioms</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;In 1933, Andrey Kolmogorov reduced all of probability theory to just three deceptively simple axioms. Every softmax output layer in deep learning is explicitly engineered so that its vector of class scores obeys those exact three axioms.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-kolmogorovs-axioms-and-softmax-validity&quot;&gt;Key ideas: Kolmogorov’s Axioms and Softmax Validity&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sample Space \(\Omega\) and Event Space \(\mathcal{F}\)&lt;/strong&gt;: Defines the exhaustive universe of mutually exclusive outcomes (e.g., the 10 digit classes \(\{0, \dots, 9\}\) in MNIST or the 50,000 tokens in a vocabulary).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Non-Negativity &amp;amp; Normalization (Axioms 1 &amp;amp; 2)&lt;/strong&gt;: Demands \(P(A) \geq 0\) and \(P(\Omega) = 1\); in neural classifiers, exponentiating logits guarantees positivity and dividing by their sum enforces normalization.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Countable Additivity (Axiom 3)&lt;/strong&gt;: States that for disjoint events, the probability of their union is the sum of their probabilities—letting us compute top-\(k\) accuracy or group-level class probabilities by simple summation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Derived Rules (Complement &amp;amp; Inclusion–Exclusion)&lt;/strong&gt;: Immediately gives \(P(A^c) = 1 - P(A)\) and \(P(A \cup B) = P(A) + P(B) - P(A \cap B)\), preventing double-counting in multi-label classification.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-verifying-kolmogorovs-axioms-on-a-softmax-output&quot;&gt;Worked example: Verifying Kolmogorov’s Axioms on a Softmax Output&lt;/h3&gt;

&lt;p&gt;Suppose a 3-class image classifier outputs raw logits \(\mathbf{z} = [0, \ln 2, \ln 5]\) for classes \(\{\text{cat}, \text{dog}, \text{bird}\}\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Exponentiate Logits (Enforcing Axiom 1: Non-Negativity)&lt;/strong&gt;:
\(e^0 = 1, \quad e^{\ln 2} = 2, \quad e^{\ln 5} = 5\)
All values are strictly positive.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Normalize by Total Partition Sum \(Z\) (Enforcing Axiom 2: Normalization)&lt;/strong&gt;:
\(Z = 1 + 2 + 5 = 8\)
\(P(\text{cat}) = \frac{1}{8} = 0.125, \quad P(\text{dog}) = \frac{2}{8} = 0.250, \quad P(\text{bird}) = \frac{5}{8} = 0.625\)
Sum check: \(0.125 + 0.250 + 0.625 = 1.000 = P(\Omega)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply Axiom 3 (Additivity) and Complement Rule&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Probability of a mammal (\(\{\text{cat}\} \cup \{\text{dog}\}\), disjoint):
\(P(\text{mammal}) = P(\text{cat}) + P(\text{dog}) = 0.125 + 0.250 = 0.375\)&lt;/li&gt;
      &lt;li&gt;Complement check:
\(P(\text{not mammal}) = 1 - 0.375 = 0.625 = P(\text{bird})\)
Every softmax layer is an axiomatic probability projector.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;basic-probability-theory&quot;&gt;Basic Probability Theory&lt;/h2&gt;

&lt;p&gt;Probability theory provides the mathematical framework for reasoning about uncertainty, which is fundamental to many deep-learning problems in machine learning and data science.&lt;/p&gt;

&lt;h3 id=&quot;1-sample-space-and-events&quot;&gt;1. Sample Space and Events&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Sample Space (Ω)&lt;/strong&gt;: The set of all possible outcomes of an experiment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Event (A)&lt;/strong&gt;: A subset of the sample space representing a collection of outcomes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Coin flip: Ω = {H, T}&lt;/li&gt;
  &lt;li&gt;Die roll: Ω = {1, 2, 3, 4, 5, 6}&lt;/li&gt;
  &lt;li&gt;Continuous: Ω = [0, 1] for uniform random variable&lt;/li&gt;
&lt;/ul&gt;

&lt;div id=&quot;sample-space-demo&quot; style=&quot;border: 2px solid #ddd; padding: 20px; margin: 20px 0; border-radius: 10px; background-color: #f9f9f9;&quot;&gt;
    &lt;h4 style=&quot;text-align: center; color: #333;&quot;&gt;Interactive Sample Space Visualization&lt;/h4&gt;
    
    &lt;div style=&quot;display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start;&quot;&gt;
        &lt;div style=&quot;flex: 1; min-width: 400px;&quot;&gt;
            &lt;canvas id=&quot;sampleSpaceCanvas&quot; width=&quot;400&quot; height=&quot;300&quot; style=&quot;border: 1px solid #ccc; background: white;&quot;&gt;&lt;/canvas&gt;
            &lt;p style=&quot;font-size: 12px; color: #666; margin-top: 5px;&quot;&gt;
                &lt;strong&gt;Visualization:&lt;/strong&gt; Click to generate random samples. Different colors represent different events.
            &lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div style=&quot;flex: 1; min-width: 250px;&quot;&gt;
            &lt;div style=&quot;background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);&quot;&gt;
                &lt;h5 style=&quot;margin-top: 0; color: #444;&quot;&gt;Experiment Type&lt;/h5&gt;
                
                &lt;div style=&quot;margin-bottom: 15px;&quot;&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;experiment&quot; value=&quot;coin&quot; checked=&quot;&quot; /&gt; Coin Flip
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;experiment&quot; value=&quot;dice&quot; /&gt; Dice Roll
                    &lt;/label&gt;
                    &lt;label style=&quot;display: block; margin-bottom: 10px;&quot;&gt;
                        &lt;input type=&quot;radio&quot; name=&quot;experiment&quot; value=&quot;uniform&quot; /&gt; Uniform [0,1]
                    &lt;/label&gt;
                &lt;/div&gt;
                
                &lt;button id=&quot;generate-sample&quot; style=&quot;width: 100%; padding: 10px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer; margin-bottom: 10px;&quot;&gt;Generate Sample&lt;/button&gt;
                &lt;button id=&quot;clear-samples&quot; style=&quot;width: 100%; padding: 8px; background: #6c757d; color: white; border: none; border-radius: 5px; cursor: pointer; margin-bottom: 15px;&quot;&gt;Clear&lt;/button&gt;
                
                &lt;div id=&quot;sample-stats&quot; style=&quot;font-family: monospace; font-size: 12px; line-height: 1.4; background: #f8f9fa; padding: 10px; border-radius: 4px;&quot;&gt;
                    &lt;div&gt;&lt;strong&gt;Statistics:&lt;/strong&gt;&lt;/div&gt;
                    &lt;div&gt;Total samples: &lt;span id=&quot;total-samples&quot;&gt;0&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Event A: &lt;span id=&quot;event-a-count&quot;&gt;0&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;Event B: &lt;span id=&quot;event-b-count&quot;&gt;0&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(A) ≈ &lt;span id=&quot;prob-a&quot;&gt;0.000&lt;/span&gt;&lt;/div&gt;
                    &lt;div&gt;P(B) ≈ &lt;span id=&quot;prob-b&quot;&gt;0.000&lt;/span&gt;&lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;h3 id=&quot;2-probability-axioms-kolmogorov-axioms&quot;&gt;2. Probability Axioms (Kolmogorov Axioms)&lt;/h3&gt;

&lt;p&gt;For any probability measure P, the following axioms must hold:&lt;/p&gt;

&lt;h4 id=&quot;axiom-1-non-negativity&quot;&gt;Axiom 1: Non-negativity&lt;/h4&gt;
&lt;p&gt;\(P(A) \geq 0 \text{ for all events } A\)&lt;/p&gt;

&lt;h4 id=&quot;axiom-2-normalization&quot;&gt;Axiom 2: Normalization&lt;/h4&gt;
&lt;p&gt;\(P(\Omega) = 1\)&lt;/p&gt;

&lt;h4 id=&quot;axiom-3-countable-additivity&quot;&gt;Axiom 3: Countable Additivity&lt;/h4&gt;
&lt;p&gt;For mutually exclusive events \(A_1, A_2, \ldots\):
\(P\left(\bigcup_{i=1}^{\infty} A_i\right) = \sum_{i=1}^{\infty} P(A_i)\)&lt;/p&gt;

&lt;h3 id=&quot;3-basic-properties-and-rules&quot;&gt;3. Basic Properties and Rules&lt;/h3&gt;

&lt;h4 id=&quot;complement-rule&quot;&gt;Complement Rule&lt;/h4&gt;
&lt;p&gt;\(P(A^c) = 1 - P(A)\)&lt;/p&gt;

&lt;h4 id=&quot;addition-rule&quot;&gt;Addition Rule&lt;/h4&gt;
&lt;p&gt;For any two events A and B:
\(P(A \cup B) = P(A) + P(B) - P(A \cap B)\)&lt;/p&gt;

&lt;h4 id=&quot;multiplication-rule&quot;&gt;Multiplication Rule&lt;/h4&gt;
&lt;p&gt;\(P(A \cap B) = P(A|B) \cdot P(B) = P(B|A) \cdot P(A)\)&lt;/p&gt;

&lt;script&gt;
class SampleSpaceDemo {
    constructor() {
        this.canvas = document.getElementById(&apos;sampleSpaceCanvas&apos;);
        this.ctx = this.canvas.getContext(&apos;2d&apos;);
        this.width = this.canvas.width;
        this.height = this.canvas.height;
        
        this.samples = [];
        this.experimentType = &apos;coin&apos;;
        
        this.setupControls();
        this.draw();
    }
    
    setupControls() {
        const radios = document.querySelectorAll(&apos;input[name=&quot;experiment&quot;]&apos;);
        const generateBtn = document.getElementById(&apos;generate-sample&apos;);
        const clearBtn = document.getElementById(&apos;clear-samples&apos;);
        
        radios.forEach(radio =&gt; {
            radio.addEventListener(&apos;change&apos;, (e) =&gt; {
                this.experimentType = e.target.value;
                this.samples = [];
                this.updateStats();
                this.draw();
            });
        });
        
        generateBtn.addEventListener(&apos;click&apos;, () =&gt; this.generateSample());
        clearBtn.addEventListener(&apos;click&apos;, () =&gt; {
            this.samples = [];
            this.updateStats();
            this.draw();
        });
        
        this.canvas.addEventListener(&apos;click&apos;, () =&gt; this.generateSample());
    }
    
    generateSample() {
        let sample;
        
        switch(this.experimentType) {
            case &apos;coin&apos;:
                sample = {
                    value: Math.random() &lt; 0.5 ? &apos;H&apos; : &apos;T&apos;,
                    x: Math.random() * (this.width - 40) + 20,
                    y: Math.random() * (this.height - 40) + 20,
                    eventA: Math.random() &lt; 0.5, // Event A: Heads
                    eventB: Math.random() &lt; 0.3  // Event B: Lucky flip
                };
                break;
            case &apos;dice&apos;:
                const diceValue = Math.floor(Math.random() * 6) + 1;
                sample = {
                    value: diceValue,
                    x: Math.random() * (this.width - 40) + 20,
                    y: Math.random() * (this.height - 40) + 20,
                    eventA: diceValue &gt;= 4, // Event A: 4, 5, or 6
                    eventB: diceValue % 2 === 0 // Event B: Even
                };
                break;
            case &apos;uniform&apos;:
                const uniformValue = Math.random();
                sample = {
                    value: uniformValue.toFixed(3),
                    x: uniformValue * (this.width - 40) + 20,
                    y: Math.random() * (this.height - 40) + 20,
                    eventA: uniformValue &gt; 0.5, // Event A: &gt; 0.5
                    eventB: uniformValue &lt; 0.7  // Event B: &lt; 0.7
                };
                break;
        }
        
        this.samples.push(sample);
        this.updateStats();
        this.draw();
    }
    
    updateStats() {
        const total = this.samples.length;
        const eventACount = this.samples.filter(s =&gt; s.eventA).length;
        const eventBCount = this.samples.filter(s =&gt; s.eventB).length;
        
        document.getElementById(&apos;total-samples&apos;).textContent = total;
        document.getElementById(&apos;event-a-count&apos;).textContent = eventACount;
        document.getElementById(&apos;event-b-count&apos;).textContent = eventBCount;
        document.getElementById(&apos;prob-a&apos;).textContent = total &gt; 0 ? (eventACount / total).toFixed(3) : &apos;0.000&apos;;
        document.getElementById(&apos;prob-b&apos;).textContent = total &gt; 0 ? (eventBCount / total).toFixed(3) : &apos;0.000&apos;;
    }
    
    draw() {
        this.ctx.clearRect(0, 0, this.width, this.height);
        
        // Draw background
        this.ctx.fillStyle = &apos;#f8f9fa&apos;;
        this.ctx.fillRect(0, 0, this.width, this.height);
        
        // Draw samples
        this.samples.forEach(sample =&gt; {
            // Determine color based on events
            let color = &apos;#666&apos;;
            if (sample.eventA &amp;&amp; sample.eventB) color = &apos;#9c27b0&apos;; // Both events
            else if (sample.eventA) color = &apos;#2196f3&apos;; // Event A only
            else if (sample.eventB) color = &apos;#f44336&apos;; // Event B only
            
            this.ctx.fillStyle = color;
            this.ctx.beginPath();
            this.ctx.arc(sample.x, sample.y, 5, 0, 2 * Math.PI);
            this.ctx.fill();
            
            // Draw value
            this.ctx.fillStyle = &apos;#000&apos;;
            this.ctx.font = &apos;10px Arial&apos;;
            this.ctx.textAlign = &apos;center&apos;;
            this.ctx.fillText(sample.value, sample.x, sample.y - 8);
        });
        
        // Draw legend
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.font = &apos;12px Arial&apos;;
        this.ctx.textAlign = &apos;left&apos;;
        this.ctx.fillText(&apos;Legend:&apos;, 10, 20);
        
        this.ctx.fillStyle = &apos;#2196f3&apos;;
        this.ctx.beginPath();
        this.ctx.arc(20, 35, 4, 0, 2 * Math.PI);
        this.ctx.fill();
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.fillText(&apos;Event A only&apos;, 30, 38);
        
        this.ctx.fillStyle = &apos;#f44336&apos;;
        this.ctx.beginPath();
        this.ctx.arc(20, 50, 4, 0, 2 * Math.PI);
        this.ctx.fill();
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.fillText(&apos;Event B only&apos;, 30, 53);
        
        this.ctx.fillStyle = &apos;#9c27b0&apos;;
        this.ctx.beginPath();
        this.ctx.arc(20, 65, 4, 0, 2 * Math.PI);
        this.ctx.fill();
        this.ctx.fillStyle = &apos;#000&apos;;
        this.ctx.fillText(&apos;Both A and B&apos;, 30, 68);
    }
}

document.addEventListener(&apos;DOMContentLoaded&apos;, function() {
    new SampleSpaceDemo();
});
&lt;/script&gt;

&lt;style&gt;
input[type=&quot;range&quot;] {
    -webkit-appearance: none;
    appearance: none;
    height: 5px;
    background: #ddd;
    outline: none;
    border-radius: 5px;
}

input[type=&quot;range&quot;]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
}

input[type=&quot;range&quot;]::-moz-range-thumb {
    width: 15px;
    height: 15px;
    background: #007bff;
    cursor: pointer;
    border-radius: 50%;
    border: none;
}

canvas {
    border-radius: 5px;
}

.demo-container {
    margin: 20px 0;
}
&lt;/style&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=pA83XtLeVig&quot;&gt;L01.4 Probability Axioms&lt;/a&gt; — MIT OpenCourseWare, English. Sample space, events, and the three axioms are exactly this lesson.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=oI3hZJqXJuc&quot;&gt;The Main Ideas behind Probability Distributions&lt;/a&gt; — StatQuest with Josh Starmer, English. Shows how a probability measure on that sample space becomes a distribution.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=HZGCoVF3YvM&quot;&gt;Bayes theorem, the geometry of changing beliefs&lt;/a&gt; — 3Blue1Brown, English. Bayes’ rule is an identity inside the same axioms, useful once events are no longer independent.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-03 Real Analysis And Set Theory</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_03_Real_Analysis_and_Set_Theory/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_03_Real_Analysis_and_Set_Theory</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Why can we even be sure that a loss function achieves a minimum on a bounded weight ball, or that a sequence of iterates produced by an optimizer converges to a limit inside our feasible set? Real analysis and set theory supply the precision behind every “exists,” “converges,” and “generalizes” statement in machine learning theory.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-foundations-of-sets-spaces-and-convergence&quot;&gt;Key ideas: Foundations of Sets, Spaces, and Convergence&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Set Theory &amp;amp; Mappings (Formalizing Data and Models)&lt;/strong&gt;: Treats datasets as finite sets or multisets, classifiers as functions \(f: \mathcal{X} \to \mathcal{Y}\), and hypothesis classes \(\mathcal{H}\) as families of functions over which learning searches.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Metric Spaces &amp;amp; Neighborhoods (Quantifying Closeness)&lt;/strong&gt;: Generalizes Euclidean distance to arbitrary metrics (\(L_1, L_2, L_\infty\), Wasserstein), defining \(\varepsilon\)-balls used in adversarial robustness and nearest-neighbor retrieval.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Open, Closed, and Compact Sets (Existence of Optima)&lt;/strong&gt;: Establishes the Extreme Value Theorem—every continuous loss on a compact (closed and bounded in \(\mathbb{R}^d\)) parameter set attains its global minimum.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sequences &amp;amp; Completeness (Convergence Guarantees)&lt;/strong&gt;: Explains why Cauchy sequences converge in \(\mathbb{R}^d\), allowing optimization proofs to guarantee that vanishing step sizes settle at a concrete limit point.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-why-closedness-matters-for-finding-a-minimum&quot;&gt;Worked example: Why Closedness Matters for Finding a Minimum&lt;/h3&gt;

&lt;p&gt;Compare minimizing the continuous loss \(L(w) = w^2 + 1\) over two feasible sets: the open interval \(U = (1, 3)\) versus the closed, compact interval \(K = [1, 3]\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate the Infimum (Greatest Lower Bound)&lt;/strong&gt;:
On both \(U\) and \(K\), \(L(w) = w^2 + 1\) is strictly increasing for \(w &amp;gt; 0\). As \(w \to 1^+\), \(L(w) \to 1^2 + 1 = 2\). Thus:
\(\inf_{w \in U} L(w) = \inf_{w \in K} L(w) = 2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Test Attainment on the Open Set \(U = (1, 3)\)&lt;/strong&gt;:
Take the sequence \(w_n = 1 + \frac{1}{n} \in U\):
    &lt;ul&gt;
      &lt;li&gt;
\[w_1 = 2.0 \implies L(2.0) = 5.0\]
      &lt;/li&gt;
      &lt;li&gt;
\[w_{10} = 1.1 \implies L(1.1) = 2.21\]
      &lt;/li&gt;
      &lt;li&gt;\(w_{100} = 1.01 \implies L(1.01) = 2.0201\)
The sequence converges to \(w^* = 1\), yet \(1 \notin (1, 3)\). No point inside \(U\) achieves \(L(w) = 2\)—the minimum does not exist in \(U\)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Test Attainment on the Compact Set \(K = [1, 3]\)&lt;/strong&gt;:
Because \(K\) is closed (it contains its boundary point \(1\)) and bounded, the Extreme Value Theorem guarantees a minimizer exists in \(K\), and indeed \(w^* = 1 \in K\) attains \(L(1) = 2\). This is why constrained optimization (like projected gradient descent onto an \(L_2\) ball \(\|\mathbf{w}\|_2 \leq R\)) always uses &lt;strong&gt;closed&lt;/strong&gt; balls.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers essential concepts from real analysis and set theory needed for deep-learning, organized into two main sections for comprehensive understanding.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Intro to Sets&lt;/td&gt;
          &lt;td&gt;Examples, Notation &amp;amp; Properties](https://www.youtube.com/watch?v=B1v2-nGXNzs) — Dr. Trefor Bazett, English. Sets, membership, and functions are the language of the set-theory lesson.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Intro to Open Sets (with Examples)&lt;/td&gt;
          &lt;td&gt;Real Analysis](https://www.youtube.com/watch?v=pnWgj8jjs3w) — Wrath of Math, English. Open sets are the first topology object the second lesson needs.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Limits, L’Hôpital’s rule, and epsilon delta definitions&lt;/td&gt;
          &lt;td&gt;Chapter 7, Essence of calculus](https://www.youtube.com/watch?v=kfF40MiS7zA) — 3Blue1Brown, English. Epsilon-delta continuity is the analysis half this overview points at.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-03-02 Topology in Real Analysis</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_03_02_Topology_in_Real_Analysis/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_03_02_Topology_in_Real_Analysis</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;When researchers talk about “adversarial \(\varepsilon\)-balls,” “manifold hypotheses,” or “flat versus sharp minima,” they are speaking the language of point-set topology. Topology strips away coordinates to ask the questions optimization truly cares about: What is a neighborhood? Where is the boundary? And can a sequence escape?&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-metric-topology-for-optimization--generalization&quot;&gt;Key ideas: Metric Topology for Optimization &amp;amp; Generalization&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Metric Spaces &amp;amp; Open Balls (Neighborhood Geometry)&lt;/strong&gt;: Defines the \(\varepsilon\)-ball \(B_\varepsilon(\mathbf{x}) = \{\mathbf{y} : d(\mathbf{x}, \mathbf{y}) &amp;lt; \varepsilon\}\), which directly formalizes adversarial threat models (\(L_2\) and \(L_\infty\) perturbation balls) and local minima.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Open vs. Closed Sets &amp;amp; Boundary Points&lt;/strong&gt;: Distinguishes interior points (where small gradient steps stay feasible) from boundary points (where constraints like weight clipping or probability simplices activate).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compactness (Heine–Borel Theorem)&lt;/strong&gt;: In \(\mathbb{R}^d\), a set is compact if and only if it is closed and bounded—guaranteeing that every continuous loss achieves a global minimum and every bounded sequence has a convergent subsequence.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Connectedness &amp;amp; Path-Connectedness (Mode Connectivity)&lt;/strong&gt;: Explains whether two distinct neural network minima can be joined by a continuous low-loss curve, a cornerstone of modern loss-landscape research.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-comparing-l_2-vs-l_infty-open-balls-in-adversarial-perturbations&quot;&gt;Worked example: Comparing \(L_2\) vs. \(L_\infty\) Open Balls in Adversarial Perturbations&lt;/h3&gt;

&lt;p&gt;Suppose an input image patch has two pixel intensities \(\mathbf{x} = (0.50, 0.50)\) and an attacker can perturb it to \(\mathbf{y} = (0.58, 0.56)\) with perturbation \(\boldsymbol{\delta} = \mathbf{y} - \mathbf{x} = (0.08, 0.06)\). Test whether \(\mathbf{y}\) lies inside the open ball \(B_{0.1}(\mathbf{x})\) under the \(L_2\) and \(L_\infty\) metrics.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the \(L_2\) (Euclidean) Distance&lt;/strong&gt;:
\(d_2(\mathbf{x}, \mathbf{y}) = \sqrt{(0.08)^2 + (0.06)^2} = \sqrt{0.0064 + 0.0036} = \sqrt{0.0100} = 0.10\)
Because an &lt;strong&gt;open&lt;/strong&gt; ball requires strict inequality \(d_2(\mathbf{x}, \mathbf{y}) &amp;lt; 0.10\), \(\mathbf{y}\) is &lt;strong&gt;not&lt;/strong&gt; in the open \(L_2\) ball—it lies right on the boundary sphere \(\partial B_{0.1}^{(2)}(\mathbf{x})\)!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the \(L_\infty\) (Chebyshev / Max-Pixel) Distance&lt;/strong&gt;:
\(d_\infty(\mathbf{x}, \mathbf{y}) = \max(\lvert 0.08\rvert, \lvert 0.06\rvert) = 0.08 &amp;lt; 0.10\)
So \(\mathbf{y}\) &lt;strong&gt;is&lt;/strong&gt; strictly in the interior of the open \(L_\infty\) ball \(B_{0.1}^{(\infty)}(\mathbf{x})\), with safety margin \(0.10 - 0.08 = 0.02\) before hitting the boundary.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Geometric Takeaway&lt;/strong&gt;:
The \(L_\infty\) ball is a square of side \(0.20\) that encloses the \(L_2\) circle of radius \(0.10\); in \(d\) dimensions, a corner of the \(L_\infty\) ball has \(L_2\) distance \(\varepsilon\sqrt{d}\), explaining why tiny per-pixel \(L_\infty\) attacks accumulate huge \(L_2\) energy on high-resolution images.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers essential topological concepts from real analysis that are crucial for understanding the structure of feasible regions, continuity, and the existence of optimal solutions in deep-learning problems.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;introduction-to-topology&quot;&gt;Introduction to Topology&lt;/h2&gt;

&lt;p&gt;Topology studies the properties of space that are preserved under continuous deformations. In deep-learning, topological concepts help us understand the structure of feasible regions and the behavior of functions, particularly regarding the existence and characterization of optimal solutions.&lt;/p&gt;

&lt;h3 id=&quot;metric-spaces-and-distance&quot;&gt;Metric Spaces and Distance&lt;/h3&gt;

&lt;p&gt;Before discussing topology, we need the concept of distance. In \(\mathbb{R}^n\), the standard &lt;strong&gt;Euclidean distance&lt;/strong&gt; between points \(\mathbf{x}\) and \(\mathbf{y}\) is:&lt;/p&gt;

\[d(\mathbf{x}, \mathbf{y}) = \|\mathbf{x} - \mathbf{y}\|_2 = \sqrt{\sum_{i=1}^n (x_i - y_i)^2}\]

&lt;h3 id=&quot;open-balls-and-neighborhoods&quot;&gt;Open Balls and Neighborhoods&lt;/h3&gt;

&lt;p&gt;An &lt;strong&gt;open ball&lt;/strong&gt; centered at \(\mathbf{x}_0\) with radius \(\epsilon &amp;gt; 0\) is:&lt;/p&gt;

\[B(\mathbf{x}_0, \epsilon) = \{\mathbf{y} \in \mathbb{R}^n : d(\mathbf{x}_0, \mathbf{y}) &amp;lt; \epsilon\}\]

&lt;p&gt;This represents all points within distance \(\epsilon\) from \(\mathbf{x}_0\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;In \(\mathbb{R}\): \(B(0, 1) = (-1, 1)\) (open interval)&lt;/li&gt;
  &lt;li&gt;In \(\mathbb{R}^2\): \(B(\mathbf{0}, 1) = \{(x, y) : x^2 + y^2 &amp;lt; 1\}\) (open unit disk)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;open-sets&quot;&gt;Open Sets&lt;/h2&gt;

&lt;p&gt;An &lt;strong&gt;open set&lt;/strong&gt; is characterized by the property that it &lt;strong&gt;contains none of its boundary points&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;formal-definition&quot;&gt;Formal Definition&lt;/h3&gt;

&lt;p&gt;A set \(S\) in \(\mathbb{R}^n\) is &lt;strong&gt;open&lt;/strong&gt; if for every point \(\mathbf{x} \in S\), there exists a positive real number \(\epsilon &amp;gt; 0\) such that the open ball \(B(\mathbf{x}, \epsilon)\) is entirely contained within \(S\):&lt;/p&gt;

\[\forall \mathbf{x} \in S, \exists \epsilon &amp;gt; 0 : B(\mathbf{x}, \epsilon) \subseteq S\]

&lt;h3 id=&quot;intuitive-understanding&quot;&gt;Intuitive Understanding&lt;/h3&gt;

&lt;p&gt;An open set has the property that if you’re inside it, you can move a small distance in any direction and still remain inside the set. There’s always some “wiggle room” around every point.&lt;/p&gt;

&lt;h3 id=&quot;examples-of-open-sets&quot;&gt;Examples of Open Sets&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;In \(\mathbb{R}\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[(0, 1) = \{x : 0 &amp;lt; x &amp;lt; 1\}\]
  &lt;/li&gt;
  &lt;li&gt;
\[(-\infty, 5) = \{x : x &amp;lt; 5\}\]
  &lt;/li&gt;
  &lt;li&gt;\(\mathbb{R}\) itself&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;In \(\mathbb{R}^2\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\{(x, y) : x^2 + y^2 &amp;lt; 1\}\) (open unit disk)&lt;/li&gt;
  &lt;li&gt;\(\{(x, y) : x &amp;gt; 0, y &amp;gt; 0\}\) (first quadrant, excluding axes)&lt;/li&gt;
  &lt;li&gt;\(\mathbb{R}^2\) itself&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;In \(\mathbb{R}^n\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Any open ball \(B(\mathbf{x}_0, r)\)&lt;/li&gt;
  &lt;li&gt;\(\mathbb{R}^n\) itself&lt;/li&gt;
  &lt;li&gt;\(\emptyset\) (empty set - vacuously open)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;properties-of-open-sets&quot;&gt;Properties of Open Sets&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;The union of any collection of open sets is open&lt;/li&gt;
  &lt;li&gt;The intersection of finitely many open sets is open&lt;/li&gt;
  &lt;li&gt;\(\mathbb{R}^n\) and \(\emptyset\) are both open&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;closed-sets&quot;&gt;Closed Sets&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;closed set&lt;/strong&gt; is defined as a set that contains all of its boundary points. Equivalently, a set \(S\) is closed if its complement \(\mathbb{R}^n \setminus S\) is an &lt;strong&gt;open set&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;formal-definition-1&quot;&gt;Formal Definition&lt;/h3&gt;

&lt;p&gt;A set \(S\) is &lt;strong&gt;closed&lt;/strong&gt; if it contains all its limit points. That is, if a sequence of points \((x_n)\) from \(S\) converges to a point \(\mathbf{x}\), then \(\mathbf{x}\) must also be in \(S\):&lt;/p&gt;

\[\text{If } \mathbf{x}_n \in S \text{ for all } n \text{ and } \lim_{n \to \infty} \mathbf{x}_n = \mathbf{x}, \text{ then } \mathbf{x} \in S\]

&lt;h3 id=&quot;examples-of-closed-sets&quot;&gt;Examples of Closed Sets&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;In \(\mathbb{R}\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[[0, 1] = \{x : 0 \leq x \leq 1\}\]
  &lt;/li&gt;
  &lt;li&gt;
\[[a, \infty) = \{x : x \geq a\}\]
  &lt;/li&gt;
  &lt;li&gt;\(\{0\}\) (single point)&lt;/li&gt;
  &lt;li&gt;\(\mathbb{Z}\) (integers)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;In \(\mathbb{R}^2\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\{(x, y) : x^2 + y^2 \leq 1\}\) (closed unit disk)&lt;/li&gt;
  &lt;li&gt;\(\{(x, y) : x \geq 0, y \geq 0\}\) (first quadrant, including axes)&lt;/li&gt;
  &lt;li&gt;\(\{(0, 0)\}\) (single point)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;In \(\mathbb{R}^n\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Any closed ball \(\overline{B}(\mathbf{x}_0, r) = \{\mathbf{x} : d(\mathbf{x}, \mathbf{x}_0) \leq r\}\)&lt;/li&gt;
  &lt;li&gt;\(\mathbb{R}^n\) itself&lt;/li&gt;
  &lt;li&gt;\(\emptyset\) (empty set)&lt;/li&gt;
  &lt;li&gt;Any finite set&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;properties-of-closed-sets&quot;&gt;Properties of Closed Sets&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;The intersection of any collection of closed sets is closed&lt;/li&gt;
  &lt;li&gt;The union of finitely many closed sets is closed&lt;/li&gt;
  &lt;li&gt;\(\mathbb{R}^n\) and \(\emptyset\) are both closed&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;important-note&quot;&gt;Important Note&lt;/h3&gt;

&lt;p&gt;Sets can be:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Open but not closed:&lt;/strong&gt; \((0, 1)\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Closed but not open:&lt;/strong&gt; \([0, 1]\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Both open and closed:&lt;/strong&gt; \(\mathbb{R}^n\), \(\emptyset\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Neither open nor closed:&lt;/strong&gt; \([0, 1)\), \((0, 1]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;boundary-interior-and-closure&quot;&gt;Boundary, Interior, and Closure&lt;/h2&gt;

&lt;h3 id=&quot;boundary&quot;&gt;Boundary&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;boundary&lt;/strong&gt; of a set \(S\), denoted \(\partial S\), consists of points that are “on the edge” of the set. A point \(\mathbf{x}\) is a &lt;strong&gt;boundary point&lt;/strong&gt; of \(S\) if every open ball centered at \(\mathbf{x}\) intersects both \(S\) and its complement \(S^c\):&lt;/p&gt;

\[\partial S = \{\mathbf{x} : \forall \epsilon &amp;gt; 0, B(\mathbf{x}, \epsilon) \cap S \neq \emptyset \text{ and } B(\mathbf{x}, \epsilon) \cap S^c \neq \emptyset\}\]

&lt;h3 id=&quot;interior&quot;&gt;Interior&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;interior&lt;/strong&gt; of a set \(S\), denoted \(S^\circ\) or \(\text{int}(S)\), includes all points strictly “inside” the set, excluding the boundary:&lt;/p&gt;

\[S^\circ = \{\mathbf{x} \in S : \exists \epsilon &amp;gt; 0, B(\mathbf{x}, \epsilon) \subseteq S\}\]

&lt;h3 id=&quot;closure&quot;&gt;Closure&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;closure&lt;/strong&gt; of a set \(S\), denoted \(\overline{S}\) or \(\text{cl}(S)\), is the smallest closed set containing \(S\):&lt;/p&gt;

\[\overline{S} = S \cup \partial S\]

&lt;h3 id=&quot;example-analysis&quot;&gt;Example Analysis&lt;/h3&gt;

&lt;p&gt;For the interval \(S = [0, 1)\) in \(\mathbb{R}\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Interior:&lt;/strong&gt; \(S^\circ = (0, 1)\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Boundary:&lt;/strong&gt; \(\partial S = \{0, 1\}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Closure:&lt;/strong&gt; \(\overline{S} = [0, 1]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For the open disk \(S = \{(x, y) : x^2 + y^2 &amp;lt; 1\}\) in \(\mathbb{R}^2\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Interior:&lt;/strong&gt; \(S^\circ = S\) (the set is already open)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Boundary:&lt;/strong&gt; \(\partial S = \{(x, y) : x^2 + y^2 = 1\}\) (unit circle)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Closure:&lt;/strong&gt; \(\overline{S} = \{(x, y) : x^2 + y^2 \leq 1\}\) (closed unit disk)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;compact-sets&quot;&gt;Compact Sets&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;compact set&lt;/strong&gt; is one of the most important concepts in deep-learning theory.&lt;/p&gt;

&lt;h3 id=&quot;definition-in-euclidean-spaces&quot;&gt;Definition in Euclidean Spaces&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Heine-Borel Theorem:&lt;/strong&gt; In Euclidean spaces (\(\mathbb{R}^n\)), a set is compact if and only if it is both &lt;strong&gt;closed and bounded&lt;/strong&gt;.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Bounded:&lt;/strong&gt; A set \(S\) is bounded if it can be contained within some sufficiently large open ball: \(\exists M &amp;gt; 0, \mathbf{x}_0\) such that \(S \subseteq B(\mathbf{x}_0, M)\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Closed:&lt;/strong&gt; As defined above&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;examples-of-compact-sets&quot;&gt;Examples of Compact Sets&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;In \(\mathbb{R}\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\([a, b]\) (any closed, bounded interval)&lt;/li&gt;
  &lt;li&gt;\(\{0\}\) (single point)&lt;/li&gt;
  &lt;li&gt;Any finite set&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;In \(\mathbb{R}^2\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\{(x, y) : x^2 + y^2 \leq 1\}\) (closed unit disk)&lt;/li&gt;
  &lt;li&gt;\([0, 1] \times [0, 1]\) (unit square)&lt;/li&gt;
  &lt;li&gt;Any finite set of points&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;In \(\mathbb{R}^n\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Any closed ball \(\overline{B}(\mathbf{x}_0, r)\)&lt;/li&gt;
  &lt;li&gt;Any closed, bounded rectangle \([a_1, b_1] \times [a_2, b_2] \times \cdots \times [a_n, b_n]\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;non-compact-sets&quot;&gt;Non-Compact Sets&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;\((0, 1)\) (bounded but not closed)&lt;/li&gt;
  &lt;li&gt;\([0, \infty)\) (closed but not bounded)&lt;/li&gt;
  &lt;li&gt;\(\mathbb{R}^n\) (not bounded)&lt;/li&gt;
  &lt;li&gt;\(\{1, 1/2, 1/3, 1/4, \ldots\}\) (bounded but not closed, since 0 is a limit point not in the set)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;continuity-of-functions&quot;&gt;Continuity of Functions&lt;/h2&gt;

&lt;h3 id=&quot;point-wise-continuity&quot;&gt;Point-wise Continuity&lt;/h3&gt;

&lt;p&gt;A function \(f: A \to \mathbb{R}\) is &lt;strong&gt;continuous at a point&lt;/strong&gt; \(\mathbf{c} \in A\) if for every \(\varepsilon &amp;gt; 0\), there exists \(\delta &amp;gt; 0\) such that for all \(\mathbf{x} \in A\):&lt;/p&gt;

\[\|\mathbf{x} - \mathbf{c}\| &amp;lt; \delta \implies |f(\mathbf{x}) - f(\mathbf{c})| &amp;lt; \varepsilon\]

&lt;p&gt;&lt;strong&gt;Intuitive meaning:&lt;/strong&gt; Small changes in input lead to small changes in output.&lt;/p&gt;

&lt;h3 id=&quot;global-continuity&quot;&gt;Global Continuity&lt;/h3&gt;

&lt;p&gt;\(f\) is &lt;strong&gt;continuous on \(A\)&lt;/strong&gt; if it’s continuous at every point in \(A\).&lt;/p&gt;

&lt;h3 id=&quot;sequential-characterization&quot;&gt;Sequential Characterization&lt;/h3&gt;

&lt;p&gt;\(f\) is continuous at \(\mathbf{c}\) if and only if for every sequence \((\mathbf{x}_n)\) in \(A\) converging to \(\mathbf{c}\):&lt;/p&gt;

\[\lim_{n \to \infty} f(\mathbf{x}_n) = f(\mathbf{c})\]

&lt;hr /&gt;

&lt;h2 id=&quot;important-theorems-for-deep-learning&quot;&gt;Important Theorems for Deep Learning&lt;/h2&gt;

&lt;h3 id=&quot;extreme-value-theorem&quot;&gt;Extreme Value Theorem&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;If \(f\) is continuous on a compact set \(K\), then \(f\) attains its maximum and minimum on \(K\).&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is fundamental for deep-learning: it guarantees that continuous objective functions have optimal solutions on compact feasible regions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Proof idea:&lt;/strong&gt; Compactness ensures that the supremum and infimum of \(f\) on \(K\) are actually achieved at points in \(K\).&lt;/p&gt;

&lt;h3 id=&quot;intermediate-value-theorem&quot;&gt;Intermediate Value Theorem&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;If \(f\) is continuous on \([a, b]\) and \(y\) is between \(f(a)\) and \(f(b)\), then there exists \(c \in [a, b]\) such that \(f(c) = y\).&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This helps establish the existence of solutions to equations \(f(x) = 0\).&lt;/p&gt;

&lt;h3 id=&quot;bolzano-weierstrass-theorem&quot;&gt;Bolzano-Weierstrass Theorem&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Every bounded sequence in \(\mathbb{R}^n\) has a convergent subsequence.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This is crucial for proving convergence of deep-learning algorithms.&lt;/p&gt;

&lt;h3 id=&quot;weierstrass-approximation-theorem&quot;&gt;Weierstrass Approximation Theorem&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Every continuous function on a closed interval can be uniformly approximated by polynomials.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;This justifies using polynomial approximations in deep-learning algorithms.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;applications-in-deep-learning&quot;&gt;Applications in Deep Learning&lt;/h2&gt;

&lt;h3 id=&quot;1-existence-of-solutions&quot;&gt;1. Existence of Solutions&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Compact feasible sets guarantee optimal solutions exist:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;If the feasible region \(S\) is compact and the objective function \(f\) is continuous, then the deep-learning problem \(\min_{\mathbf{x} \in S} f(\mathbf{x})\) has a solution.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-constraint-qualification&quot;&gt;2. Constraint Qualification&lt;/h3&gt;

&lt;p&gt;Understanding topological properties of constraint sets:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Regular points:&lt;/strong&gt; Points where constraint gradients are linearly independent&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Interior point methods:&lt;/strong&gt; Require the feasible region to have non-empty interior&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-convergence-analysis&quot;&gt;3. Convergence Analysis&lt;/h3&gt;

&lt;p&gt;Analyzing whether deep-learning algorithms converge:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Closed sets:&lt;/strong&gt; Ensure limit points of convergent sequences remain feasible&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compactness:&lt;/strong&gt; Guarantees convergent subsequences exist&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-local-vs-global-optima&quot;&gt;4. Local vs Global Optima&lt;/h3&gt;

&lt;p&gt;Using neighborhoods to define optimality:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Local minimum:&lt;/strong&gt; \(f(\mathbf{x}^*) \leq f(\mathbf{x})\) for all \(\mathbf{x}\) in some neighborhood of \(\mathbf{x}^*\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Global minimum:&lt;/strong&gt; \(f(\mathbf{x}^*) \leq f(\mathbf{x})\) for all \(\mathbf{x}\) in the feasible region&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;5-feasible-region-analysis&quot;&gt;5. Feasible Region Analysis&lt;/h3&gt;

&lt;p&gt;Determining properties of constraint sets:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Linear constraints:&lt;/strong&gt; Define closed sets (half-spaces)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Nonlinear constraints:&lt;/strong&gt; May create sets that are neither open nor closed&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compact feasible regions:&lt;/strong&gt; Guarantee existence of optimal solutions&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;example-portfolio-deep-learning&quot;&gt;Example: Portfolio Deep Learning&lt;/h3&gt;

&lt;p&gt;Consider minimizing portfolio risk subject to constraints:&lt;/p&gt;

\[\begin{align}
\min_{\mathbf{w}} \quad &amp;amp; \mathbf{w}^T \mathbf{\Sigma} \mathbf{w} \\
\text{s.t.} \quad &amp;amp; \mathbf{1}^T \mathbf{w} = 1 \\
&amp;amp; \mathbf{w} \geq \mathbf{0}
\end{align}\]

&lt;p&gt;The feasible region \(S = \{\mathbf{w} : \mathbf{1}^T \mathbf{w} = 1, \mathbf{w} \geq \mathbf{0}\}\) is:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Closed:&lt;/strong&gt; It’s the intersection of closed sets&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bounded:&lt;/strong&gt; The constraint \(\mathbf{1}^T \mathbf{w} = 1\) with \(\mathbf{w} \geq \mathbf{0}\) bounds the feasible region&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compact:&lt;/strong&gt; Being closed and bounded in \(\mathbb{R}^n\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since the objective function \(\mathbf{w}^T \mathbf{\Sigma} \mathbf{w}\) is continuous and \(S\) is compact, the Extreme Value Theorem guarantees that an optimal portfolio exists.&lt;/p&gt;

&lt;p&gt;Understanding topology and real analysis provides the rigorous foundation needed to prove that deep-learning problems have solutions and that algorithms will find them. These concepts are essential for both theoretical analysis and practical algorithm design.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Intro to Open Sets (with Examples)&lt;/td&gt;
          &lt;td&gt;Real Analysis](https://www.youtube.com/watch?v=pnWgj8jjs3w) — Wrath of Math, English. An open set is defined by a ball around every point, which is this lesson’s starting definition.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Identifying Open, Closed, and Compact Sets&lt;/td&gt;
          &lt;td&gt;Real Analysis Exercises](https://www.youtube.com/watch?v=0_mottmadEU) — Wrath of Math, English. Works examples that separate open, closed, and compact sets, including boundary and closure.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Open Covers, Finite Subcovers, and Compact Sets&lt;/td&gt;
          &lt;td&gt;Real Analysis](https://www.youtube.com/watch?v=dAz9ax-bjzU) — Wrath of Math, English. Compactness via open covers is the theorem-level definition the lesson uses for extreme-value arguments.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-03-01 Set Theory Fundamentals</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_03_01_Set_Theory_Fundamentals/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_03_01_Set_Theory_Fundamentals</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Every evaluation metric you compute in machine learning—precision, recall, Intersection-over-Union (IoU) in object detection, or train/validation/test splits—is literally an operation on sets. Mastering set notation and laws prevents subtle bugs like data leakage and miscalculated class metrics.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-set-operations-in-machine-learning-workflows&quot;&gt;Key ideas: Set Operations in Machine Learning Workflows&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Sets, Subsets, and Partitions (Dataset Splitting)&lt;/strong&gt;: Formalizes how a full dataset \(D\) must be partitioned into pairwise disjoint subsets \(D_{\text{train}}, D_{\text{val}}, D_{\text{test}}\) whose union is \(D\) and pairwise intersections are \(\emptyset\) (zero leakage).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Union, Intersection, and Set Difference (Evaluation Metrics)&lt;/strong&gt;: Directly defines True Positives (\(P \cap T\)), False Positives (\(P \setminus T\)), False Negatives (\(T \setminus P\)), and Jaccard / IoU similarity \(\frac{\lvert A \cap B\rvert}{\lvert A \cup B\rvert}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;De Morgan’s Laws &amp;amp; Complements (Logical Filtering)&lt;/strong&gt;: Translates complex boolean data filters—such as excluding samples that are either corrupted or unlabeled—into clean, bug-free set identities: \((A \cup B)^c = A^c \cap B^c\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cartesian Products &amp;amp; Functions (Input–Output Spaces)&lt;/strong&gt;: Defines labeled datasets as subsets of \(\mathcal{X} \times \mathcal{Y}\) and neural models as mappings \(f: \mathcal{X} \to \mathcal{Y}\) between structured sets.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-computing-iou-and-verifying-inclusionexclusion-on-detection-sets&quot;&gt;Worked example: Computing IoU and Verifying Inclusion–Exclusion on Detection Sets&lt;/h3&gt;

&lt;p&gt;Suppose an object detector predicts a set of foreground pixels \(P\) of size \(\lvert P\rvert = 120\), while the ground-truth bounding mask \(T\) has \(\lvert T\rvert = 100\) pixels, and they overlap on \(\lvert P \cap T\rvert = 80\) pixels inside a \(500\)-pixel image \(U\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Union via Inclusion–Exclusion&lt;/strong&gt;:
\(\lvert P \cup T\rvert = \lvert P\rvert + \lvert T\rvert - \lvert P \cap T\rvert = 120 + 100 - 80 = 140\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute Intersection-over-Union (IoU / Jaccard Index)&lt;/strong&gt;:
\(\text{IoU}(P, T) = \frac{\lvert P \cap T\rvert}{\lvert P \cup T\rvert} = \frac{80}{140} = \frac{4}{7} \approx 0.5714\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decompose Errors Using Set Difference&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;False Positives: \(\lvert P \setminus T\rvert = \lvert P\rvert - \lvert P \cap T\rvert = 120 - 80 = 40\).&lt;/li&gt;
      &lt;li&gt;False Negatives: \(\lvert T \setminus P\rvert = \lvert T\rvert - \lvert P \cap T\rvert = 100 - 80 = 20\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Verify True Negatives via De Morgan’s Law&lt;/strong&gt;:
Background pixels correctly ignored are \(P^c \cap T^c = (P \cup T)^c\), so:
\(\lvert P^c \cap T^c\rvert = \lvert U\rvert - \lvert P \cup T\rvert = 500 - 140 = 360\)
Partition check: \(\text{TP} + \text{FP} + \text{FN} + \text{TN} = 80 + 40 + 20 + 360 = 500 = \lvert U\rvert\). Every pixel is accounted for exactly once.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers fundamental concepts from set theory that provide the mathematical foundation for understanding deep-learning problems, constraints, and feasible regions.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;introduction-to-set-theory&quot;&gt;Introduction to Set Theory&lt;/h2&gt;

&lt;p&gt;Set theory provides the foundation for modern mathematics and is essential for understanding deep-learning concepts. A &lt;strong&gt;set&lt;/strong&gt; is simply a collection of distinct objects, called elements or members.&lt;/p&gt;

&lt;h3 id=&quot;basic-notation&quot;&gt;Basic Notation&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Set notation:&lt;/strong&gt; \(A = \{1, 2, 3, 4\}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Element membership:&lt;/strong&gt; \(x \in A\) (x is in A) or \(x \notin A\) (x is not in A)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Empty set:&lt;/strong&gt; \(\emptyset = \{\}\) (the set with no elements)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Set builder notation:&lt;/strong&gt; \(A = \{x : P(x)\}\) (the set of all x such that property P(x) holds)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;examples&quot;&gt;Examples&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;\(A = \{1, 2, 3, 4\}\) (explicit listing)&lt;/li&gt;
  &lt;li&gt;\(B = \{x \in \mathbb{R} : x^2 &amp;lt; 4\} = (-2, 2)\) (set builder notation)&lt;/li&gt;
  &lt;li&gt;\(C = \{x \in \mathbb{Z} : x \text{ is even}\}\) (all even integers)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;basic-set-operations&quot;&gt;Basic Set Operations&lt;/h2&gt;

&lt;h3 id=&quot;sets-and-subsets&quot;&gt;Sets and Subsets&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Subset:&lt;/strong&gt; \(A \subseteq B\) means every element of \(A\) is also in \(B\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Proper Subset:&lt;/strong&gt; \(A \subset B\) means \(A \subseteq B\) and \(A \neq B\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Set Equality:&lt;/strong&gt; \(A = B\) if and only if \(A \subseteq B\) and \(B \subseteq A\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[\{1, 2\} \subseteq \{1, 2, 3, 4\}\]
  &lt;/li&gt;
  &lt;li&gt;
\[\{1, 2\} \subset \{1, 2, 3, 4\}\]
  &lt;/li&gt;
  &lt;li&gt;\(\emptyset \subseteq A\) for any set \(A\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;union-and-intersection&quot;&gt;Union and Intersection&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Union (\(A \cup B\)):&lt;/strong&gt; All elements that are in \(A\) or \(B\) (or both)
\(A \cup B = \{x : x \in A \text{ or } x \in B\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Intersection (\(A \cap B\)):&lt;/strong&gt; All elements that are in both \(A\) and \(B\)
\(A \cap B = \{x : x \in A \text{ and } x \in B\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;If \(A = \{1, 2, 3\}\) and \(B = \{3, 4, 5\}\), then:
    &lt;ul&gt;
      &lt;li&gt;
\[A \cup B = \{1, 2, 3, 4, 5\}\]
      &lt;/li&gt;
      &lt;li&gt;
\[A \cap B = \{3\}\]
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Disjoint Sets:&lt;/strong&gt; \(A\) and \(B\) are disjoint if \(A \cap B = \emptyset\)&lt;/p&gt;

&lt;h3 id=&quot;complement-and-difference&quot;&gt;Complement and Difference&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Complement (\(A^c\)):&lt;/strong&gt; All elements not in \(A\) (within some universal set \(U\))
\(A^c = \{x \in U : x \notin A\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Set Difference (\(A \setminus B\)):&lt;/strong&gt; Elements in \(A\) but not in \(B\)
\(A \setminus B = \{x : x \in A \text{ and } x \notin B\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Symmetric Difference:&lt;/strong&gt; \((A \setminus B) \cup (B \setminus A) = (A \cup B) \setminus (A \cap B)\)&lt;/p&gt;

&lt;h3 id=&quot;set-laws&quot;&gt;Set Laws&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Commutative Laws:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[A \cup B = B \cup A\]
  &lt;/li&gt;
  &lt;li&gt;
\[A \cap B = B \cap A\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Associative Laws:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[(A \cup B) \cup C = A \cup (B \cup C)\]
  &lt;/li&gt;
  &lt;li&gt;
\[(A \cap B) \cap C = A \cap (B \cap C)\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Distributive Laws:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[A \cap (B \cup C) = (A \cap B) \cup (A \cap C)\]
  &lt;/li&gt;
  &lt;li&gt;
\[A \cup (B \cap C) = (A \cup B) \cap (A \cup C)\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;De Morgan’s Laws:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[(A \cup B)^c = A^c \cap B^c\]
  &lt;/li&gt;
  &lt;li&gt;
\[(A \cap B)^c = A^c \cup B^c\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;important-number-sets&quot;&gt;Important Number Sets&lt;/h2&gt;

&lt;p&gt;Understanding the hierarchy of number systems is crucial for deep-learning:&lt;/p&gt;

&lt;h3 id=&quot;natural-numbers&quot;&gt;Natural Numbers&lt;/h3&gt;
&lt;p&gt;\(\mathbb{N} = \{1, 2, 3, 4, \ldots\}\)
(Sometimes includes 0: \(\mathbb{N}_0 = \{0, 1, 2, 3, \ldots\}\))&lt;/p&gt;

&lt;h3 id=&quot;integers&quot;&gt;Integers&lt;/h3&gt;
&lt;p&gt;\(\mathbb{Z} = \{\ldots, -2, -1, 0, 1, 2, \ldots\}\)&lt;/p&gt;

&lt;h3 id=&quot;rational-numbers&quot;&gt;Rational Numbers&lt;/h3&gt;
&lt;p&gt;\(\mathbb{Q} = \left\{\frac{p}{q} : p, q \in \mathbb{Z}, q \neq 0\right\}\)&lt;/p&gt;

&lt;p&gt;All numbers that can be expressed as fractions.&lt;/p&gt;

&lt;h3 id=&quot;real-numbers&quot;&gt;Real Numbers&lt;/h3&gt;
&lt;p&gt;\(\mathbb{R}\) includes all rational and irrational numbers (like \(\pi\), \(e\), \(\sqrt{2}\)).&lt;/p&gt;

&lt;h3 id=&quot;complex-numbers&quot;&gt;Complex Numbers&lt;/h3&gt;
&lt;p&gt;\(\mathbb{C} = \{a + bi : a, b \in \mathbb{R}, i^2 = -1\}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hierarchy:&lt;/strong&gt; \(\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q} \subset \mathbb{R} \subset \mathbb{C}\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;functions-domain-and-range&quot;&gt;Functions: Domain and Range&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;function&lt;/strong&gt; \(f: A \to B\) is a rule that assigns to each element in set \(A\) exactly one element in set \(B\).&lt;/p&gt;

&lt;h3 id=&quot;key-concepts&quot;&gt;Key Concepts&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Domain:&lt;/strong&gt; The set \(A\) of all possible input values&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Codomain:&lt;/strong&gt; The set \(B\) where outputs are taken from&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Range (Image):&lt;/strong&gt; The set of all actual output values: \(\text{Range}(f) = \{f(x) : x \in A\} \subseteq B\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt; For \(f(x) = x^2\) with \(f: \mathbb{R} \to \mathbb{R}\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Domain: \(\mathbb{R}\)&lt;/li&gt;
  &lt;li&gt;Codomain: \(\mathbb{R}\)&lt;/li&gt;
  &lt;li&gt;Range: \([0, \infty)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;types-of-functions&quot;&gt;Types of Functions&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Injective (One-to-One):&lt;/strong&gt; Each element in the range corresponds to exactly one element in the domain
\(f(x_1) = f(x_2) \implies x_1 = x_2\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Surjective (Onto):&lt;/strong&gt; Every element in the codomain is in the range
For every \(y \in B\), there exists \(x \in A\) such that \(f(x) = y\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Bijective:&lt;/strong&gt; Both injective and surjective
There’s a perfect one-to-one correspondence between domain and codomain.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(f(x) = 2x\) on \(\mathbb{R}\) is bijective&lt;/li&gt;
  &lt;li&gt;\(f(x) = x^2\) on \(\mathbb{R}\) is neither injective nor surjective&lt;/li&gt;
  &lt;li&gt;\(f(x) = x^2\) on \([0, \infty) \to [0, \infty)\) is bijective&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;inequalities&quot;&gt;Inequalities&lt;/h2&gt;

&lt;p&gt;Understanding inequalities is crucial for deep-learning, as constraints are often expressed as inequalities.&lt;/p&gt;

&lt;h3 id=&quot;basic-inequality-symbols&quot;&gt;Basic Inequality Symbols&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;\(a &amp;lt; b\): \(a\) is strictly less than \(b\)&lt;/li&gt;
  &lt;li&gt;\(a \leq b\): \(a\) is less than or equal to \(b\)&lt;/li&gt;
  &lt;li&gt;\(a &amp;gt; b\): \(a\) is strictly greater than \(b\)&lt;/li&gt;
  &lt;li&gt;\(a \geq b\): \(a\) is greater than or equal to \(b\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;properties-of-inequalities&quot;&gt;Properties of Inequalities&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Transitivity:&lt;/strong&gt; If \(a \leq b\) and \(b \leq c\), then \(a \leq c\)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Addition:&lt;/strong&gt; If \(a \leq b\), then \(a + c \leq b + c\) for any \(c\)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Multiplication by Positive:&lt;/strong&gt; If \(a \leq b\) and \(c &amp;gt; 0\), then \(ac \leq bc\)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Multiplication by Negative:&lt;/strong&gt; If \(a \leq b\) and \(c &amp;lt; 0\), then \(ac \geq bc\) (inequality flips!)&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;interval-notation&quot;&gt;Interval Notation&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Open interval:&lt;/strong&gt; \((a, b) = \{x \in \mathbb{R} : a &amp;lt; x &amp;lt; b\}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Closed interval:&lt;/strong&gt; \([a, b] = \{x \in \mathbb{R} : a \leq x \leq b\}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Half-open intervals:&lt;/strong&gt; \([a, b)\), \((a, b]\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Unbounded intervals:&lt;/strong&gt; \((-\infty, a)\), \([a, \infty)\), \((-\infty, \infty) = \mathbb{R}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;applications-in-deep-learning&quot;&gt;Applications in Deep Learning&lt;/h2&gt;

&lt;p&gt;Set theory concepts are fundamental to deep-learning:&lt;/p&gt;

&lt;h3 id=&quot;1-feasible-regions&quot;&gt;1. Feasible Regions&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;feasible region&lt;/strong&gt; is the set of all points satisfying the constraints:
\(S = \{x \in \mathbb{R}^n : g_i(x) \leq 0, i = 1, \ldots, m; h_j(x) = 0, j = 1, \ldots, p\}\)&lt;/p&gt;

&lt;h3 id=&quot;2-level-sets&quot;&gt;2. Level Sets&lt;/h3&gt;

&lt;p&gt;For a function \(f: \mathbb{R}^n \to \mathbb{R}\), the &lt;strong&gt;level set&lt;/strong&gt; at level \(c\) is:
\(L_c = \{x \in \mathbb{R}^n : f(x) = c\}\)&lt;/p&gt;

&lt;h3 id=&quot;3-constraint-qualification&quot;&gt;3. Constraint Qualification&lt;/h3&gt;

&lt;p&gt;Understanding when constraint sets have “nice” properties (like being closed or having non-empty interior) affects the existence and characterization of optimal solutions.&lt;/p&gt;

&lt;h3 id=&quot;4-convergence-analysis&quot;&gt;4. Convergence Analysis&lt;/h3&gt;

&lt;p&gt;Sequences and limits are essential for analyzing whether deep-learning algorithms converge to optimal solutions.&lt;/p&gt;

&lt;h3 id=&quot;5-set-operations-in-algorithms&quot;&gt;5. Set Operations in Algorithms&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Intersection:&lt;/strong&gt; Finding points that satisfy multiple constraints&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Union:&lt;/strong&gt; Combining feasible regions from different scenarios&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Complement:&lt;/strong&gt; Understanding infeasible regions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt; In linear programming, the feasible region is:
\(S = \{x \in \mathbb{R}^n : Ax \leq b, x \geq 0\} = \bigcap_{i=1}^{m} \{x : a_i^T x \leq b_i\} \cap \{x : x \geq 0\}\)&lt;/p&gt;

&lt;p&gt;This is the intersection of half-spaces, demonstrating how set operations naturally arise in deep-learning problem formulation.&lt;/p&gt;

&lt;p&gt;Understanding set theory provides the rigorous mathematical foundation needed to formulate deep-learning problems precisely and analyze their properties systematically.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Intro to Sets&lt;/td&gt;
          &lt;td&gt;Examples, Notation &amp;amp; Properties](https://www.youtube.com/watch?v=B1v2-nGXNzs) — Dr. Trefor Bazett, English. Set notation, operations, and what a function’s domain and codomain are.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=tyDKR4FG3Yw&quot;&gt;INTRODUCTION to SET THEORY - DISCRETE MATHEMATICS&lt;/a&gt; — TrevTutor, English. A fuller pass over unions, intersections, and the number sets the lesson lists.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=JzIjCkouIGg&quot;&gt;MaDL - Sets, Scalars, Vectors, Matrices and Tensors&lt;/a&gt; — Tübingen Machine Learning, English. Connects those sets to the scalars, vectors, and tensors the rest of the course actually computes with.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-02 Basic Linear Algebra</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_02_Basic_Linear_Algebra/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_02_Basic_Linear_Algebra</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;If you ever wonder why GPUs—chips originally built to rotate 3D triangles in video games—sparked the deep learning revolution, the answer is linear algebra. A neural network is, at its core, an alternating cascade of matrix multiplications and nonlinearities, and linear algebra gives us the geometry to understand what those matrices actually do to data.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-the-three-pillars-of-linear-algebra-in-deep-learning&quot;&gt;Key ideas: The Three Pillars of Linear Algebra in Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Vectors &amp;amp; Vector Spaces (Feature Geometry)&lt;/strong&gt;: Represents words, images, and hidden states as points in \(\mathbb{R}^d\), where inner products measure semantic similarity and norms measure signal energy.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matrices &amp;amp; Linear Transformations (Layer Operators)&lt;/strong&gt;: Views every weight matrix \(W \in \mathbb{R}^{m \times n}\) as a geometric operator that rotates, scales, shears, or projects data from one representation space to another.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Eigenvalues &amp;amp; Eigenvectors (Dynamical Stability)&lt;/strong&gt;: Reveals the invariant axes of a linear operator, governing PCA dimensionality reduction, Hessian conditioning, and why repeated matrix multiplication causes vanishing or exploding gradients in deep networks.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-tracing-a-feature-vector-through-a-linear-layer-and-its-spectrum&quot;&gt;Worked example: Tracing a Feature Vector Through a Linear Layer and Its Spectrum&lt;/h3&gt;

&lt;p&gt;Consider a 2D input feature vector \(\mathbf{x} = \begin{bmatrix} 3 \\ 1 \end{bmatrix}\) passed through a symmetric weight matrix \(W = \begin{bmatrix} 2 &amp;amp; 1 \\ 1 &amp;amp; 2 \end{bmatrix}\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Matrix-Vector Transformation (Forward Pass)&lt;/strong&gt;:
\(\mathbf{h} = W\mathbf{x} = \begin{bmatrix} 2 &amp;amp; 1 \\ 1 &amp;amp; 2 \end{bmatrix}\begin{bmatrix} 3 \\ 1 \end{bmatrix} = \begin{bmatrix} 2(3) + 1(1) \\ 1(3) + 2(1) \end{bmatrix} = \begin{bmatrix} 7 \\ 5 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Find the Eigenvalues of \(W\)&lt;/strong&gt;:
\(\det(W - \lambda I) = (2 - \lambda)^2 - 1 = \lambda^2 - 4\lambda + 3 = (\lambda - 3)(\lambda - 1) = 0\)
So \(\lambda_1 = 3\) (eigenvector \(\mathbf{v}_1 = \frac{1}{\sqrt{2}}\begin{bmatrix} 1 \\ 1 \end{bmatrix}\)) and \(\lambda_2 = 1\) (eigenvector \(\mathbf{v}_2 = \frac{1}{\sqrt{2}}\begin{bmatrix} 1 \\ -1 \end{bmatrix}\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Decompose \(\mathbf{x}\) in the Eigenbasis&lt;/strong&gt;:
Notice \(\mathbf{x} = \begin{bmatrix} 3 \\ 1 \end{bmatrix} = 2\begin{bmatrix} 1 \\ 1 \end{bmatrix} + 1\begin{bmatrix} 1 \\ -1 \end{bmatrix}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply \(W\) Spectrally and Verify&lt;/strong&gt;:
\(W\mathbf{x} = 2(3)\begin{bmatrix} 1 \\ 1 \end{bmatrix} + 1(1)\begin{bmatrix} 1 \\ -1 \end{bmatrix} = \begin{bmatrix} 6 \\ 6 \end{bmatrix} + \begin{bmatrix} 1 \\ -1 \end{bmatrix} = \begin{bmatrix} 7 \\ 5 \end{bmatrix}\)
After \(k\) repeated linear layers, \(W^k \mathbf{x} = 2(3^k)\begin{bmatrix} 1 \\ 1 \end{bmatrix} + 1(1^k)\begin{bmatrix} 1 \\ -1 \end{bmatrix}\), showing immediately why the dominant eigenvalue \(\lambda_1 = 3\) exponentially overwhelms the smaller mode!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers essential linear algebra concepts needed for deep-learning, organized into three main sections for systematic learning.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Vectors&lt;/td&gt;
          &lt;td&gt;Chapter 1, Essence of linear algebra](https://www.youtube.com/watch?v=fNk_zzaMoSs) — 3Blue1Brown, English. Vectors in R^n are the objects the linear-algebra block is about.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Linear transformations and matrices&lt;/td&gt;
          &lt;td&gt;Chapter 3, Essence of linear algebra](https://www.youtube.com/watch?v=kYB8IZa5AuE) — 3Blue1Brown, English. Matrices as linear maps are the second lesson in this block.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Eigenvectors and eigenvalues&lt;/td&gt;
          &lt;td&gt;Chapter 14, Essence of linear algebra](https://www.youtube.com/watch?v=PFDu9oVAE-g) — 3Blue1Brown, English. Eigenvectors are the third lesson; this is the geometric picture before any algorithm.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-02-03 Eigenvalues and Eigenvectors</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_02_03_Eigenvalues_and_Eigenvectors/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_02_03_Eigenvalues_and_Eigenvectors</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Train a 50-layer recurrent network with carelessly scaled weights and within seconds your gradients either collapse to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0.0&lt;/code&gt; or explode to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;NaN&lt;/code&gt;. Why? Because multiplying by the same matrix \(W\) fifty times scales every component along its eigenvectors by \(\lambda_i^{50}\)—and eigenvalues tell you at a glance whether a system will die, stabilize, or blow up.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-spectral-structure-of-matrices&quot;&gt;Key ideas: Spectral Structure of Matrices&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Eigenvalues &amp;amp; Eigenvectors (Invariant Directions)&lt;/strong&gt;: Nonzero vectors \(\mathbf{v}\) that a matrix \(A\) merely stretches or flips (\(A\mathbf{v} = \lambda\mathbf{v}\)) without rotating, revealing the intrinsic coordinate axes of the transformation.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Characteristic Polynomial &amp;amp; Trace/Determinant Checks&lt;/strong&gt;: Eigenvalues satisfy \(\det(A - \lambda I) = 0\), and always obey two quick sanity checks: \(\sum_i \lambda_i = \text{tr}(A)\) and \(\prod_i \lambda_i = \det(A)\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Spectral Theorem for Symmetric Matrices&lt;/strong&gt;: Real symmetric matrices (such as covariance matrices in PCA and Hessians of smooth losses) always have real eigenvalues and an orthonormal eigenbasis, guaranteeing clean diagonalization \(A = Q\Lambda Q^\top\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Condition Number &amp;amp; Optimization Speed&lt;/strong&gt;: The ratio \(\kappa = \lvert \lambda_{\max}\rvert / \lvert \lambda_{\min}\rvert\) of the Hessian controls how elongated a loss valley is; large \(\kappa\) forces vanilla gradient descent to crawl, motivating preconditioning and normalization.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-full-eigendecomposition-and-condition-number-of-a-hessian&quot;&gt;Worked example: Full Eigendecomposition and Condition Number of a Hessian&lt;/h3&gt;

&lt;p&gt;Consider the symmetric Hessian matrix \(H = \begin{bmatrix} 5 &amp;amp; 2 \\ 2 &amp;amp; 2 \end{bmatrix}\) of a quadratic loss \(L(\mathbf{w}) = \frac{1}{2}\mathbf{w}^\top H \mathbf{w}\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Solve the Characteristic Equation \(\det(H - \lambda I) = 0\)&lt;/strong&gt;:
\((5 - \lambda)(2 - \lambda) - (2)(2) = \lambda^2 - 7\lambda + 10 - 4 = \lambda^2 - 7\lambda + 6 = 0\)
Factoring gives \((\lambda - 6)(\lambda - 1) = 0\), so \(\lambda_1 = 6\) and \(\lambda_2 = 1\).
    &lt;ul&gt;
      &lt;li&gt;Trace check: \(\lambda_1 + \lambda_2 = 6 + 1 = 7 = 5 + 2 = \text{tr}(H)\).&lt;/li&gt;
      &lt;li&gt;Determinant check: \(\lambda_1 \lambda_2 = 6 \times 1 = 6 = (5)(2) - 4 = \det(H)\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Find Orthonormal Eigenvectors&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;For \(\lambda_1 = 6\): \((H - 6I)\mathbf{v} = \begin{bmatrix} -1 &amp;amp; 2 \\ 2 &amp;amp; -4 \end{bmatrix}\begin{bmatrix} v_1 \\ v_2 \end{bmatrix} = \mathbf{0} \implies v_1 = 2v_2\).
Normalized: \(\mathbf{q}_1 = \frac{1}{\sqrt{5}}\begin{bmatrix} 2 \\ 1 \end{bmatrix}\).&lt;/li&gt;
      &lt;li&gt;For \(\lambda_2 = 1\): \((H - I)\mathbf{v} = \begin{bmatrix} 4 &amp;amp; 2 \\ 2 &amp;amp; 1 \end{bmatrix}\begin{bmatrix} v_1 \\ v_2 \end{bmatrix} = \mathbf{0} \implies v_2 = -2v_1\).
Normalized: \(\mathbf{q}_2 = \frac{1}{\sqrt{5}}\begin{bmatrix} 1 \\ -2 \end{bmatrix}\).&lt;/li&gt;
      &lt;li&gt;Orthogonality check: \(\mathbf{q}_1^\top \mathbf{q}_2 = \frac{1}{5}(2 - 2) = 0\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Optimization Implication (Condition Number &amp;amp; Max Safe Step Size)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Condition number: \(\kappa(H) = \frac{\lambda_1}{\lambda_2} = \frac{6}{1} = 6\).&lt;/li&gt;
      &lt;li&gt;Maximum stable gradient descent learning rate: \(\eta_{\max} = \frac{2}{\lambda_{\max}} = \frac{2}{6} = \frac{1}{3} \approx 0.333\). Any step size \(\eta &amp;gt; 1/3\) will oscillate and diverge along \(\mathbf{q}_1\)!&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers eigenvalues and eigenvectors, which are crucial for understanding the behavior of linear transformations and quadratic functions in deep-learning.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;definition-and-intuition&quot;&gt;Definition and Intuition&lt;/h2&gt;

&lt;p&gt;When a matrix transforms a vector, it usually changes both the vector’s direction and its length. However, &lt;strong&gt;eigenvectors&lt;/strong&gt; are special vectors that, when transformed by a given matrix, only get scaled but do not change their direction.&lt;/p&gt;

&lt;h3 id=&quot;mathematical-definition&quot;&gt;Mathematical Definition&lt;/h3&gt;

&lt;p&gt;For a square matrix \(\mathbf{A}\) and a non-zero vector \(\mathbf{v}\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;\(\mathbf{v}\) is an &lt;strong&gt;eigenvector&lt;/strong&gt; of \(\mathbf{A}\)&lt;/li&gt;
  &lt;li&gt;\(\lambda\) is the corresponding &lt;strong&gt;eigenvalue&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;if they satisfy the &lt;strong&gt;eigenvalue equation&lt;/strong&gt;:&lt;/p&gt;

\[\mathbf{A}\mathbf{v} = \lambda\mathbf{v}\]

&lt;h3 id=&quot;geometric-interpretation&quot;&gt;Geometric Interpretation&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Eigenvectors:&lt;/strong&gt; Non-zero vectors that maintain their direction under the transformation \(\mathbf{A}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Eigenvalues:&lt;/strong&gt; The scalar factors by which the eigenvectors are scaled&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Visual Understanding:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;If \(\lambda &amp;gt; 1\): The eigenvector is stretched&lt;/li&gt;
  &lt;li&gt;If \(0 &amp;lt; \lambda &amp;lt; 1\): The eigenvector is shrunk&lt;/li&gt;
  &lt;li&gt;If \(\lambda &amp;lt; 0\): The eigenvector is scaled and flipped&lt;/li&gt;
  &lt;li&gt;If \(\lambda = 0\): The eigenvector is mapped to the zero vector&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;finding-eigenvalues-and-eigenvectors&quot;&gt;Finding Eigenvalues and Eigenvectors&lt;/h2&gt;

&lt;h3 id=&quot;step-1-find-eigenvalues&quot;&gt;Step 1: Find Eigenvalues&lt;/h3&gt;

&lt;p&gt;Rearrange the eigenvalue equation:
\(\mathbf{A}\mathbf{v} = \lambda\mathbf{v}\)
\(\mathbf{A}\mathbf{v} - \lambda\mathbf{v} = \mathbf{0}\)
\((\mathbf{A} - \lambda\mathbf{I})\mathbf{v} = \mathbf{0}\)&lt;/p&gt;

&lt;p&gt;For a non-trivial solution (\(\mathbf{v} \neq \mathbf{0}\)), the matrix \((\mathbf{A} - \lambda\mathbf{I})\) must be singular, so:&lt;/p&gt;

\[\det(\mathbf{A} - \lambda\mathbf{I}) = 0\]

&lt;p&gt;This is called the &lt;strong&gt;characteristic equation&lt;/strong&gt;.&lt;/p&gt;

&lt;h3 id=&quot;step-2-find-eigenvectors&quot;&gt;Step 2: Find Eigenvectors&lt;/h3&gt;

&lt;p&gt;For each eigenvalue \(\lambda_i\), solve the system:
\((\mathbf{A} - \lambda_i\mathbf{I})\mathbf{v} = \mathbf{0}\)&lt;/p&gt;

&lt;p&gt;The solutions form the &lt;strong&gt;eigenspace&lt;/strong&gt; corresponding to \(\lambda_i\).&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;detailed-example&quot;&gt;Detailed Example&lt;/h2&gt;

&lt;p&gt;Let’s find the eigenvalues and eigenvectors of \(\mathbf{A} = \begin{pmatrix} 3 &amp;amp; 1 \\ 0 &amp;amp; 2 \end{pmatrix}\).&lt;/p&gt;

&lt;h3 id=&quot;step-1-find-eigenvalues-1&quot;&gt;Step 1: Find Eigenvalues&lt;/h3&gt;

\[\mathbf{A} - \lambda\mathbf{I} = \begin{pmatrix} 3 &amp;amp; 1 \\ 0 &amp;amp; 2 \end{pmatrix} - \lambda\begin{pmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{pmatrix} = \begin{pmatrix} 3-\lambda &amp;amp; 1 \\ 0 &amp;amp; 2-\lambda \end{pmatrix}\]

\[\det(\mathbf{A} - \lambda\mathbf{I}) = (3-\lambda)(2-\lambda) - (1)(0) = (3-\lambda)(2-\lambda) = 0\]

&lt;p&gt;This gives us \(\lambda_1 = 3\) and \(\lambda_2 = 2\).&lt;/p&gt;

&lt;h3 id=&quot;step-2-find-eigenvectors-1&quot;&gt;Step 2: Find Eigenvectors&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;For \(\lambda_1 = 3\):&lt;/strong&gt;
\((\mathbf{A} - 3\mathbf{I})\mathbf{v} = \begin{pmatrix} 0 &amp;amp; 1 \\ 0 &amp;amp; -1 \end{pmatrix}\begin{pmatrix} v_1 \\ v_2 \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;This gives us \(v_2 = 0\) and \(v_1\) can be any non-zero value. So \(\mathbf{v}_1 = \begin{pmatrix} 1 \\ 0 \end{pmatrix}\) (or any scalar multiple).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For \(\lambda_2 = 2\):&lt;/strong&gt;
\((\mathbf{A} - 2\mathbf{I})\mathbf{v} = \begin{pmatrix} 1 &amp;amp; 1 \\ 0 &amp;amp; 0 \end{pmatrix}\begin{pmatrix} v_1 \\ v_2 \end{pmatrix} = \begin{pmatrix} 0 \\ 0 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;This gives us \(v_1 + v_2 = 0\), so \(v_2 = -v_1\). Thus \(\mathbf{v}_2 = \begin{pmatrix} 1 \\ -1 \end{pmatrix}\) (or any scalar multiple).&lt;/p&gt;

&lt;h3 id=&quot;verification&quot;&gt;Verification&lt;/h3&gt;

&lt;p&gt;Let’s verify our results:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{A}\mathbf{v}_1 = \begin{pmatrix} 3 &amp;amp; 1 \\ 0 &amp;amp; 2 \end{pmatrix}\begin{pmatrix} 1 \\ 0 \end{pmatrix} = \begin{pmatrix} 3 \\ 0 \end{pmatrix} = 3\begin{pmatrix} 1 \\ 0 \end{pmatrix} = 3\mathbf{v}_1\) ✓&lt;/li&gt;
  &lt;li&gt;\(\mathbf{A}\mathbf{v}_2 = \begin{pmatrix} 3 &amp;amp; 1 \\ 0 &amp;amp; 2 \end{pmatrix}\begin{pmatrix} 1 \\ -1 \end{pmatrix} = \begin{pmatrix} 2 \\ -2 \end{pmatrix} = 2\begin{pmatrix} 1 \\ -1 \end{pmatrix} = 2\mathbf{v}_2\) ✓&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;properties-and-important-theorems&quot;&gt;Properties and Important Theorems&lt;/h2&gt;

&lt;h3 id=&quot;key-properties&quot;&gt;Key Properties&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Sum of eigenvalues = trace of matrix:&lt;/strong&gt;
\(\sum_{i=1}^n \lambda_i = \text{tr}(\mathbf{A}) = \sum_{i=1}^n a_{ii}\)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Product of eigenvalues = determinant of matrix:&lt;/strong&gt;
\(\prod_{i=1}^n \lambda_i = \det(\mathbf{A})\)&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Eigenvectors corresponding to different eigenvalues are linearly independent&lt;/strong&gt;&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;If \(\mathbf{A}\) is symmetric, all eigenvalues are real and eigenvectors are orthogonal&lt;/strong&gt;&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;eigenvalue-multiplicity&quot;&gt;Eigenvalue Multiplicity&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Algebraic multiplicity:&lt;/strong&gt; How many times \(\lambda\) appears as a root of the characteristic polynomial&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Geometric multiplicity:&lt;/strong&gt; The dimension of the eigenspace (number of linearly independent eigenvectors)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For any eigenvalue: geometric multiplicity ≤ algebraic multiplicity&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;diagonalization&quot;&gt;Diagonalization&lt;/h2&gt;

&lt;p&gt;A matrix \(\mathbf{A}\) is &lt;strong&gt;diagonalizable&lt;/strong&gt; if it can be written as:&lt;/p&gt;

\[\mathbf{A} = \mathbf{P}\mathbf{D}\mathbf{P}^{-1}\]

&lt;p&gt;where:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{D}\) is a diagonal matrix of eigenvalues&lt;/li&gt;
  &lt;li&gt;\(\mathbf{P}\) is a matrix whose columns are the corresponding eigenvectors&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;benefits-of-diagonalization&quot;&gt;Benefits of Diagonalization&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Easy computation of powers:&lt;/strong&gt; \(\mathbf{A}^k = \mathbf{P}\mathbf{D}^k\mathbf{P}^{-1}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Understanding behavior:&lt;/strong&gt; The eigenvalues determine the transformation’s behavior along each eigenvector direction&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;applications-in-deep-learning&quot;&gt;Applications in Deep Learning&lt;/h2&gt;

&lt;p&gt;Eigenvalues and eigenvectors are crucial in deep-learning for several reasons:&lt;/p&gt;

&lt;h3 id=&quot;1-quadratic-forms-and-definiteness&quot;&gt;1. Quadratic Forms and Definiteness&lt;/h3&gt;

&lt;p&gt;For a quadratic function \(f(\mathbf{x}) = \mathbf{x}^T\mathbf{Q}\mathbf{x}\):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Positive definite&lt;/strong&gt; (\(f(\mathbf{x}) &amp;gt; 0\) for \(\mathbf{x} \neq \mathbf{0}\)): All eigenvalues of \(\mathbf{Q}\) are positive&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Positive semidefinite&lt;/strong&gt; (\(f(\mathbf{x}) \geq 0\)): All eigenvalues are non-negative&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Negative definite&lt;/strong&gt; (\(f(\mathbf{x}) &amp;lt; 0\) for \(\mathbf{x} \neq \mathbf{0}\)): All eigenvalues are negative&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Indefinite&lt;/strong&gt; (\(f(\mathbf{x})\) can be positive or negative): Mixed positive and negative eigenvalues&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-second-order-optimality-conditions&quot;&gt;2. Second-Order Optimality Conditions&lt;/h3&gt;

&lt;p&gt;For a function \(f(\mathbf{x})\) at a critical point \(\mathbf{x}^*\) (where \(\nabla f(\mathbf{x}^*) = \mathbf{0}\)):&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Local minimum:&lt;/strong&gt; Hessian \(\nabla^2 f(\mathbf{x}^*)\) is positive definite (all eigenvalues &amp;gt; 0)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Local maximum:&lt;/strong&gt; Hessian is negative definite (all eigenvalues &amp;lt; 0)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Saddle point:&lt;/strong&gt; Hessian is indefinite (mixed eigenvalues)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;3-principal-component-analysis-pca&quot;&gt;3. Principal Component Analysis (PCA)&lt;/h3&gt;

&lt;p&gt;PCA finds the directions of maximum variance in data:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Eigenvectors of the covariance matrix give the principal directions&lt;/li&gt;
  &lt;li&gt;Eigenvalues give the variance along each principal direction&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;4-convergence-analysis&quot;&gt;4. Convergence Analysis&lt;/h3&gt;

&lt;p&gt;In iterative deep-learning algorithms:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;The &lt;strong&gt;condition number&lt;/strong&gt; \(\kappa = \frac{\lambda_{\max}}{\lambda_{\min}}\) affects convergence speed&lt;/li&gt;
  &lt;li&gt;Large condition numbers lead to slow convergence&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;5-newtons-method&quot;&gt;5. Newton’s Method&lt;/h3&gt;

&lt;p&gt;Newton’s method uses the inverse Hessian:
\(\mathbf{x}_{k+1} = \mathbf{x}_k - [\nabla^2 f(\mathbf{x}_k)]^{-1} \nabla f(\mathbf{x}_k)\)&lt;/p&gt;

&lt;p&gt;The eigenvalues of the Hessian determine the method’s behavior and convergence rate.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;example-deep-learning-application&quot;&gt;Example: Deep Learning Application&lt;/h2&gt;

&lt;p&gt;Consider minimizing \(f(x, y) = 2x^2 + 3y^2 + 2xy\).&lt;/p&gt;

&lt;p&gt;The Hessian is: \(\mathbf{H} = \begin{pmatrix} 4 &amp;amp; 2 \\ 2 &amp;amp; 6 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Finding eigenvalues:&lt;/strong&gt;
\(\det(\mathbf{H} - \lambda\mathbf{I}) = (4-\lambda)(6-\lambda) - 4 = \lambda^2 - 10\lambda + 20 = 0\)&lt;/p&gt;

\[\lambda = \frac{10 \pm \sqrt{100-80}}{2} = \frac{10 \pm 2\sqrt{5}}{2} = 5 \pm \sqrt{5}\]

&lt;p&gt;Since both eigenvalues are positive (\(\lambda_1 = 5 + \sqrt{5} &amp;gt; 0\) and \(\lambda_2 = 5 - \sqrt{5} &amp;gt; 0\)), the Hessian is positive definite, confirming that the origin is a global minimum.&lt;/p&gt;

&lt;p&gt;The condition number is \(\kappa = \frac{5 + \sqrt{5}}{5 - \sqrt{5}} \approx 4.24\), indicating reasonably good conditioning for deep-learning algorithms.&lt;/p&gt;

&lt;p&gt;Understanding eigenvalues and eigenvectors provides deep insights into the geometric and analytical properties of deep-learning problems, enabling better algorithm design and convergence analysis.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Eigenvectors and eigenvalues&lt;/td&gt;
          &lt;td&gt;Chapter 14, Essence of linear algebra](https://www.youtube.com/watch?v=PFDu9oVAE-g) — 3Blue1Brown, English. The geometric definition: Av is a scaled copy of v.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=-GcrsEqzmsA&quot;&gt;MaDL - Eigenvalue and Singular Value Decomposition&lt;/a&gt; — Tübingen Machine Learning, English. Computes eigenvalues and the SVD the lesson’s diagonalization section leads into.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-02-02 Matrices and Linear Transformations</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_02_02_Matrices_and_Linear_Transformations/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_02_02_Matrices_and_Linear_Transformations</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;When PyTorch executes &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nn.Linear(768, 3072)&lt;/code&gt;, it is not merely shuffling a grid of numbers—it is applying a linear map that embeds a 768-dimensional token representation into a richer 3072-dimensional space where previously entangled concepts become linearly separable.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-matrices-as-geometric-operators&quot;&gt;Key ideas: Matrices as Geometric Operators&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Matrices as Linear Maps&lt;/strong&gt;: Every \(m \times n\) matrix \(A\) uniquely specifies a linear transformation \(T(\mathbf{x}) = A\mathbf{x}\) from \(\mathbb{R}^n\) to \(\mathbb{R}^m\), with its columns showing exactly where the standard basis vectors land.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Matrix Multiplication as Composition&lt;/strong&gt;: Multiplying \(B(A\mathbf{x}) = (BA)\mathbf{x}\) composes two sequential transformations; this also explains why stacking linear layers without nonlinear activations collapses into a single matrix \(W_{\text{eff}} = W_2 W_1\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Rank, Nullspace, and Information Bottlenecks&lt;/strong&gt;: The rank of \(W\) equals the dimension of its output subspace, while its nullspace \(\ker(W) = \{\mathbf{x} : W\mathbf{x} = \mathbf{0}\}\) captures all input directions permanently erased by the layer.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Transpose and Adjoint (The Backward Pass Operator)&lt;/strong&gt;: If a forward layer multiplies by \(W\), backpropagating gradients multiplies by \(W^\top\), mapping output sensitivities back into the input coordinate space.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-composing-two-linear-layers-and-verifying-non-commutativity&quot;&gt;Worked example: Composing Two Linear Layers and Verifying Non-Commutativity&lt;/h3&gt;

&lt;p&gt;Let Layer 1 project from \(\mathbb{R}^2 \to \mathbb{R}^2\) via \(A = \begin{bmatrix} 1 &amp;amp; 2 \\ 0 &amp;amp; 1 \end{bmatrix}\) (horizontal shear) and Layer 2 scale coordinates via \(B = \begin{bmatrix} 2 &amp;amp; 0 \\ 0 &amp;amp; -1 \end{bmatrix}\). Apply them to \(\mathbf{x} = \begin{bmatrix} 3 \\ 4 \end{bmatrix}\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Step-by-Step Application (\(A\) then \(B\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;First apply \(A\):
\(\mathbf{h} = A\mathbf{x} = \begin{bmatrix} 1(3) + 2(4) \\ 0(3) + 1(4) \end{bmatrix} = \begin{bmatrix} 11 \\ 4 \end{bmatrix}\)&lt;/li&gt;
      &lt;li&gt;Then apply \(B\):
\(\mathbf{y} = B\mathbf{h} = \begin{bmatrix} 2(11) + 0(4) \\ 0(11) + (-1)(4) \end{bmatrix} = \begin{bmatrix} 22 \\ -4 \end{bmatrix}\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Collapsed Composite Matrix \(BA\)&lt;/strong&gt;:
\(BA = \begin{bmatrix} 2 &amp;amp; 0 \\ 0 &amp;amp; -1 \end{bmatrix}\begin{bmatrix} 1 &amp;amp; 2 \\ 0 &amp;amp; 1 \end{bmatrix} = \begin{bmatrix} 2 &amp;amp; 4 \\ 0 &amp;amp; -1 \end{bmatrix}\)
Check directly: \((BA)\mathbf{x} = \begin{bmatrix} 2(3) + 4(4) \\ 0(3) - 1(4) \end{bmatrix} = \begin{bmatrix} 22 \\ -4 \end{bmatrix}\). Exact match!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Check the Reverse Order \(AB\) (Non-Commutativity)&lt;/strong&gt;:
\(AB = \begin{bmatrix} 1 &amp;amp; 2 \\ 0 &amp;amp; 1 \end{bmatrix}\begin{bmatrix} 2 &amp;amp; 0 \\ 0 &amp;amp; -1 \end{bmatrix} = \begin{bmatrix} 2 &amp;amp; -2 \\ 0 &amp;amp; -1 \end{bmatrix} \neq BA\)
Applying \(AB\) to \(\mathbf{x}\) gives \(\begin{bmatrix} 2(3) - 2(4) \\ -4 \end{bmatrix} = \begin{bmatrix} -2 \\ -4 \end{bmatrix}\). Order of transformations matters dramatically in deep architectures.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers matrices, matrix operations, and linear transformations, which are fundamental tools for representing and solving deep-learning problems.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;matrices-and-matrix-operations&quot;&gt;Matrices and Matrix Operations&lt;/h2&gt;

&lt;h3 id=&quot;what-is-a-matrix&quot;&gt;What is a Matrix?&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;matrix&lt;/strong&gt; is a rectangular grid of numbers arranged in rows and columns. Matrices represent data, transformations, systems of equations, and relationships between variables.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;General Form:&lt;/strong&gt;
\(\mathbf{A} = \begin{pmatrix} 
a_{11} &amp;amp; a_{12} &amp;amp; \cdots &amp;amp; a_{1n} \\
a_{21} &amp;amp; a_{22} &amp;amp; \cdots &amp;amp; a_{2n} \\
\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\
a_{m1} &amp;amp; a_{m2} &amp;amp; \cdots &amp;amp; a_{mn}
\end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;This is an \(m \times n\) matrix (\(m\) rows, \(n\) columns).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;
\(\mathbf{A} = \begin{pmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 4 &amp;amp; 5 &amp;amp; 6 \end{pmatrix}\) is a \(2 \times 3\) matrix.&lt;/p&gt;

&lt;h3 id=&quot;matrix-addition&quot;&gt;Matrix Addition&lt;/h3&gt;

&lt;p&gt;Matrices are added by summing corresponding elements. Both matrices must have the same dimensions.&lt;/p&gt;

\[\mathbf{A} + \mathbf{B} = \begin{pmatrix} a_{11} + b_{11} &amp;amp; a_{12} + b_{12} \\ a_{21} + b_{21} &amp;amp; a_{22} + b_{22} \end{pmatrix}\]

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;
\(\begin{pmatrix} 1 &amp;amp; 2 \\ 3 &amp;amp; 4 \end{pmatrix} + \begin{pmatrix} 5 &amp;amp; 6 \\ 7 &amp;amp; 8 \end{pmatrix} = \begin{pmatrix} 6 &amp;amp; 8 \\ 10 &amp;amp; 12 \end{pmatrix}\)&lt;/p&gt;

&lt;h3 id=&quot;scalar-multiplication&quot;&gt;Scalar Multiplication&lt;/h3&gt;

&lt;p&gt;Multiply every element of the matrix by the scalar:&lt;/p&gt;

\[c\mathbf{A} = \begin{pmatrix} ca_{11} &amp;amp; ca_{12} \\ ca_{21} &amp;amp; ca_{22} \end{pmatrix}\]

&lt;h3 id=&quot;matrix-multiplication&quot;&gt;Matrix Multiplication&lt;/h3&gt;

&lt;p&gt;For matrices \(\mathbf{A}_{m \times n}\) and \(\mathbf{B}_{n \times p}\), the product \(\mathbf{C}_{m \times p}\) is formed by taking the dot product of rows from \(\mathbf{A}\) and columns from \(\mathbf{B}\):&lt;/p&gt;

\[c_{ij} = \sum_{k=1}^{n} a_{ik} b_{kj}\]

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;
\(\begin{pmatrix} 1 &amp;amp; 2 \\ 3 &amp;amp; 4 \end{pmatrix} \begin{pmatrix} 5 &amp;amp; 6 \\ 7 &amp;amp; 8 \end{pmatrix} = \begin{pmatrix} 1 \cdot 5 + 2 \cdot 7 &amp;amp; 1 \cdot 6 + 2 \cdot 8 \\ 3 \cdot 5 + 4 \cdot 7 &amp;amp; 3 \cdot 6 + 4 \cdot 8 \end{pmatrix} = \begin{pmatrix} 19 &amp;amp; 22 \\ 43 &amp;amp; 50 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Important:&lt;/strong&gt; Matrix multiplication is &lt;strong&gt;not commutative&lt;/strong&gt;: \(\mathbf{AB} \neq \mathbf{BA}\) in general.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;linear-transformations&quot;&gt;Linear Transformations&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;linear transformation&lt;/strong&gt; is a function \(T: \mathbb{R}^n \to \mathbb{R}^m\) that preserves vector addition and scalar multiplication. Every linear transformation can be represented by a matrix.&lt;/p&gt;

&lt;h3 id=&quot;definition&quot;&gt;Definition&lt;/h3&gt;

&lt;p&gt;A transformation \(T(\mathbf{v}) = \mathbf{Av}\) is linear if and only if:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Additivity:&lt;/strong&gt; \(T(\mathbf{u} + \mathbf{v}) = T(\mathbf{u}) + T(\mathbf{v})\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Homogeneity:&lt;/strong&gt; \(T(c\mathbf{v}) = cT(\mathbf{v})\)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These can be combined into: \(T(c_1\mathbf{u} + c_2\mathbf{v}) = c_1T(\mathbf{u}) + c_2T(\mathbf{v})\)&lt;/p&gt;

&lt;h3 id=&quot;matrix-vector-multiplication&quot;&gt;Matrix-Vector Multiplication&lt;/h3&gt;

&lt;p&gt;If \(\mathbf{A}\) is an \(m \times n\) matrix and \(\mathbf{v}\) is an \(n \times 1\) column vector, their product \(\mathbf{Av}\) is an \(m \times 1\) column vector:&lt;/p&gt;

\[\mathbf{w} = \mathbf{Av} = \begin{pmatrix} 
a_{11}v_1 + a_{12}v_2 + \cdots + a_{1n}v_n \\
a_{21}v_1 + a_{22}v_2 + \cdots + a_{2n}v_n \\
\vdots \\
a_{m1}v_1 + a_{m2}v_2 + \cdots + a_{mn}v_n
\end{pmatrix}\]

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt;
\(\begin{pmatrix} 2 &amp;amp; 1 \\ 0 &amp;amp; 3 \end{pmatrix} \begin{pmatrix} 4 \\ 5 \end{pmatrix} = \begin{pmatrix} 2 \cdot 4 + 1 \cdot 5 \\ 0 \cdot 4 + 3 \cdot 5 \end{pmatrix} = \begin{pmatrix} 13 \\ 15 \end{pmatrix}\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;common-2d-transformations&quot;&gt;Common 2D Transformations&lt;/h2&gt;

&lt;p&gt;Understanding geometric transformations helps visualize how matrices affect vectors.&lt;/p&gt;

&lt;h3 id=&quot;scaling&quot;&gt;Scaling&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Scaling Matrix:&lt;/strong&gt;
\(\mathbf{S} = \begin{pmatrix} s_x &amp;amp; 0 \\ 0 &amp;amp; s_y \end{pmatrix}\)&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Scales x-coordinates by \(s_x\) and y-coordinates by \(s_y\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Example:&lt;/strong&gt; \(\begin{pmatrix} 2 &amp;amp; 0 \\ 0 &amp;amp; 3 \end{pmatrix}\) doubles x-values and triples y-values&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;rotation&quot;&gt;Rotation&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Rotation Matrix (counter-clockwise by angle \(\theta\)):&lt;/strong&gt;
\(\mathbf{R} = \begin{pmatrix} \cos\theta &amp;amp; -\sin\theta \\ \sin\theta &amp;amp; \cos\theta \end{pmatrix}\)&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Example:&lt;/strong&gt; 90° rotation: \(\begin{pmatrix} 0 &amp;amp; -1 \\ 1 &amp;amp; 0 \end{pmatrix}\)&lt;/li&gt;
  &lt;li&gt;Transforms \((x, y) \mapsto (-y, x)\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;reflection&quot;&gt;Reflection&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Reflection across x-axis:&lt;/strong&gt;
\(\mathbf{F}_x = \begin{pmatrix} 1 &amp;amp; 0 \\ 0 &amp;amp; -1 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reflection across y-axis:&lt;/strong&gt;
\(\mathbf{F}_y = \begin{pmatrix} -1 &amp;amp; 0 \\ 0 &amp;amp; 1 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reflection across line \(y = x\):&lt;/strong&gt;
\(\mathbf{F}_{y=x} = \begin{pmatrix} 0 &amp;amp; 1 \\ 1 &amp;amp; 0 \end{pmatrix}\)&lt;/p&gt;

&lt;h3 id=&quot;shearing&quot;&gt;Shearing&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Horizontal Shear:&lt;/strong&gt;
\(\mathbf{H} = \begin{pmatrix} 1 &amp;amp; k \\ 0 &amp;amp; 1 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;Transforms \((x, y) \mapsto (x + ky, y)\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;special-types-of-matrices&quot;&gt;Special Types of Matrices&lt;/h2&gt;

&lt;h3 id=&quot;identity-matrix&quot;&gt;Identity Matrix&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;identity matrix&lt;/strong&gt; \(\mathbf{I}\) acts like the number 1 for matrix multiplication:&lt;/p&gt;

\[\mathbf{I}_n = \begin{pmatrix} 
1 &amp;amp; 0 &amp;amp; \cdots &amp;amp; 0 \\
0 &amp;amp; 1 &amp;amp; \cdots &amp;amp; 0 \\
\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\
0 &amp;amp; 0 &amp;amp; \cdots &amp;amp; 1
\end{pmatrix}\]

&lt;p&gt;&lt;strong&gt;Property:&lt;/strong&gt; \(\mathbf{AI} = \mathbf{IA} = \mathbf{A}\) for any compatible matrix \(\mathbf{A}\).&lt;/p&gt;

&lt;h3 id=&quot;transpose&quot;&gt;Transpose&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;transpose&lt;/strong&gt; \(\mathbf{A}^T\) flips a matrix across its main diagonal:&lt;/p&gt;

\[\text{If } \mathbf{A} = \begin{pmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 4 &amp;amp; 5 &amp;amp; 6 \end{pmatrix}, \text{ then } \mathbf{A}^T = \begin{pmatrix} 1 &amp;amp; 4 \\ 2 &amp;amp; 5 \\ 3 &amp;amp; 6 \end{pmatrix}\]

&lt;p&gt;&lt;strong&gt;Properties:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[(\mathbf{A}^T)^T = \mathbf{A}\]
  &lt;/li&gt;
  &lt;li&gt;
\[(\mathbf{A} + \mathbf{B})^T = \mathbf{A}^T + \mathbf{B}^T\]
  &lt;/li&gt;
  &lt;li&gt;
\[(\mathbf{AB})^T = \mathbf{B}^T\mathbf{A}^T\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;symmetric-matrices&quot;&gt;Symmetric Matrices&lt;/h3&gt;

&lt;p&gt;A matrix is &lt;strong&gt;symmetric&lt;/strong&gt; if \(\mathbf{A} = \mathbf{A}^T\):&lt;/p&gt;

\[\mathbf{A} = \begin{pmatrix} 1 &amp;amp; 2 &amp;amp; 3 \\ 2 &amp;amp; 4 &amp;amp; 5 \\ 3 &amp;amp; 5 &amp;amp; 6 \end{pmatrix}\]

&lt;p&gt;Symmetric matrices have special properties important in deep-learning.&lt;/p&gt;

&lt;h3 id=&quot;inverse-matrix&quot;&gt;Inverse Matrix&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;inverse&lt;/strong&gt; \(\mathbf{A}^{-1}\) of a square matrix \(\mathbf{A}\) satisfies:&lt;/p&gt;

\[\mathbf{A}\mathbf{A}^{-1} = \mathbf{A}^{-1}\mathbf{A} = \mathbf{I}\]

&lt;p&gt;&lt;strong&gt;For 2×2 matrices:&lt;/strong&gt;
\(\mathbf{A}^{-1} = \frac{1}{\det(\mathbf{A})} \begin{pmatrix} d &amp;amp; -b \\ -c &amp;amp; a \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;where \(\mathbf{A} = \begin{pmatrix} a &amp;amp; b \\ c &amp;amp; d \end{pmatrix}\) and \(\det(\mathbf{A}) = ad - bc\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Not all matrices have inverses. A matrix is &lt;strong&gt;invertible&lt;/strong&gt; (non-singular) if and only if its determinant is non-zero.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;applications-in-deep-learning&quot;&gt;Applications in Deep Learning&lt;/h2&gt;

&lt;p&gt;Matrices and linear transformations are fundamental in deep-learning for several reasons:&lt;/p&gt;

&lt;h3 id=&quot;1-system-of-linear-equations&quot;&gt;1. System of Linear Equations&lt;/h3&gt;

&lt;p&gt;Many deep-learning problems involve solving \(\mathbf{Ax} = \mathbf{b}\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Unique solution:&lt;/strong&gt; \(\mathbf{x} = \mathbf{A}^{-1}\mathbf{b}\) (when \(\mathbf{A}\) is invertible)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Least squares:&lt;/strong&gt; Minimize \(\|\mathbf{Ax} - \mathbf{b}\|^2\) when no exact solution exists&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-quadratic-forms&quot;&gt;2. Quadratic Forms&lt;/h3&gt;

&lt;p&gt;Quadratic functions appear frequently in deep-learning:
\(f(\mathbf{x}) = \mathbf{x}^T\mathbf{Q}\mathbf{x} + \mathbf{c}^T\mathbf{x} + d\)&lt;/p&gt;

&lt;p&gt;The matrix \(\mathbf{Q}\) determines the curvature properties of the function.&lt;/p&gt;

&lt;h3 id=&quot;3-linear-programming&quot;&gt;3. Linear Programming&lt;/h3&gt;

&lt;p&gt;Standard form: Minimize \(\mathbf{c}^T\mathbf{x}\) subject to \(\mathbf{Ax} = \mathbf{b}\), \(\mathbf{x} \geq \mathbf{0}\)&lt;/p&gt;

&lt;h3 id=&quot;4-constraint-representation&quot;&gt;4. Constraint Representation&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Equality constraints:&lt;/strong&gt; \(\mathbf{Ax} = \mathbf{b}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Inequality constraints:&lt;/strong&gt; \(\mathbf{Ax} \leq \mathbf{b}\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;5-transformations-of-variables&quot;&gt;5. Transformations of Variables&lt;/h3&gt;

&lt;p&gt;Change of variables: \(\mathbf{y} = \mathbf{T}\mathbf{x}\) can simplify deep-learning problems.&lt;/p&gt;

&lt;h3 id=&quot;example-portfolio-deep-learning&quot;&gt;Example: Portfolio Deep Learning&lt;/h3&gt;

&lt;p&gt;In finance, we might minimize portfolio risk:
\(\text{minimize } \mathbf{w}^T\mathbf{\Sigma}\mathbf{w}\)&lt;/p&gt;

&lt;p&gt;where \(\mathbf{w}\) is the vector of portfolio weights and \(\mathbf{\Sigma}\) is the covariance matrix of asset returns.&lt;/p&gt;

&lt;p&gt;Understanding matrices and linear transformations provides the tools to formulate, analyze, and solve a wide variety of deep-learning problems efficiently.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Linear transformations and matrices&lt;/td&gt;
          &lt;td&gt;Chapter 3, Essence of linear algebra](https://www.youtube.com/watch?v=kYB8IZa5AuE) — 3Blue1Brown, English. A matrix is the linear map the lesson studies, not a grid of numbers.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Matrix multiplication as composition&lt;/td&gt;
          &lt;td&gt;Chapter 4, Essence of linear algebra](https://www.youtube.com/watch?v=XkY2DOUCWMU) — 3Blue1Brown, English. Matrix multiplication as composition is the product rule for stacking the layers this lesson describes.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Inverse matrices, column space and null space&lt;/td&gt;
          &lt;td&gt;Chapter 7, Essence of linear algebra](https://www.youtube.com/watch?v=uQhTuRlWMxw) — 3Blue1Brown, English. Inverses, column space, and null space are the special matrices and solvability facts at the end of the lesson.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-02-01 Vectors and Vector Spaces</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_02_01_Vectors_and_Vector_Spaces/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_02_01_Vectors_and_Vector_Spaces</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;In 2013, researchers stunned the NLP community by showing that subtracting the vector for “man” from “king” and adding “woman” landed right next to “queen.” That wasn’t magic—it was vector space geometry: closure under linear combinations, inner products, and low-dimensional subspaces doing their quiet work.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-vectors-subspaces-and-representation-geometry&quot;&gt;Key ideas: Vectors, Subspaces, and Representation Geometry&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Vector Spaces &amp;amp; Subspaces (Closure Under Linear Combinations)&lt;/strong&gt;: Defines the ambient space \(\mathbb{R}^n\) where feature embeddings live, and explains why the set of all outputs of a linear layer forms a structured subspace (its column space).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Inner Products, Norms, and Angles (Similarity Metrics)&lt;/strong&gt;: Measures vector length (\(L_2\) norm for weight decay, \(L_1\) norm for sparsity) and directional alignment via cosine similarity \(\cos\theta = \frac{\mathbf{u}\cdot\mathbf{v}}{\|\mathbf{u}\|\|\mathbf{v}\|}\), the core operation inside Transformer self-attention.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Linear Independence &amp;amp; Span (Redundancy vs. Expressivity)&lt;/strong&gt;: Distinguishes genuinely new feature directions from redundant linear combinations; linearly dependent neurons waste parameters without expanding the spanned subspace.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Basis &amp;amp; Dimension (Intrinsic Degrees of Freedom)&lt;/strong&gt;: Establishes the minimum number of coordinate axes needed to reconstruct every point in a subspace—the foundation of low-rank adaptation (LoRA) and manifold learning.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-testing-linear-independence-projection-and-cosine-similarity&quot;&gt;Worked example: Testing Linear Independence, Projection, and Cosine Similarity&lt;/h3&gt;

&lt;p&gt;Given two embedding vectors in \(\mathbb{R}^3\), \(\mathbf{u} = \begin{bmatrix} 1 \\ 2 \\ 2 \end{bmatrix}\) and \(\mathbf{v} = \begin{bmatrix} 2 \\ 1 \\ -2 \end{bmatrix}\), and a query vector \(\mathbf{q} = \begin{bmatrix} 4 \\ 5 \\ 2 \end{bmatrix}\):&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Norms and Dot Product of \(\mathbf{u}\) and \(\mathbf{v}\)&lt;/strong&gt;:
\(\|\mathbf{u}\| = \sqrt{1^2 + 2^2 + 2^2} = \sqrt{9} = 3, \qquad \|\mathbf{v}\| = \sqrt{2^2 + 1^2 + (-2)^2} = \sqrt{9} = 3\)
\(\mathbf{u} \cdot \mathbf{v} = (1)(2) + (2)(1) + (2)(-2) = 2 + 2 - 4 = 0\)
Because \(\mathbf{u} \cdot \mathbf{v} = 0\) and both are nonzero, \(\mathbf{u}\) and \(\mathbf{v}\) are &lt;strong&gt;orthogonal&lt;/strong&gt; and therefore linearly independent!&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Project \(\mathbf{q}\) Onto the 2D Subspace \(\text{span}\{\mathbf{u}, \mathbf{v}\}\)&lt;/strong&gt;:
Since \(\mathbf{u} \perp \mathbf{v}\), the orthogonal projection splits cleanly:
\(\mathbf{q}\cdot\mathbf{u} = 4(1) + 5(2) + 2(2) = 18 \implies c_1 = \frac{\mathbf{q}\cdot\mathbf{u}}{\|\mathbf{u}\|^2} = \frac{18}{9} = 2\)
\(\mathbf{q}\cdot\mathbf{v} = 4(2) + 5(1) + 2(-2) = 9 \implies c_2 = \frac{\mathbf{q}\cdot\mathbf{v}}{\|\mathbf{v}\|^2} = \frac{9}{9} = 1\)
\(\text{proj}_S(\mathbf{q}) = 2\mathbf{u} + 1\mathbf{v} = \begin{bmatrix} 2 \\ 4 \\ 4 \end{bmatrix} + \begin{bmatrix} 2 \\ 1 \\ -2 \end{bmatrix} = \begin{bmatrix} 4 \\ 5 \\ 2 \end{bmatrix} = \mathbf{q}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Geometric Conclusion&lt;/strong&gt;:
The residual \(\mathbf{q} - \text{proj}_S(\mathbf{q}) = \mathbf{0}\), proving \(\mathbf{q}\) lies strictly inside \(\text{span}\{\mathbf{u}, \mathbf{v}\}\). Thus \(\{\mathbf{u}, \mathbf{v}, \mathbf{q}\}\) is linearly dependent and spans only a 2D plane inside \(\mathbb{R}^3\).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson introduces vectors, vector spaces, and fundamental concepts that form the foundation for understanding linear algebra in deep-learning contexts.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;vectors-and-vector-spaces-mathbbrn&quot;&gt;Vectors and Vector Spaces (\(\mathbb{R}^n\))&lt;/h2&gt;

&lt;h3 id=&quot;what-is-a-vector&quot;&gt;What is a Vector?&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vectors:&lt;/strong&gt; Think of a vector as an arrow in space, representing both a direction and a magnitude (length). Mathematically, it’s an ordered list of numbers, like coordinates. For example, a vector in 2D space could be \(\mathbf{v} = \begin{pmatrix} 3 \\ 4 \end{pmatrix}\), meaning 3 units along the x-axis and 4 units along the y-axis.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Geometric vs Algebraic View:&lt;/strong&gt;&lt;/p&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Geometric:&lt;/strong&gt; Vectors are arrows with direction and magnitude&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Algebraic:&lt;/strong&gt; Vectors are ordered lists of real numbers&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;vector-spaces&quot;&gt;Vector Spaces&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Vector Space (\(\mathbb{R}^n\)):&lt;/strong&gt; This is the collection of all possible vectors that have \(n\) components (numbers). For instance, \(\mathbb{R}^2\) includes all 2-component vectors, representing all points or arrows in a 2D plane.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
    &lt;ul&gt;
      &lt;li&gt;\(\mathbb{R}^2 = \left\{\begin{pmatrix} x \\ y \end{pmatrix} : x, y \in \mathbb{R}\right\}\) (the plane)&lt;/li&gt;
      &lt;li&gt;\(\mathbb{R}^3 = \left\{\begin{pmatrix} x \\ y \\ z \end{pmatrix} : x, y, z \in \mathbb{R}\right\}\) (3D space)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;vector-operations&quot;&gt;Vector Operations&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Vector Addition:&lt;/strong&gt;
\(\mathbf{u} + \mathbf{v} = \begin{pmatrix} u_1 \\ u_2 \\ \vdots \\ u_n \end{pmatrix} + \begin{pmatrix} v_1 \\ v_2 \\ \vdots \\ v_n \end{pmatrix} = \begin{pmatrix} u_1 + v_1 \\ u_2 + v_2 \\ \vdots \\ u_n + v_n \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Scalar Multiplication:&lt;/strong&gt;
\(c\mathbf{v} = c \begin{pmatrix} v_1 \\ v_2 \\ \vdots \\ v_n \end{pmatrix} = \begin{pmatrix} cv_1 \\ cv_2 \\ \vdots \\ cv_n \end{pmatrix}\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;linear-independence-basis-and-dimension&quot;&gt;Linear Independence, Basis, and Dimension&lt;/h2&gt;

&lt;h3 id=&quot;linear-independence&quot;&gt;Linear Independence&lt;/h3&gt;

&lt;p&gt;A set of vectors \(\{\mathbf{v}_1, \mathbf{v}_2, \ldots, \mathbf{v}_k\}\) is &lt;strong&gt;linearly independent&lt;/strong&gt; if the only solution to:&lt;/p&gt;

\[c_1\mathbf{v}_1 + c_2\mathbf{v}_2 + \cdots + c_k\mathbf{v}_k = \mathbf{0}\]

&lt;p&gt;is \(c_1 = c_2 = \cdots = c_k = 0\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Intuitive Understanding:&lt;/strong&gt; A set of vectors is “linearly independent” if no vector in the set can be created by scaling and adding the other vectors in the set. They all point in “different enough” directions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example in \(\mathbb{R}^2\):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(\mathbf{v}_1 = \begin{pmatrix} 1 \\ 0 \end{pmatrix}\) and \(\mathbf{v}_2 = \begin{pmatrix} 0 \\ 1 \end{pmatrix}\) are linearly independent&lt;/li&gt;
  &lt;li&gt;\(\mathbf{v}_1 = \begin{pmatrix} 1 \\ 2 \end{pmatrix}\) and \(\mathbf{v}_2 = \begin{pmatrix} 2 \\ 4 \end{pmatrix}\) are linearly dependent (since \(\mathbf{v}_2 = 2\mathbf{v}_1\))&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;basis&quot;&gt;Basis&lt;/h3&gt;

&lt;p&gt;A &lt;strong&gt;basis&lt;/strong&gt; for a vector space is a minimal set of linearly independent vectors that can be combined (scaled and added) to create &lt;em&gt;any&lt;/em&gt; other vector in that space. It’s like a fundamental set of building blocks.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Properties of a Basis:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;The vectors are linearly independent&lt;/li&gt;
  &lt;li&gt;They span the entire vector space&lt;/li&gt;
  &lt;li&gt;Every vector in the space can be written uniquely as a linear combination of basis vectors&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Standard Basis for \(\mathbb{R}^n\):&lt;/strong&gt;
\(\mathbf{e}_1 = \begin{pmatrix} 1 \\ 0 \\ \vdots \\ 0 \end{pmatrix}, \mathbf{e}_2 = \begin{pmatrix} 0 \\ 1 \\ \vdots \\ 0 \end{pmatrix}, \ldots, \mathbf{e}_n = \begin{pmatrix} 0 \\ 0 \\ \vdots \\ 1 \end{pmatrix}\)&lt;/p&gt;

&lt;h3 id=&quot;dimension&quot;&gt;Dimension&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;dimension&lt;/strong&gt; of a vector space is simply the number of vectors in any of its bases. It tells you how many independent directions are needed to describe the space.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
\[\dim(\mathbb{R}^2) = 2\]
  &lt;/li&gt;
  &lt;li&gt;
\[\dim(\mathbb{R}^3) = 3\]
  &lt;/li&gt;
  &lt;li&gt;
\[\dim(\mathbb{R}^n) = n\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;norms-of-vectors&quot;&gt;Norms of Vectors&lt;/h2&gt;

&lt;p&gt;A &lt;strong&gt;norm&lt;/strong&gt; is a function that assigns a “length” or “size” to a vector. It generalizes the concept of distance from the origin.&lt;/p&gt;

&lt;h3 id=&quot;properties-of-norms&quot;&gt;Properties of Norms&lt;/h3&gt;

&lt;p&gt;Any norm \(\|\cdot\|\) must satisfy three properties:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Non-negativity:&lt;/strong&gt; \(\|\mathbf{x}\| \geq 0\), and \(\|\mathbf{x}\| = 0\) if and only if \(\mathbf{x} = \mathbf{0}\)&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;Homogeneity:&lt;/strong&gt; $$|t\mathbf{x}| =&lt;/td&gt;
          &lt;td&gt;t&lt;/td&gt;
          &lt;td&gt;|\mathbf{x}|\(for any scalar\)t$$&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Triangle Inequality:&lt;/strong&gt; \(\|\mathbf{x} + \mathbf{y}\| \leq \|\mathbf{x}\| + \|\mathbf{y}\|\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;common-norms&quot;&gt;Common Norms&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Euclidean Norm (L2 Norm):&lt;/strong&gt;
\(\|\mathbf{x}\|_2 = \sqrt{\sum_{i=1}^n x_i^2} = \sqrt{x_1^2 + x_2^2 + \cdots + x_n^2}\)&lt;/p&gt;

&lt;p&gt;This is the “ordinary” distance we’re familiar with.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Manhattan Norm (L1 Norm):&lt;/strong&gt;
\(\|\mathbf{x}\|_1 = \sum_{i=1}^n |x_i| = |x_1| + |x_2| + \cdots + |x_n|\)&lt;/p&gt;

&lt;p&gt;Also called “taxicab norm” - the distance a taxi would travel in a city with a grid layout.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Maximum Norm (L∞ Norm):&lt;/strong&gt;
\(\|\mathbf{x}\|_\infty = \max_{i} |x_i|\)&lt;/p&gt;

&lt;p&gt;The largest component in absolute value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Example:&lt;/strong&gt; For \(\mathbf{x} = \begin{pmatrix} 3 \\ -4 \\ 1 \end{pmatrix}\):&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;
\[\|\mathbf{x}\|_2 = \sqrt{3^2 + (-4)^2 + 1^2} = \sqrt{26} \approx 5.1\]
  &lt;/li&gt;
  &lt;li&gt;
\[\|\mathbf{x}\|_1 = |3| + |-4| + |1| = 8\]
  &lt;/li&gt;
  &lt;li&gt;
\[\|\mathbf{x}\|_\infty = \max\{|3|, |-4|, |1|\} = 4\]
  &lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;inner-products-dot-product&quot;&gt;Inner Products (Dot Product)&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;dot product&lt;/strong&gt; (or inner product) is the most common way to multiply two vectors, producing a scalar result.&lt;/p&gt;

&lt;h3 id=&quot;definition&quot;&gt;Definition&lt;/h3&gt;

&lt;p&gt;For two vectors \(\mathbf{x}\) and \(\mathbf{y}\) in \(\mathbb{R}^n\):&lt;/p&gt;

\[\mathbf{x}^T \mathbf{y} = \mathbf{x} \cdot \mathbf{y} = \sum_{i=1}^n x_i y_i = x_1 y_1 + x_2 y_2 + \cdots + x_n y_n\]

&lt;h3 id=&quot;geometric-interpretation&quot;&gt;Geometric Interpretation&lt;/h3&gt;

\[\mathbf{x} \cdot \mathbf{y} = \|\mathbf{x}\| \|\mathbf{y}\| \cos \theta\]

&lt;p&gt;where \(\theta\) is the angle between the vectors.&lt;/p&gt;

&lt;h3 id=&quot;properties&quot;&gt;Properties&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Commutative:&lt;/strong&gt; \(\mathbf{x} \cdot \mathbf{y} = \mathbf{y} \cdot \mathbf{x}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Distributive:&lt;/strong&gt; \(\mathbf{x} \cdot (\mathbf{y} + \mathbf{z}) = \mathbf{x} \cdot \mathbf{y} + \mathbf{x} \cdot \mathbf{z}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Homogeneous:&lt;/strong&gt; \((c\mathbf{x}) \cdot \mathbf{y} = c(\mathbf{x} \cdot \mathbf{y})\)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;special-cases&quot;&gt;Special Cases&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Orthogonal vectors:&lt;/strong&gt; \(\mathbf{x} \cdot \mathbf{y} = 0\) (perpendicular)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Parallel vectors:&lt;/strong&gt; \(\mathbf{x} \cdot \mathbf{y} = \pm \|\mathbf{x}\| \|\mathbf{y}\|\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Self dot product:&lt;/strong&gt; \(\mathbf{x} \cdot \mathbf{x} = \|\mathbf{x}\|_2^2\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;example&quot;&gt;Example&lt;/h3&gt;

&lt;p&gt;For \(\mathbf{x} = \begin{pmatrix} 1 \\ 2 \end{pmatrix}\) and \(\mathbf{y} = \begin{pmatrix} 3 \\ 4 \end{pmatrix}\):&lt;/p&gt;

\[\mathbf{x}^T \mathbf{y} = (1)(3) + (2)(4) = 3 + 8 = 11\]

&lt;hr /&gt;

&lt;h2 id=&quot;applications-in-deep-learning&quot;&gt;Applications in Deep Learning&lt;/h2&gt;

&lt;p&gt;Understanding vectors and vector spaces is crucial for deep-learning because:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Decision Variables:&lt;/strong&gt; Deep Learning problems often involve finding the best values for multiple variables, naturally represented as vectors.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Gradients:&lt;/strong&gt; The gradient of a function is a vector pointing in the direction of steepest increase.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Constraints:&lt;/strong&gt; Linear constraints in deep-learning can be expressed using dot products: \(\mathbf{a}^T \mathbf{x} \leq b\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Distance and Similarity:&lt;/strong&gt; Different norms provide different ways to measure distances between solutions or the size of changes.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Orthogonality:&lt;/strong&gt; Many deep-learning concepts rely on perpendicularity, such as the relationship between gradients and level curves.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Linear Combinations:&lt;/strong&gt; Feasible regions are often defined as linear combinations of vectors (convex hulls, cones, etc.).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The vector space framework provides the mathematical foundation for formulating and solving deep-learning problems systematically.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Vectors&lt;/td&gt;
          &lt;td&gt;Chapter 1, Essence of linear algebra](https://www.youtube.com/watch?v=fNk_zzaMoSs) — 3Blue1Brown, English. What a vector is, before span, basis, and dimension.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Linear combinations, span, and basis vectors&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of linear algebra](https://www.youtube.com/watch?v=k7RM-ot2NWY) — 3Blue1Brown, English. Linear combinations, span, and basis are the independence and dimension section of this lesson.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Dot products and duality&lt;/td&gt;
          &lt;td&gt;Chapter 9, Essence of linear algebra](https://www.youtube.com/watch?v=LyGKycYT2v0) — 3Blue1Brown, English. The dot product here is the inner product in the lesson; the Euclidean norm is the length it induces.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01 Calculus</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_01_Calculus/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_01_Calculus</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;In 1687, Isaac Newton used calculus to predict the orbits of planets; three and a half centuries later, we use the exact same differential machinery to steer parameter vectors through billion-dimensional loss valleys. Calculus is what turns a static neural network into a system capable of self-correction.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-four-pillars-of-calculus-for-deep-learning&quot;&gt;Key ideas: Four Pillars of Calculus for Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Continuity &amp;amp; Lipschitz Smoothness&lt;/strong&gt;: Ensures that tiny changes in network weights produce bounded, predictable changes in outputs and gradients, preventing catastrophic jumps during training.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Derivatives &amp;amp; Multivariable Calculus&lt;/strong&gt;: Generalizes scalar slopes to partial derivatives, Jacobians, and Hessians, letting us track how every weight in a deep graph contributes to the final scalar loss.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradients &amp;amp; Directional Derivatives&lt;/strong&gt;: Identifies the exact direction of steepest ascent in parameter space, proving mathematically why stepping opposite the gradient locally decreases the objective fastest.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Taylor Series Approximations&lt;/strong&gt;: Approximates complex non-convex loss landscapes locally by hyperplanes (first-order SGD) and quadratics (second-order Newton and Adam-style curvature preconditioning).&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-from-local-linear-approximation-to-curvature-control&quot;&gt;Worked example: From Local Linear Approximation to Curvature Control&lt;/h3&gt;

&lt;p&gt;Consider the smooth scalar loss \(L(w) = w^3 - 6w^2 + 12w + 1\) evaluated near \(w_0 = 1\). Let us see how continuity, derivatives, and Taylor expansion work together to predict the effect of a step \(\Delta w = 0.5\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate the Function and Derivatives at \(w_0 = 1\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Value: \(L(1) = 1 - 6 + 12 + 1 = 8\).&lt;/li&gt;
      &lt;li&gt;First derivative (slope): \(L&apos;(w) = 3w^2 - 12w + 12 \implies L&apos;(1) = 3 - 12 + 12 = 3\).&lt;/li&gt;
      &lt;li&gt;Second derivative (curvature): \(L&apos;&apos;(w) = 6w - 12 \implies L&apos;&apos;(1) = 6 - 12 = -6\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;First-Order (Tangent Line) Prediction for \(w_1 = 1.5\)&lt;/strong&gt;:
\(L_{\text{lin}}(1.5) = L(1) + L&apos;(1)\Delta w = 8 + 3(0.5) = 9.5\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Second-Order (Quadratic Taylor) Prediction for \(w_1 = 1.5\)&lt;/strong&gt;:
\(L_{\text{quad}}(1.5) = L(1) + L&apos;(1)\Delta w + \frac{1}{2}L&apos;&apos;(1)(\Delta w)^2 = 8 + 1.5 + \frac{1}{2}(-6)(0.25) = 9.5 - 0.75 = 8.75\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Exact Value Check&lt;/strong&gt;:
\(L(1.5) = (1.5)^3 - 6(1.5)^2 + 12(1.5) + 1 = 3.375 - 13.5 + 18 + 1 = 8.875\)
The linear model errs by \(0.625\) because it ignores negative curvature, while the quadratic model slashes the error fivefold to \(0.125\)—precisely the geometric reason step sizes must respect local curvature.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers essential calculus concepts needed for deep-learning, organized into four main sections for better understanding.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;xem trước&lt;/strong&gt; &lt;a href=&quot;https://www.youtube.com/watch?v=WUvTyaaNkzM&quot;&gt;The essence of calculus&lt;/a&gt; — 3Blue1Brown, English. The single idea of a derivative as local linear change, which the four calculus lessons then split apart.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[The paradox of the derivative&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of calculus](https://www.youtube.com/watch?v=9vKqVkMQHKk) — 3Blue1Brown, English. The formal derivative this overview points at is built carefully here, including why the limit definition is subtle.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YNYwUWH-04w&quot;&gt;MaDL - Differential Calculus&lt;/a&gt; — Tübingen Machine Learning, English. A short DL-oriented pass over differentials, closer to how the course uses calculus than a full calculus sequence.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01-04 Taylor Series</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_01_04_Taylor_Series/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_01_04_Taylor_Series</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Deep neural networks define wildly tangled, non-convex functions that no human can solve in closed form. Yet optimization succeeds because, if you zoom in close enough around your current weights, every smooth function looks like a flat plane (first-order Taylor) or a simple quadratic bowl (second-order Taylor).&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-local-polynomial-approximations-in-deep-learning&quot;&gt;Key ideas: Local Polynomial Approximations in Deep Learning&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;First-Order Taylor Expansion (Linearization)&lt;/strong&gt;: Approximates \(f(\mathbf{x} + \boldsymbol{\delta}) \approx f(\mathbf{x}) + \nabla f(\mathbf{x})^\top \boldsymbol{\delta}\), which is the exact derivation behind standard gradient descent and linearized neural tangent kernel (NTK) theory.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Second-Order Taylor Expansion (Quadratic Modeling)&lt;/strong&gt;: Adds the curvature term \(\frac{1}{2}\boldsymbol{\delta}^\top H_f(\mathbf{x})\boldsymbol{\delta}\), yielding Newton’s step \(\boldsymbol{\delta}^* = -H^{-1}\nabla f\) and the smoothness descent lemma that bounds safe learning rates.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Remainder Term &amp;amp; Trust Region&lt;/strong&gt;: Quantifies the approximation error \(R_n(\boldsymbol{\delta}) = O(\|\boldsymbol{\delta}\|^{n+1})\), explaining why overly large learning rates break the local quadratic model and cause loss divergence.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Canonical Maclaurin Series (Activation &amp;amp; Stability Tools)&lt;/strong&gt;: Expansions of \(e^x\), \(\ln(1+x)\), and \(\sigma(x)\) around \(0\) allow engineers to derive numerically stable softmax/log-sum-exp tricks and analyze initialization dynamics near zero.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-second-order-taylor-expansion-of-the-softplus-loss&quot;&gt;Worked example: Second-Order Taylor Expansion of the Softplus Loss&lt;/h3&gt;

&lt;p&gt;Consider the smooth surrogate for ReLU, the softplus function \(f(x) = \ln(1 + e^x)\), expanded around \(x_0 = 0\) to approximate \(f(0.4)\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute Derivatives at \(x_0 = 0\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Value: \(f(0) = \ln(1 + e^0) = \ln 2 \approx 0.69315\).&lt;/li&gt;
      &lt;li&gt;First derivative (the sigmoid function!):
\(f&apos;(x) = \frac{e^x}{1 + e^x} = \sigma(x) \implies f&apos;(0) = \frac{1}{2} = 0.5\)&lt;/li&gt;
      &lt;li&gt;Second derivative:
\(f&apos;&apos;(x) = \sigma(x)(1 - \sigma(x)) \implies f&apos;&apos;(0) = 0.5 \times 0.5 = 0.25\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Construct the Linear (\(T_1\)) and Quadratic (\(T_2\)) Approximations&lt;/strong&gt;:
\(T_1(x) = \ln 2 + 0.5 x\)
\(T_2(x) = \ln 2 + 0.5 x + \frac{0.25}{2} x^2 = \ln 2 + 0.5 x + 0.125 x^2\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Evaluate at \(x = 0.4\) (where \(x^2 = 0.16\))&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Linear: \(T_1(0.4) = 0.69315 + 0.5(0.4) = 0.89315\).&lt;/li&gt;
      &lt;li&gt;Quadratic: \(T_2(0.4) = 0.89315 + 0.125(0.16) = 0.89315 + 0.02000 = 0.91315\).&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare Against Exact Value&lt;/strong&gt;:
\(f(0.4) = \ln(1 + e^{0.4}) \approx \ln(1 + 1.49182) = \ln(2.49182) \approx 0.91301\)
The linear error is \(0.01986\), whereas the quadratic Taylor polynomial matches to four decimal places (error \(0.00014\)—a \(140\times\) improvement!).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers Taylor series expansions, which are fundamental for approximating functions and understanding the local behavior of functions in deep-learning algorithms.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;taylor-series-definition&quot;&gt;Taylor Series Definition&lt;/h2&gt;

&lt;p&gt;The Taylor series is a representation of a function as an infinite sum of terms calculated from the values of the function’s derivatives at a single point. It provides a way to approximate complex functions using polynomials.&lt;/p&gt;

&lt;h3 id=&quot;single-variable-taylor-series&quot;&gt;Single Variable Taylor Series&lt;/h3&gt;

&lt;p&gt;A Taylor series is a series expansion of a function \(f(x)\) about a point \(a\):&lt;/p&gt;

\[f(x) = \sum_{n=0}^{\infty} \frac{f^{(n)}(a)}{n!}(x-a)^n\]

&lt;p&gt;In expanded form:&lt;/p&gt;

\[f(x) = f(a) + \frac{f&apos;(a)}{1!}(x-a) + \frac{f&apos;&apos;(a)}{2!}(x-a)^2 + \frac{f&apos;&apos;&apos;(a)}{3!}(x-a)^3 + \dots\]

&lt;h3 id=&quot;maclaurin-series&quot;&gt;Maclaurin Series&lt;/h3&gt;

&lt;p&gt;When the expansion is around \(a = 0\), the Taylor series is called a &lt;strong&gt;Maclaurin series&lt;/strong&gt;:&lt;/p&gt;

\[f(x) = f(0) + f&apos;(0)x + \frac{f&apos;&apos;(0)}{2!}x^2 + \frac{f&apos;&apos;&apos;(0)}{3!}x^3 + \dots\]

&lt;h3 id=&quot;common-maclaurin-series&quot;&gt;Common Maclaurin Series&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Exponential Function:&lt;/strong&gt;
\(e^x = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \dots = \sum_{n=0}^{\infty} \frac{x^n}{n!}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Sine Function:&lt;/strong&gt;
\(\sin x = x - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + \dots = \sum_{n=0}^{\infty} \frac{(-1)^n x^{2n+1}}{(2n+1)!}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Cosine Function:&lt;/strong&gt;
\(\cos x = 1 - \frac{x^2}{2!} + \frac{x^4}{4!} - \frac{x^6}{6!} + \dots = \sum_{n=0}^{\infty} \frac{(-1)^n x^{2n}}{(2n)!}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Natural Logarithm (for \(|x| &amp;lt; 1\)):&lt;/strong&gt;
\(\ln(1 + x) = x - \frac{x^2}{2} + \frac{x^3}{3} - \frac{x^4}{4} + \dots = \sum_{n=1}^{\infty} \frac{(-1)^{n+1} x^n}{n}\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;multivariable-taylor-series&quot;&gt;Multivariable Taylor Series&lt;/h2&gt;

&lt;p&gt;For functions of multiple variables, Taylor series become more complex but follow similar principles. The expansion around a point \(\mathbf{x}_0\) involves partial derivatives.&lt;/p&gt;

&lt;h3 id=&quot;first-order-taylor-expansion&quot;&gt;First-Order Taylor Expansion&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;linear approximation&lt;/strong&gt; of \(f(\mathbf{x})\) around \(\mathbf{x}_0\):&lt;/p&gt;

\[f(\mathbf{x}) \approx f(\mathbf{x}_0) + \nabla f(\mathbf{x}_0)^T (\mathbf{x} - \mathbf{x}_0)\]

&lt;p&gt;This is the equation of the tangent plane to the function at \(\mathbf{x}_0\).&lt;/p&gt;

&lt;h3 id=&quot;second-order-taylor-expansion&quot;&gt;Second-Order Taylor Expansion&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;quadratic approximation&lt;/strong&gt; includes curvature information:&lt;/p&gt;

\[f(\mathbf{x}) \approx f(\mathbf{x}_0) + \nabla f(\mathbf{x}_0)^T (\mathbf{x} - \mathbf{x}_0) + \frac{1}{2} (\mathbf{x} - \mathbf{x}_0)^T \nabla^2 f(\mathbf{x}_0) (\mathbf{x} - \mathbf{x}_0)\]

&lt;p&gt;where \(\nabla^2 f(\mathbf{x}_0)\) is the Hessian matrix at \(\mathbf{x}_0\).&lt;/p&gt;

&lt;h3 id=&quot;general-form&quot;&gt;General Form&lt;/h3&gt;

&lt;p&gt;The complete multivariable Taylor series involves higher-order tensors:&lt;/p&gt;

\[f(\mathbf{x}) = \sum_{|\alpha|=0}^{\infty} \frac{D^{\alpha} f(\mathbf{x}_0)}{\alpha!} (\mathbf{x} - \mathbf{x}_0)^{\alpha}\]

&lt;p&gt;where \(\alpha = (\alpha_1, \alpha_2, \ldots, \alpha_n)\) is a multi-index.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;applications-in-deep-learning&quot;&gt;Applications in Deep Learning&lt;/h2&gt;

&lt;p&gt;Taylor series are fundamental to deep-learning theory and algorithms for several reasons:&lt;/p&gt;

&lt;h3 id=&quot;1-local-function-approximation&quot;&gt;1. Local Function Approximation&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Linear Approximation (First-Order Methods):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Used in gradient descent algorithms&lt;/li&gt;
  &lt;li&gt;Assumes the function is approximately linear in a small neighborhood&lt;/li&gt;
  &lt;li&gt;Step size must be small enough for the approximation to be valid&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Quadratic Approximation (Second-Order Methods):&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Used in Newton’s method and quasi-Newton methods&lt;/li&gt;
  &lt;li&gt;Captures curvature information through the Hessian&lt;/li&gt;
  &lt;li&gt;Often provides faster convergence than first-order methods&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;2-optimality-conditions&quot;&gt;2. Optimality Conditions&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;First-Order Necessary Condition:&lt;/strong&gt;
At a local minimum \(\mathbf{x}^*\), we must have \(\nabla f(\mathbf{x}^*) = \mathbf{0}\).&lt;/p&gt;

&lt;p&gt;This comes from the first-order Taylor expansion: if \(\nabla f(\mathbf{x}^*) \neq \mathbf{0}\), we could move in the direction \(-\nabla f(\mathbf{x}^*)\) to decrease the function value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Second-Order Sufficient Condition:&lt;/strong&gt;
If \(\nabla f(\mathbf{x}^*) = \mathbf{0}\) and \(\nabla^2 f(\mathbf{x}^*)\) is positive definite, then \(\mathbf{x}^*\) is a local minimum.&lt;/p&gt;

&lt;p&gt;This follows from the second-order Taylor expansion: the quadratic term dominates near \(\mathbf{x}^*\).&lt;/p&gt;

&lt;h3 id=&quot;3-algorithm-design&quot;&gt;3. Algorithm Design&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Newton’s Method:&lt;/strong&gt;
Uses the second-order Taylor approximation to find the minimum of the quadratic model:&lt;/p&gt;

\[\mathbf{x}_{k+1} = \mathbf{x}_k - [\nabla^2 f(\mathbf{x}_k)]^{-1} \nabla f(\mathbf{x}_k)\]

&lt;p&gt;&lt;strong&gt;Trust Region Methods:&lt;/strong&gt;
Use Taylor approximations within a trusted region where the approximation is believed to be accurate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Line Search Methods:&lt;/strong&gt;
Use Taylor expansions to determine appropriate step sizes along search directions.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;example-quadratic-function-analysis&quot;&gt;Example: Quadratic Function Analysis&lt;/h2&gt;

&lt;p&gt;Consider \(f(x, y) = x^2 + 2xy + 3y^2\) around the point \((0, 0)\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Gradient:&lt;/strong&gt;
\(\nabla f = \begin{pmatrix} 2x + 2y \\ 2x + 6y \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;At \((0, 0)\): \(\nabla f(0, 0) = \begin{pmatrix} 0 \\ 0 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Hessian:&lt;/strong&gt;
\(\nabla^2 f = \begin{pmatrix} 2 &amp;amp; 2 \\ 2 &amp;amp; 6 \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Second-Order Taylor Expansion around \((0, 0)\):&lt;/strong&gt;
\(f(x, y) \approx f(0, 0) + 0 + \frac{1}{2} \begin{pmatrix} x &amp;amp; y \end{pmatrix} \begin{pmatrix} 2 &amp;amp; 2 \\ 2 &amp;amp; 6 \end{pmatrix} \begin{pmatrix} x \\ y \end{pmatrix}\)&lt;/p&gt;

\[= 0 + \frac{1}{2}(2x^2 + 4xy + 6y^2) = x^2 + 2xy + 3y^2\]

&lt;p&gt;In this case, the function is exactly quadratic, so the second-order Taylor expansion is exact.&lt;/p&gt;

&lt;p&gt;Since the Hessian has eigenvalues \(\lambda_1 = 2 + 2\sqrt{2} &amp;gt; 0\) and \(\lambda_2 = 2 - 2\sqrt{2} &amp;lt; 0\), the point \((0, 0)\) is a saddle point, not a minimum.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;practical-considerations&quot;&gt;Practical Considerations&lt;/h2&gt;

&lt;h3 id=&quot;convergence-and-accuracy&quot;&gt;Convergence and Accuracy&lt;/h3&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Radius of Convergence&lt;/strong&gt;: Taylor series only converge within a certain radius from the expansion point&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Truncation Error&lt;/strong&gt;: Using finite terms introduces approximation errors&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Computational Cost&lt;/strong&gt;: Higher-order terms require more derivative computations&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;deep-learning-algorithm-choice&quot;&gt;Deep Learning Algorithm Choice&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;First-order methods&lt;/strong&gt; (gradient descent): Use only gradient information, slower but cheaper per iteration&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Second-order methods&lt;/strong&gt; (Newton): Use Hessian information, faster convergence but expensive per iteration&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Quasi-Newton methods&lt;/strong&gt;: Approximate the Hessian, balancing speed and computational cost&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The Taylor series expansion helps us approximate complex functions with simpler polynomial functions around a specific point, which is vital for deep-learning algorithms and understanding local behavior of functions.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Taylor series&lt;/td&gt;
          &lt;td&gt;Chapter 11, Essence of calculus](https://www.youtube.com/watch?v=3d6DsjIBzJ4) — 3Blue1Brown, English. The Taylor polynomial is the local approximation the lesson defines, including the quadratic term deep learning actually uses.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=YNYwUWH-04w&quot;&gt;MaDL - Differential Calculus&lt;/a&gt; — Tübingen Machine Learning, English. The first-order term in that expansion is the differential this short lecture computes.&lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=wH-mvAPIlT8&quot;&gt;MaDL - The Argmin and Argmax Operators&lt;/a&gt; — Tübingen Machine Learning, English. Argmin of a local quadratic model is how the lesson turns a Taylor expansion into an optimization step.&lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01-03 Gradient and Directional Derivatives</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_01_03_Gradient_and_Directional_Derivatives/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_01_03_Gradient_and_Directional_Derivatives</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Picture yourself blindfolded on a foggy mountain ridge trying to descend as fast as possible with only a spirit level under your boots. You cannot see the valley floor, yet one local measurement—the gradient—points directly uphill, and its opposite points straight down the steepest local slope.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-geometry-of-gradients-and-steepest-descent&quot;&gt;Key ideas: Geometry of Gradients and Steepest Descent&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Directional Derivative (Probing Any Direction)&lt;/strong&gt;: Measures the instantaneous rate of change of \(f\) along a chosen unit vector \(\mathbf{u}\) via the dot product \(D_{\mathbf{u}} f(\mathbf{x}) = \nabla f(\mathbf{x}) \cdot \mathbf{u}\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Cauchy–Schwarz Optimality (Why \(-\nabla f\) Wins)&lt;/strong&gt;: Since \(\nabla f \cdot \mathbf{u} = \|\nabla f\| \|\mathbf{u}\| \cos\theta = \|\nabla f\|\cos\theta\), ascent is maximized at \(\theta = 0\) (\(\mathbf{u} = \nabla f / \|\nabla f\|\)) and descent is maximized at \(\theta = \pi\) (\(\mathbf{u} = -\nabla f / \|\nabla f\|\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Orthogonality to Level Sets&lt;/strong&gt;: Every tangent vector along a contour curve \(f(\mathbf{x}) = c\) has directional derivative \(0\), proving that \(\nabla f\) is always perpendicular to the level contours.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Anisotropic Conditioning (Why Gradients Zig-Zag)&lt;/strong&gt;: In elongated elliptical valleys, the negative gradient points perpendicular to the contour—toward the steep canyon wall rather than straight to the minimum—motivating momentum and adaptive optimizers.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-computing-directional-derivatives-on-an-elliptical-loss-bowl&quot;&gt;Worked example: Computing Directional Derivatives on an Elliptical Loss Bowl&lt;/h3&gt;

&lt;p&gt;Consider the anisotropic quadratic loss \(f(x, y) = x^2 + 4y^2\) at the point \(\mathbf{p} = (2, 1)\), where \(f(2, 1) = 4 + 4 = 8\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Gradient at \(\mathbf{p} = (2, 1)\)&lt;/strong&gt;:
\(\nabla f(x, y) = \begin{bmatrix} 2x \\ 8y \end{bmatrix} \implies \nabla f(2, 1) = \begin{bmatrix} 4 \\ 8 \end{bmatrix}\)
Its Euclidean norm is \(\|\nabla f(2, 1)\| = \sqrt{4^2 + 8^2} = \sqrt{80} = 4\sqrt{5} \approx 8.944\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Directional Derivative Along an Arbitrary Vector \(\mathbf{v} = (3, -4)\)&lt;/strong&gt;:
First normalize \(\mathbf{v}\) to a unit vector (never skip normalization!):
\(\|\mathbf{v}\| = \sqrt{3^2 + (-4)^2} = 5 \implies \mathbf{u} = \begin{bmatrix} 3/5 \\ -4/5 \end{bmatrix} = \begin{bmatrix} 0.6 \\ -0.8 \end{bmatrix}\)
Now take the dot product:
\(D_{\mathbf{u}} f(2, 1) = \nabla f(2, 1) \cdot \mathbf{u} = (4)(0.6) + (8)(-0.8) = 2.4 - 6.4 = -4.0\)
Because \(D_{\mathbf{u}} f &amp;lt; 0\), moving in direction \(\mathbf{u}\) decreases the loss at an initial rate of \(4.0\) units per unit step.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compare with the Steepest Descent Direction&lt;/strong&gt;:
The unit steepest descent vector is \(\mathbf{u}^* = -\frac{\nabla f}{\|\nabla f\|} = \begin{bmatrix} -1/\sqrt{5} \\ -2/\sqrt{5} \end{bmatrix} \approx \begin{bmatrix} -0.447 \\ -0.894 \end{bmatrix}\), giving:
\(D_{\mathbf{u}^*} f(2, 1) = -\|\nabla f(2, 1)\| = -4\sqrt{5} \approx -8.944\)
Notice that the true direction from \((2, 1)\) directly to the minimum \((0, 0)\) is proportional to \((-2, -1)\), not \((-1, -2)\)—so the steepest local descent vector misses the origin because the \(y\)-axis is \(4\times\) steeper than the \(x\)-axis.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson explores the gradient vector and directional derivatives, which are central concepts in deep-learning for understanding how functions change in different directions.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;gradient-vector&quot;&gt;Gradient Vector&lt;/h2&gt;

&lt;p&gt;The gradient \(\nabla f\) is a vector composed of the partial derivatives of the function \(f\) with respect to each of its variables. It indicates the direction of the steepest ascent of the function at a given point.&lt;/p&gt;

&lt;h3 id=&quot;definition-and-computation&quot;&gt;Definition and Computation&lt;/h3&gt;

&lt;p&gt;For a function of two variables, \(f(x, y)\), its gradient is:&lt;/p&gt;

\[\nabla f = \begin{pmatrix} \frac{\partial f}{\partial x} \\ \frac{\partial f}{\partial y} \end{pmatrix}\]

&lt;p&gt;For a function of \(n\) variables, \(f(x_1, x_2, \ldots, x_n)\):&lt;/p&gt;

\[\nabla f = \begin{pmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_n} \end{pmatrix}\]

&lt;h3 id=&quot;example-computing-a-gradient&quot;&gt;Example: Computing a Gradient&lt;/h3&gt;

&lt;p&gt;For \(f(x, y) = x^2 + 3xy + y^2\):&lt;/p&gt;

&lt;p&gt;\(\frac{\partial f}{\partial x} = 2x + 3y\)
\(\frac{\partial f}{\partial y} = 3x + 2y\)&lt;/p&gt;

&lt;p&gt;Therefore: \(\nabla f = \begin{pmatrix} 2x + 3y \\ 3x + 2y \end{pmatrix}\)&lt;/p&gt;

&lt;p&gt;At the point \((1, 2)\): \(\nabla f(1, 2) = \begin{pmatrix} 2(1) + 3(2) \\ 3(1) + 2(2) \end{pmatrix} = \begin{pmatrix} 8 \\ 7 \end{pmatrix}\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;directional-derivatives&quot;&gt;Directional Derivatives&lt;/h2&gt;

&lt;p&gt;The &lt;strong&gt;directional derivative&lt;/strong&gt; measures the rate of change of \(f\) when we move in any chosen direction \(\mathbf{u}\). Here \(\mathbf{u}\) must be a unit vector (length 1).&lt;/p&gt;

&lt;h3 id=&quot;definition&quot;&gt;Definition&lt;/h3&gt;

&lt;p&gt;For a function \(f(\mathbf{x})\) and unit vector \(\mathbf{u} = \langle u_1, u_2, \ldots, u_n \rangle\):&lt;/p&gt;

\[D_{\mathbf{u}}f(\mathbf{x}) = \nabla f(\mathbf{x}) \cdot \mathbf{u} = \sum_{i=1}^{n} \frac{\partial f}{\partial x_i} u_i\]

&lt;h3 id=&quot;geometric-interpretation&quot;&gt;Geometric Interpretation&lt;/h3&gt;

&lt;p&gt;The directional derivative can be written as:&lt;/p&gt;

\[D_{\mathbf{u}}f = \lvert \nabla f \rvert \cos \theta\]

&lt;p&gt;where \(\theta\) is the angle between \(\nabla f\) and \(\mathbf{u}\), and \(\lvert \nabla f \rvert\) is the magnitude of the gradient.&lt;/p&gt;

&lt;h3 id=&quot;example-computing-directional-derivatives&quot;&gt;Example: Computing Directional Derivatives&lt;/h3&gt;

&lt;p&gt;Using our previous example \(f(x, y) = x^2 + 3xy + y^2\) at point \((1, 2)\) where \(\nabla f(1, 2) = \begin{pmatrix} 8 \\ 7 \end{pmatrix}\):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Direction 1:&lt;/strong&gt; \(\mathbf{u}_1 = \begin{pmatrix} 1 \\ 0 \end{pmatrix}\) (positive x-direction)
\(D_{\mathbf{u}_1}f(1, 2) = 8 \cdot 1 + 7 \cdot 0 = 8\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Direction 2:&lt;/strong&gt; \(\mathbf{u}_2 = \begin{pmatrix} 0 \\ 1 \end{pmatrix}\) (positive y-direction)
\(D_{\mathbf{u}_2}f(1, 2) = 8 \cdot 0 + 7 \cdot 1 = 7\)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Direction 3:&lt;/strong&gt; \(\mathbf{u}_3 = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 \\ 1 \end{pmatrix}\) (45° diagonal)
\(D_{\mathbf{u}_3}f(1, 2) = 8 \cdot \frac{1}{\sqrt{2}} + 7 \cdot \frac{1}{\sqrt{2}} = \frac{15}{\sqrt{2}} \approx 10.61\)&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;maximum-and-minimum-rates-of-change&quot;&gt;Maximum and Minimum Rates of Change&lt;/h2&gt;

&lt;h3 id=&quot;key-properties&quot;&gt;Key Properties&lt;/h3&gt;

&lt;p&gt;From the formula \(D_{\mathbf{u}}f = \lvert \nabla f \rvert \cos \theta\), we can determine:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Maximum Rate of Change&lt;/strong&gt;: Occurs when \(\cos \theta = 1\) (i.e., \(\theta = 0°\))
    &lt;ul&gt;
      &lt;li&gt;Direction: \(\mathbf{u} = \frac{\nabla f}{\lvert \nabla f \rvert}\) (same direction as gradient)&lt;/li&gt;
      &lt;li&gt;Maximum rate: \(D_{\max}f = \lvert \nabla f \rvert\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Minimum Rate of Change&lt;/strong&gt;: Occurs when \(\cos \theta = -1\) (i.e., \(\theta = 180°\))
    &lt;ul&gt;
      &lt;li&gt;Direction: \(\mathbf{u} = -\frac{\nabla f}{\lvert \nabla f \rvert}\) (opposite to gradient)&lt;/li&gt;
      &lt;li&gt;Minimum rate: \(D_{\min}f = -\lvert \nabla f \rvert\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Zero Rate of Change&lt;/strong&gt;: Occurs when \(\cos \theta = 0\) (i.e., \(\theta = 90°\))
    &lt;ul&gt;
      &lt;li&gt;Direction: Any vector perpendicular to \(\nabla f\)&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;summary-of-gradient-properties&quot;&gt;Summary of Gradient Properties&lt;/h3&gt;

&lt;ul&gt;
  &lt;li&gt;The gradient \(\nabla f\) points in the direction of &lt;strong&gt;steepest increase&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;The direction \(-\nabla f\) points in the direction of &lt;strong&gt;steepest decrease&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;The magnitude \(\lvert \nabla f \rvert\) gives the &lt;strong&gt;maximum rate of change&lt;/strong&gt;&lt;/li&gt;
  &lt;li&gt;When \(\nabla f = \mathbf{0}\), the point is a &lt;strong&gt;critical point&lt;/strong&gt; (potential optimum)&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;relation-to-level-curves&quot;&gt;Relation to Level Curves&lt;/h2&gt;

&lt;p&gt;At any point on a level curve \(f(x, y) = c\), the gradient vector \(\nabla f\) is &lt;strong&gt;orthogonal (perpendicular)&lt;/strong&gt; to the tangent line of the level curve at that point.&lt;/p&gt;

&lt;h3 id=&quot;why-this-matters&quot;&gt;Why This Matters&lt;/h3&gt;

&lt;p&gt;This orthogonality property is fundamental because:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Level curves represent constant function values&lt;/strong&gt;: Moving along a level curve doesn’t change the function value, so the directional derivative is zero.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Gradient points to steepest increase&lt;/strong&gt;: The direction that increases the function value most rapidly must be perpendicular to the direction that doesn’t change it at all.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Deep Learning insight&lt;/strong&gt;: To find extrema, we look for points where the gradient is zero (critical points) or where the gradient is perpendicular to the constraint boundary.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;applications-in-deep-learning&quot;&gt;Applications in Deep Learning&lt;/h3&gt;

&lt;p&gt;Understanding gradients and directional derivatives is crucial for:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Descent&lt;/strong&gt;: Moving in the direction \(-\nabla f\) to minimize \(f\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Ascent&lt;/strong&gt;: Moving in the direction \(+\nabla f\) to maximize \(f\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Constrained Deep Learning&lt;/strong&gt;: Using the relationship between gradients and level curves&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Convergence Analysis&lt;/strong&gt;: Understanding when algorithms will converge to optimal solutions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Step Size Selection&lt;/strong&gt;: Determining how far to move in the gradient direction&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The gradient provides both the direction to move and information about how quickly the function is changing, making it the foundation for most deep-learning algorithms.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Directional Derivatives&lt;/td&gt;
          &lt;td&gt;What’s the slope in any direction?](https://www.youtube.com/watch?v=GJODOGq7cAY) — Dr. Trefor Bazett, English. The directional derivative is the slope in a chosen direction, and the gradient is the direction of steepest ascent.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=rh885pI4lPA&quot;&gt;MaDL - Vector Calculus&lt;/a&gt; — Tübingen Machine Learning, English. Puts the gradient, directional derivative, and Jacobian in the notation this course uses for vector-valued maps.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Continuity vs Partial Derivatives vs Differentiability&lt;/td&gt;
          &lt;td&gt;My Favorite Multivariable Function](https://www.youtube.com/watch?v=6Wi1kT9kR1M) — Dr. Trefor Bazett, English. Shows why a gradient can exist in a weaker sense than full differentiability, which is the distinction the level-curve section relies on.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01-02 Derivatives and Multivariable Calculus</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_01_02_Derivatives_and_Multivariable_Calculus/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_01_02_Derivatives_and_Multivariable_Calculus</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;When a neural network misclassifies an X-ray, a single scalar loss number has to send bespoke blame signals back to millions of weights simultaneously. Multivariable calculus—partial derivatives, Jacobians, Hessians, and the multivariable chain rule—is the exact bookkeeping system that makes that feat possible.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-multivariable-calculus-for-neural-optimization&quot;&gt;Key ideas: Multivariable Calculus for Neural Optimization&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Partial Derivatives (Axis-Aligned Sensitivities)&lt;/strong&gt;: Isolate the rate of change of a loss \(f(x_1, \dots, x_n)\) with respect to one coordinate while holding all other parameters frozen.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Gradient &amp;amp; Jacobian (First-Order Linearization)&lt;/strong&gt;: Package all partial derivatives of a scalar function into a gradient vector \(\nabla f\), or of a vector-valued layer \(h: \mathbb{R}^n \to \mathbb{R}^m\) into an \(m \times n\) Jacobian matrix \(J_h\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;The Hessian Matrix (Second-Order Curvature)&lt;/strong&gt;: Collects all second partial derivatives \(H_{ij} = \frac{\partial^2 f}{\partial x_i \partial x_j}\), distinguishing strict local minima (positive definite), maxima (negative definite), and saddle points (indefinite)—which dominate high-dimensional neural loss landscapes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Multivariable Chain Rule (The Core of Backpropagation)&lt;/strong&gt;: Composes local derivatives along every path in a computational graph, summing contributions whenever one variable feeds into multiple downstream nodes.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-gradient-hessian-and-chain-rule-on-a-coupled-loss&quot;&gt;Worked example: Gradient, Hessian, and Chain Rule on a Coupled Loss&lt;/h3&gt;

&lt;p&gt;Consider the two-variable objective \(f(x, y) = x^2 y + 3y^2\) along the parameterized path \(x(t) = 2t\), \(y(t) = t + 1\), evaluated at \(t = 1\) (so \(x = 2, y = 2\)).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Gradient Vector \(\nabla f(x, y)\)&lt;/strong&gt;:
\(\frac{\partial f}{\partial x} = 2xy, \qquad \frac{\partial f}{\partial y} = x^2 + 6y\)
At \((x, y) = (2, 2)\):
\(\nabla f(2, 2) = \begin{bmatrix} 2(2)(2) \\ 2^2 + 6(2) \end{bmatrix} = \begin{bmatrix} 8 \\ 16 \end{bmatrix}\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compute the Hessian Matrix \(H_f(x, y)\)&lt;/strong&gt;:
\(\frac{\partial^2 f}{\partial x^2} = 2y, \quad \frac{\partial^2 f}{\partial x \partial y} = 2x, \quad \frac{\partial^2 f}{\partial y^2} = 6\)
At \((2, 2)\):
\(H_f(2, 2) = \begin{bmatrix} 4 &amp;amp; 4 \\ 4 &amp;amp; 6 \end{bmatrix}\)
Check definiteness via leading principal minors: \(D_1 = 4 &amp;gt; 0\) and \(D_2 = (4)(6) - (4)(4) = 24 - 16 = 8 &amp;gt; 0\). Thus \(H_f(2, 2)\) is strictly positive definite (locally bowl-shaped).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Apply the Multivariable Chain Rule for \(\frac{df}{dt}\) at \(t = 1\)&lt;/strong&gt;:
We have \(\frac{dx}{dt} = 2\) and \(\frac{dy}{dt} = 1\). Therefore:
\(\frac{df}{dt}\Big|_{t=1} = \frac{\partial f}{\partial x}\frac{dx}{dt} + \frac{\partial f}{\partial y}\frac{dy}{dt} = (8)(2) + (16)(1) = 16 + 16 = 32\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Independent Substitution Check&lt;/strong&gt;:
Substitute directly: \(f(t) = (2t)^2(t+1) + 3(t+1)^2 = 4t^3 + 7t^2 + 6t + 3\). Differentiating gives \(f&apos;(t) = 12t^2 + 14t + 6\), and at \(t = 1\): \(f&apos;(1) = 12 + 14 + 6 = 32\). Exact match!&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson covers derivatives and essential multivariable calculus concepts that form the foundation for deep-learning theory and algorithms.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;derivatives-and-rate-of-change&quot;&gt;Derivatives and Rate of Change&lt;/h2&gt;

&lt;p&gt;The derivative of a single variable function represents its instantaneous rate of change, which is fundamental to understanding how functions behave locally.&lt;/p&gt;

&lt;h3 id=&quot;basic-derivative-concepts&quot;&gt;Basic Derivative Concepts&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Slope between two points:&lt;/strong&gt;&lt;/p&gt;

\[\text{Slope} = \frac{y_2 - y_1}{x_2 - x_1}\]

&lt;p&gt;&lt;strong&gt;Derivative (instantaneous rate of change):&lt;/strong&gt;&lt;/p&gt;

\[f&apos;(x_0) = \lim_{x_1 \to x_0} \frac{f(x_1) - f(x_0)}{x_1 - x_0} = \lim_{\Delta x \to 0} \frac{f(x_0 + \Delta x) - f(x_0)}{\Delta x}\]

&lt;p&gt;The derivative tells us how quickly the function is changing at any given point, which is essential for finding optimal points where the rate of change is zero.&lt;/p&gt;

&lt;h3 id=&quot;level-curves-of-functions&quot;&gt;Level Curves of Functions&lt;/h3&gt;

&lt;p&gt;Level curves are a fundamental concept in multivariable calculus used to visualize functions of two variables, typically denoted as \(f(x, y)\). They provide a way to represent a 3D surface in a 2D plane.&lt;/p&gt;

&lt;p&gt;A &lt;strong&gt;level curve&lt;/strong&gt; of a function \(f(x, y)\) is the set of all points \((x, y)\) in the domain of \(f\) where the function takes a constant value:&lt;/p&gt;

\[f(x, y) = c\]

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;For \(f(x, y) = x^2 + y^2\), the level curves are circles: \(x^2 + y^2 = c\)&lt;/li&gt;
  &lt;li&gt;For \(f(x, y) = x + y\), the level curves are parallel lines: \(x + y = c\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Level curves help us understand:&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;The topography of the function&lt;/li&gt;
  &lt;li&gt;Directions of steepest ascent and descent&lt;/li&gt;
  &lt;li&gt;Locations of potential optima&lt;/li&gt;
&lt;/ol&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;multivariable-calculus-key-concepts&quot;&gt;Multivariable Calculus Key Concepts&lt;/h2&gt;

&lt;h3 id=&quot;partial-derivatives&quot;&gt;Partial Derivatives&lt;/h3&gt;

&lt;p&gt;For a function \(f(x_1, x_2, \ldots, x_n)\), the &lt;strong&gt;partial derivative&lt;/strong&gt; with respect to \(x_i\) is:&lt;/p&gt;

\[\frac{\partial f}{\partial x_i} = \lim_{h \to 0} \frac{f(x_1, \ldots, x_i + h, \ldots, x_n) - f(x_1, \ldots, x_i, \ldots, x_n)}{h}\]

&lt;p&gt;This measures how \(f\) changes when only \(x_i\) varies while all other variables remain fixed.&lt;/p&gt;

&lt;h3 id=&quot;gradient-vector&quot;&gt;Gradient Vector&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;gradient&lt;/strong&gt; is a vector composed of all partial derivatives:&lt;/p&gt;

\[\nabla f(\mathbf{x}) = \begin{pmatrix} \frac{\partial f}{\partial x_1} \\ \frac{\partial f}{\partial x_2} \\ \vdots \\ \frac{\partial f}{\partial x_n} \end{pmatrix}\]

&lt;p&gt;The gradient points in the direction of steepest increase of the function and is perpendicular to level curves.&lt;/p&gt;

&lt;h3 id=&quot;hessian-matrix&quot;&gt;Hessian Matrix&lt;/h3&gt;

&lt;p&gt;The &lt;strong&gt;Hessian matrix&lt;/strong&gt; contains all second-order partial derivatives:&lt;/p&gt;

\[\nabla^2 f(\mathbf{x}) = \mathbf{H} = \begin{pmatrix} 
\frac{\partial^2 f}{\partial x_1^2} &amp;amp; \frac{\partial^2 f}{\partial x_1 \partial x_2} &amp;amp; \cdots &amp;amp; \frac{\partial^2 f}{\partial x_1 \partial x_n} \\
\frac{\partial^2 f}{\partial x_2 \partial x_1} &amp;amp; \frac{\partial^2 f}{\partial x_2^2} &amp;amp; \cdots &amp;amp; \frac{\partial^2 f}{\partial x_2 \partial x_n} \\
\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \\
\frac{\partial^2 f}{\partial x_n \partial x_1} &amp;amp; \frac{\partial^2 f}{\partial x_n \partial x_2} &amp;amp; \cdots &amp;amp; \frac{\partial^2 f}{\partial x_n^2}
\end{pmatrix}\]

&lt;p&gt;The Hessian provides information about the curvature of the function and is crucial for:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;Determining the nature of critical points (minimum, maximum, or saddle point)&lt;/li&gt;
  &lt;li&gt;Second-order deep-learning methods like Newton’s method&lt;/li&gt;
&lt;/ul&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;chain-rule-for-multivariable-functions&quot;&gt;Chain Rule for Multivariable Functions&lt;/h2&gt;

&lt;p&gt;The chain rule is fundamental for computing derivatives of composite functions, which frequently appear in deep-learning problems.&lt;/p&gt;

&lt;h3 id=&quot;basic-chain-rule&quot;&gt;Basic Chain Rule&lt;/h3&gt;

&lt;p&gt;For a function \(z = f(x, y)\) where \(x = g(t)\) and \(y = h(t)\):&lt;/p&gt;

\[\frac{dz}{dt} = \frac{\partial f}{\partial x} \frac{dx}{dt} + \frac{\partial f}{\partial y} \frac{dy}{dt}\]

&lt;h3 id=&quot;general-chain-rule&quot;&gt;General Chain Rule&lt;/h3&gt;

&lt;p&gt;For \(z = f(x_1, x_2, \ldots, x_n)\) where each \(x_i = x_i(t_1, t_2, \ldots, t_m)\):&lt;/p&gt;

\[\frac{\partial z}{\partial t_j} = \sum_{i=1}^{n} \frac{\partial f}{\partial x_i} \frac{\partial x_i}{\partial t_j}\]

&lt;h3 id=&quot;applications-in-deep-learning&quot;&gt;Applications in Deep Learning&lt;/h3&gt;

&lt;p&gt;The chain rule is essential for:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Gradient Computation&lt;/strong&gt;: Computing gradients of composite objective functions&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Constraint Handling&lt;/strong&gt;: Dealing with constraints that are functions of other variables&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Algorithm Implementation&lt;/strong&gt;: Backpropagation in neural networks and automatic differentiation&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Sensitivity Analysis&lt;/strong&gt;: Understanding how changes in parameters affect optimal solutions&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;example-deep-learning-with-constraints&quot;&gt;Example: Deep Learning with Constraints&lt;/h3&gt;

&lt;p&gt;Consider minimizing \(f(x, y) = x^2 + y^2\) subject to \(g(x, y) = x + y - 1 = 0\).&lt;/p&gt;

&lt;p&gt;Using the constraint to eliminate one variable: \(y = 1 - x\), so we minimize:
\(h(x) = f(x, 1-x) = x^2 + (1-x)^2\)&lt;/p&gt;

&lt;p&gt;Using the chain rule:
\(h&apos;(x) = \frac{\partial f}{\partial x} \cdot 1 + \frac{\partial f}{\partial y} \cdot \frac{d(1-x)}{dx} = 2x + 2(1-x)(-1) = 4x - 2\)&lt;/p&gt;

&lt;p&gt;Setting \(h&apos;(x) = 0\) gives \(x = 1/2\), so the optimal point is \((1/2, 1/2)\).&lt;/p&gt;

&lt;p&gt;This demonstrates how multivariable calculus concepts work together to solve deep-learning problems systematically.&lt;/p&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [The paradox of the derivative&lt;/td&gt;
          &lt;td&gt;Chapter 2, Essence of calculus](https://www.youtube.com/watch?v=9vKqVkMQHKk) — 3Blue1Brown, English. The one-variable derivative the lesson uses as the rate of change.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;https://www.youtube.com/watch?v=EoEV5-_mLeM&quot;&gt;What are derivatives in 3D? Intro to Partial Derivatives&lt;/a&gt; — Dr. Trefor Bazett, English. Partial derivatives are the coordinate-wise rates the multivariable section adds once the input is a vector.&lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Visualizing the chain rule and product rule&lt;/td&gt;
          &lt;td&gt;Chapter 4, Essence of calculus](https://www.youtube.com/watch?v=YG15m2VwSjA) — 3Blue1Brown, English. The chain rule visualized here is the one-variable case; the lesson’s multivariable chain rule is the same product of derivatives along a composition.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 
 <entry>
   <title>00-01-01 Continuity and Uniform Continuity</title>
   <link href="https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_01_01_Continuity_and_Uniform_Continuity/"/>
   <updated>2021-01-01T00:00:00+00:00</updated>
   <id>https://deep-learning-self-learning.pages.dev/contents/en/chapter00/00_01_01_Continuity_and_Uniform_Continuity</id>
   <content type="html">&lt;blockquote&gt;
  &lt;p&gt;&lt;em&gt;Why can a single imperceptible pixel perturbation fool a high-accuracy image classifier into calling a panda a gibbon, or cause a GAN discriminator to explode? The answer lies not just in whether a network is continuous, but in how tightly its worst-case sensitivity—its Lipschitz constant—is controlled across the entire input space.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2 id=&quot;key-ideas-continuity-uniformity-and-lipschitz-control&quot;&gt;Key ideas: Continuity, Uniformity, and Lipschitz Control&lt;/h2&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Pointwise Continuity (Local Predictability)&lt;/strong&gt;: Guarantees that around a specific input \(c\), sufficiently small perturbations stay close in output space, though the required tolerance \(\delta(\varepsilon, c)\) may shrink arbitrarily at other points.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Uniform Continuity (Global Consistency)&lt;/strong&gt;: Strengthens continuity by demanding a single \(\delta(\varepsilon)\) that works simultaneously everywhere on the domain, preventing arbitrarily steep cliffs from forming as you move across the space.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Lipschitz Continuity (Quantitative Slope Bound)&lt;/strong&gt;: Caps the maximum amplification ratio \(\lvert f(x) - f(y)\rvert / \lvert x - y\rvert \leq L\), which directly governs adversarial robustness, Wasserstein GAN constraints, and safe gradient descent step sizes (\(\eta &amp;lt; 2/L\)).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Compactness &amp;amp; Heine–Cantor Bridge&lt;/strong&gt;: Explains why continuous functions on closed, bounded domains (like normalized image hypercubes \([0, 1]^d\)) are automatically uniformly continuous, giving theoretical safety on bounded feature spaces.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;worked-example-computing-exact-lipschitz-bounds-vs-failure-of-uniform-continuity&quot;&gt;Worked example: Computing Exact Lipschitz Bounds vs. Failure of Uniform Continuity&lt;/h3&gt;

&lt;p&gt;Compare two functions on the open interval \(A = (0, 1]\): \(f(x) = x^2\) and \(g(x) = \frac{1}{x}\).&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Checking Lipschitz Continuity of \(f(x) = x^2\) on \((0, 1]\)&lt;/strong&gt;:
For any \(x, y \in (0, 1]\), factor the difference:
\(\lvert f(x) - f(y)\rvert = \lvert x^2 - y^2\rvert = \lvert x + y\rvert \cdot \lvert x - y\rvert\)
Since \(x \leq 1\) and \(y \leq 1\), we have \(\lvert x + y\rvert \leq 2\). Thus:
\(\lvert f(x) - f(y)\rvert \leq 2\lvert x - y\rvert\)
So \(f\) is \(2\)-Lipschitz on \((0, 1]\), and hence uniformly continuous with \(\delta = \varepsilon / 2\).&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Concrete Numerical Verification for \(f\)&lt;/strong&gt;:
Take \(\varepsilon = 0.1\), so \(\delta = 0.05\). Pick \(x = 0.99, y = 0.96\) (distance \(0.03 &amp;lt; 0.05\)):
\(\lvert 0.99^2 - 0.96^2\rvert = \lvert 0.9801 - 0.9216\rvert = 0.0585 &amp;lt; 0.1\)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Why \(g(x) = 1/x\) Fails Uniform Continuity on \((0, 1]\)&lt;/strong&gt;:
Fix \(\varepsilon = 1\). For any candidate \(\delta &amp;gt; 0\), choose an integer \(n\) large enough that \(\frac{1}{n} &amp;lt; \delta\), and set \(x = \frac{1}{n}, y = \frac{1}{2n}\).
    &lt;ul&gt;
      &lt;li&gt;Input distance: \(\lvert x - y\rvert = \frac{1}{2n} &amp;lt; \delta\).&lt;/li&gt;
      &lt;li&gt;Output jump: \(\lvert g(x) - g(y)\rvert = \lvert n - 2n\rvert = n \geq 1 = \varepsilon\).
For example, with \(n = 100\): \(x = 0.01, y = 0.005\) are only \(0.005\) apart, yet \(\lvert g(0.01) - g(0.005)\rvert = \lvert 100 - 200\rvert = 100\). No single \(\delta\) can tame this blow-up near \(0\)—the exact analytical pathology behind exploding gradients near singularities.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This lesson introduces the fundamental concepts of continuity and uniform continuity, which are essential for understanding the behavior of functions in deep-learning.&lt;/p&gt;

&lt;hr /&gt;

&lt;h2 id=&quot;continuity-and-uniform-continuity&quot;&gt;Continuity and Uniform Continuity&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Continuity&lt;/strong&gt; and &lt;strong&gt;Uniform Continuity&lt;/strong&gt; are fundamental concepts that describe the behavior of functions, particularly concerning their “smoothness” or “predictability.” While closely related, they capture distinct properties, with uniform continuity being a stronger condition than mere continuity.&lt;/p&gt;

&lt;h3 id=&quot;definition-of-continuity&quot;&gt;Definition of Continuity&lt;/h3&gt;

&lt;p&gt;A function \(f: A \to \mathbb{R}\) is said to be &lt;strong&gt;continuous at a point&lt;/strong&gt; \(c \in A\) if, for every positive real number \(\varepsilon &amp;gt; 0\), there exists a positive real number \(\delta &amp;gt; 0\) such that for all \(x \in A\), if&lt;/p&gt;

\[\lvert x - c \rvert &amp;lt; \delta\]

&lt;p&gt;then&lt;/p&gt;

\[\lvert f(x) - f(c) \rvert &amp;lt; \varepsilon\]

&lt;p&gt;Intuitively, it means that for any desired level of precision \(\varepsilon\) in the output \(f(x)\), we can find a sufficiently small interval around \(c\) (of width \(2\delta\)) such that all \(x\) values within this interval map to \(f(x)\) values within an \(\varepsilon\)-interval around \(f(c)\). The crucial aspect here is that the choice of \(\delta\) generally depends not only on \(\varepsilon\) but also on the specific point \(c\).&lt;/p&gt;

&lt;p&gt;A function is &lt;strong&gt;continuous on a set&lt;/strong&gt; \(A\) if it is continuous at every point \(c \in A\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Examples of continuous functions&lt;/strong&gt; include all polynomials (e.g., \(f(x) = x^2 + 3x - 1\)), trigonometric functions like \(\sin(x)\) and \(\cos(x)\), and exponential functions \(e^x\) on their respective domains.&lt;/p&gt;

&lt;h3 id=&quot;definition-of-uniform-continuity&quot;&gt;Definition of Uniform Continuity&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Uniform Continuity&lt;/strong&gt;, on the other hand, imposes a more stringent condition. A function \(f: A \to \mathbb{R}\) is said to be &lt;strong&gt;uniformly continuous on a set&lt;/strong&gt; \(A\) if, for every positive real number \(\varepsilon &amp;gt; 0\), there exists a positive real number \(\delta &amp;gt; 0\) such that for all \(x, y \in A\), if&lt;/p&gt;

\[\lvert x - y \rvert &amp;lt; \delta\]

&lt;p&gt;then&lt;/p&gt;

\[\lvert f(x) - f(y) \rvert &amp;lt; \varepsilon\]

&lt;p&gt;The &lt;strong&gt;key distinction&lt;/strong&gt; from point-wise continuity lies in the order of quantifiers: for &lt;strong&gt;uniform&lt;/strong&gt; continuity, the \(\delta\) depends &lt;em&gt;only&lt;/em&gt; on \(\varepsilon\) and is independent of the specific points \(x\) and \(y\) in the domain.&lt;/p&gt;

&lt;h3 id=&quot;definition-of-lipschitz-continuity&quot;&gt;Definition of Lipschitz Continuity&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Lipschitz Continuity&lt;/strong&gt; provides an even more specific and quantitative notion of continuity. A function \(f: A \to \mathbb{R}\) is said to be &lt;strong&gt;Lipschitz continuous&lt;/strong&gt; (or &lt;strong&gt;L-Lipschitz&lt;/strong&gt;) on a set \(A\) if there exists a constant \(L \geq 0\) such that for all \(x, y \in A\):&lt;/p&gt;

\[\lvert f(x) - f(y) \rvert \leq L \lvert x - y \rvert\]

&lt;p&gt;The smallest such constant \(L\) is called the &lt;strong&gt;Lipschitz constant&lt;/strong&gt; or &lt;strong&gt;Lipschitz modulus&lt;/strong&gt; of \(f\).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Key Properties of Lipschitz Continuity:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Bounded Rate of Change&lt;/strong&gt;: The Lipschitz condition ensures that the function cannot change faster than a linear rate determined by \(L\).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Uniform Continuity&lt;/strong&gt;: Every Lipschitz continuous function is uniformly continuous (choose \(\delta = \varepsilon/L\) for \(L &amp;gt; 0\)).&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;strong&gt;Almost Everywhere Differentiability&lt;/strong&gt;: Lipschitz continuous functions are differentiable almost everywhere, and where the derivative exists, \(\lvert f&apos;(x) \rvert \leq L\).&lt;/p&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Examples:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;\(f(x) = \lvert x \rvert\) is 1-Lipschitz on \(\mathbb{R}\)&lt;/li&gt;
  &lt;li&gt;\(f(x) = \sin(x)\) is 1-Lipschitz on \(\mathbb{R}\) (since \(\lvert \cos(x) \rvert \leq 1\))&lt;/li&gt;
  &lt;li&gt;\(f(x) = x^2\) is not Lipschitz on \(\mathbb{R}\) but is Lipschitz on any bounded interval&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;key-differences-and-hierarchy&quot;&gt;Key Differences and Hierarchy&lt;/h3&gt;

&lt;p&gt;The three types of continuity form a hierarchy of increasingly strong conditions:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Continuity ⊆ Uniform Continuity ⊆ Lipschitz Continuity&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;Point-wise vs Global&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Continuity&lt;/strong&gt;: Local property (checked at each point)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Uniform Continuity&lt;/strong&gt;: Global property of the entire function&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Lipschitz Continuity&lt;/strong&gt;: Global property with quantitative bounds&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Choice of \(\delta\)&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Continuity&lt;/strong&gt;: \(\delta\) can depend on both \(\varepsilon\) and the specific point \(c\)&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Uniform Continuity&lt;/strong&gt;: \(\delta\) depends only on \(\varepsilon\), working for all points simultaneously&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Lipschitz Continuity&lt;/strong&gt;: \(\delta = \varepsilon/L\) provides explicit relationship&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Rate of Change Control&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;&lt;strong&gt;Continuity&lt;/strong&gt;: No control over rate of change&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Uniform Continuity&lt;/strong&gt;: Ensures bounded variation over small intervals&lt;/li&gt;
      &lt;li&gt;&lt;strong&gt;Lipschitz Continuity&lt;/strong&gt;: Provides explicit linear bound on rate of change&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Strength Relationships&lt;/strong&gt;:
    &lt;ul&gt;
      &lt;li&gt;Every Lipschitz continuous function is uniformly continuous&lt;/li&gt;
      &lt;li&gt;Every uniformly continuous function is continuous&lt;/li&gt;
      &lt;li&gt;The converses are not generally true&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id=&quot;detailed-examples-and-comparisons&quot;&gt;Detailed Examples and Comparisons&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Example 1: \(f(x) = x^2\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;On \(\mathbb{R}\)&lt;/strong&gt;: Continuous but not uniformly continuous (rate of change \(\lvert f&apos;(x) \rvert = 2\lvert x \rvert\) is unbounded)&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;On \([0,1]\)&lt;/strong&gt;: Continuous, uniformly continuous, and Lipschitz with \(L = 2\)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example 2: \(f(x) = \sin(x)\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;On \(\mathbb{R}\)&lt;/strong&gt;: Continuous, uniformly continuous, and 1-Lipschitz (since \(\lvert \cos(x) \rvert \leq 1\))&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example 3: \(f(x) = \lvert x \rvert\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;On \(\mathbb{R}\)&lt;/strong&gt;: Continuous, uniformly continuous, and 1-Lipschitz&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Note&lt;/strong&gt;: Not differentiable at \(x = 0\), but still Lipschitz&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Example 4: \(f(x) = \sqrt{x}\)&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;On \([0,1]\)&lt;/strong&gt;: Continuous and uniformly continuous, but not Lipschitz (derivative unbounded near \(x = 0\))&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;On \([a,1]\) for \(a &amp;gt; 0\)&lt;/strong&gt;: Lipschitz with \(L = 1/(2\sqrt{a})\)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;video-tham-khảo&quot;&gt;Video tham khảo&lt;/h2&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;strong&gt;xem trước&lt;/strong&gt; [Continuity at a point&lt;/td&gt;
          &lt;td&gt;Limits and continuity&lt;/td&gt;
          &lt;td&gt;AP Calculus AB&lt;/td&gt;
          &lt;td&gt;Khan Academy](https://www.youtube.com/watch?v=3KMqU5j7irw) — Khan Academy, English. Continuity at a single point is the definition the lesson starts from.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Limits, L’Hôpital’s rule, and epsilon delta definitions&lt;/td&gt;
          &lt;td&gt;Chapter 7, Essence of calculus](https://www.youtube.com/watch?v=kfF40MiS7zA) — 3Blue1Brown, English. The epsilon-delta language in the second half is the same language used to upgrade pointwise continuity to uniform continuity.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;table&gt;
      &lt;tbody&gt;
        &lt;tr&gt;
          &lt;td&gt;[Real Analysis&lt;/td&gt;
          &lt;td&gt;Intro to uniform continuity.](https://www.youtube.com/watch?v=gioaYgOQ3AQ) — Michael Penn, English. This is the uniform-continuity strengthening itself: one delta that works on a whole set, which is the lesson’s second definition.&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/li&gt;
&lt;/ul&gt;
</content>
 </entry>
 

</feed>
